SLYZ

蜕变

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

  记录下在完成cs231n的Assignment1过程中的一些东西。

1. scores是一个N*C的array,N是训练样本个数,C是标签。y是(N,)的数组,取出每一个样本对应的score,可以用以下的语法:

correct_score = scores[range(N), y]

2. numpy.random.choice

>>> np.random.choice(5, 3)
array([0, 3, 4])
>>> #This is equivalent to np.random.randint(0,5,3)

3. numpy.linalg.norm 计算范数的函数,包括二范数,核范数等等

4. numpy.array_split 把一个数组等分成几个小数组

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

5. numpy里面有很多选择沿某个轴操作的函数,比如numpy.sum,numpy.argmax等函数。axis=0,表示函数操作沿列(col)进行,得到一个行向量;

axis=1,表示函数操作沿着行(row)进行,得到一个列向量。

>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

6. numpy.hstack, numpy.vstack, numpy.stack以及numpy.concatenate  把两个或者多个数组沿某一个轴进行级联。

7. 说下最让我惊讶的python的Broadcasting。Broadcating是说两个不同维度的数组也能进行加减乘除等操作运算,当然维度不同也是有一定限制的,只是放宽了一定限制。

官网上是这么说的:When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

  1. they are equal, or
  2. one of them is 1

举个例子:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])
# Here the newaxis index operator inserts a new axis into a, making it a two-dimensional 4x1 array. Combining the 4x1 array with b, which has shape (3,), yields a 4x3 array.

 numpy还有其他一些好玩的trick,参见http://anie.me/numpy-tricks/

8. np.newaxis。新增一个维度。

9. np.flatten返回对象的一个拷贝,np.ravel返回的是原对象的视图,更改之,会更改原对象

 

 

 

posted on 2016-10-25 09:30  SLYZ  阅读(224)  评论(0编辑  收藏  举报