搭建模型第一步:你须要预习的NumPy基础都在这了

选自 Numpy,机器之心编译。html

NumPy 是一个为 Python 提供高性能向量、矩阵和高维数据结构的科学计算库。它经过 C 和 Fortran 实现,所以用向量和矩阵创建方程并实现数值计算有很是好的性能。NumPy 基本上是全部使用 Python 进行数值计算的框架和包的基础,例如 TensorFlow 和 PyTorch,构建机器学习模型最基础的内容就是学会使用 NumPy 搭建计算过程。


基础知识数组

NumPy 主要的运算对象为同质的多维数组,即由同一类型元素(通常是数字)组成的表格,且全部元素经过正整数元组进行索引。在 NumPy 中,维度 (dimension) 也被称之为轴线(axes)。bash

好比坐标点 [1, 2, 1] 有一个轴线。这个轴上有 3 个点,因此咱们说它的长度(length)为 3。而以下数组(array)有 2 个轴线,长度一样为 3。数据结构

[[ 1., 0., 0.],
[ 0., 1., 2.]]
复制代码

NumPy 的数组类(array class)叫作 ndarray,同时咱们也常称其为数组(array)。注意 numpy.array 和标准 Python 库中的类 array.array 是不一样的。标准 Python 库中的类 array.array 只处理一维的数组,提供少许的功能。ndarray 还具备以下不少重要的属性:框架

  • ndarray.ndim:显示数组的轴线数量(或维度)。
  • ndarray.shape:显示在每一个维度里数组的大小。如 n 行 m 列的矩阵,它的 shape 就是(n,m)。
>>> b = np.array([[1,2,3],[4,5,6]])
>>> b.shape
(2, 3)
复制代码
  • ndarray.size:数组中全部元素的总量,至关于数组的 shape 中全部元素的乘积,例如矩阵的元素总量为行与列的乘积。
>>> b = np.array([[1,2,3],[4,5,6]])
>>> b.size
6
复制代码
  • ndarray.dtype:显示数组元素的类型。Python 中的标准 type 函数一样能够用于显示数组类型,NumPy 有它本身的类型如:numpy.int32, numpy.int16, 和 numpy.float64,其中「int」和「float」表明数据的种类是整数仍是浮点数,「32」和「16」表明这个数组的字节数(存储大小)。
  • ndarray.itemsize:数组中每一个元素的字节存储大小。例如元素类型为 float64 的数组,其 itemsize 为 8(=64/8)。
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<type 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<type 'numpy.ndarray'>
复制代码


建立数组dom

NumPy 有不少种建立数组的方法。好比,你能够用 Python 的列表(list)来建立 NumPy 数组,其中生成的数组元素类型与原序列相同。机器学习

>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int64')
>>> b = np.array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')
复制代码

一个常见的偏差(error)在于调用 array 时使用了多个数值参数,而正确的方法应该是用「[]」来定义一个列表的数值而做为数组的一个参数。ide

>>> a = np.array(1,2,3,4)    # WRONG
>>> a = np.array([1,2,3,4])  # RIGHT
复制代码

array 将序列中的序列转换为二维的数组,序列中的序列中的序列转换为三维数组,以此类推。函数

>>> b = np.array([(1.5,2,3), (4,5,6)])
>>> b
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])
复制代码

数组的类型也能够在建立时指定清楚:布局

>>> b = np.array([(1.5,2,3), (4,5,6)])
>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+0.j]])
复制代码

通常数组的内部元素初始是未知的,但它的大小是已知的。所以,NumPy 提供了一些函数能够建立有初始数值的占位符数组,这样能够减小没必要要的数组增加及运算成本。

函数 zeros 可建立一个内部元素全是 0 的数组,函数 ones 可建立一个内部元素全是 1 的数组,函数 empty 可建立一个初始元素为随机数的数组,具体随机量取决于内存状态。默认状态下,建立数组的数据类型(dtype)通常是 float64。

>>> np.zeros( (3,4) )
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones( (2,3,4), dtype=np.int16 )   # dtype can also be specified
array([[[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]],
       [[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]]], dtype=int16)
>>> np.empty( (2,3) )                    # uninitialized, output may vary
array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
       [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])
复制代码

为了建立数列,NumPy 提供一个与 range 相似的函数来建立数组:arange。

>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )                 # it accepts float arguments
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])
复制代码

当 arange 使用浮点型参数时,由于浮点精度的有限性,arange 不能判断有须要建立的数组多少个元素。在这种状况下,换成 linspace 函数能够更好地肯定区间内到底须要产生多少个数组元素。

>>> from numpy import pi
>>> np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])
>>> x = np.linspace( 0, 2*pi, 100 )        # useful to evaluate function at lots of points
>>> f = np.sin(x)
复制代码

array, zeros, zeros_like, ones, ones_like, empty, empty_like, arange, linspace, numpy.random.rand, numpy.random.randn, fromfunction, fromfile (这些函数也能够建立数组,有时间能够尝试解释)


输出数组

当你输出一个数组时,NumPy 显示这个数组的方式和嵌套列表是类似的。但将数组打印到屏幕须要遵照如下布局:

  • 最后一个轴由左至右打印
  • 倒数第二个轴为从上到下打印
  • 其他的轴都是从上到下打印,且每一块之间都经过一个空行分隔

以下所示,一维数组输出为一行、二维为矩阵、三维为矩阵列表。

>>> a = np.arange(6)                         # 1d array
>>> print(a)
[0 1 2 3 4 5]
>>>
>>> b = np.arange(12).reshape(4,3)           # 2d array
>>> print(b)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
>>>
>>> c = np.arange(24).reshape(2,3,4)         # 3d array
>>> print(c)
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]
 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
复制代码

上述使用的 reshape 函数可指定数组的行列数,并将全部元素按指定的维度数排列,详细介绍请看后面章节。在数组的打印中,若是一个数组所含元素数太大,NumPy 会自动跳过数组的中间部分,只输出两边。

>>> print(np.arange(10000))
[   0    1    2 ..., 9997 9998 9999]
>>>
>>> print(np.arange(10000).reshape(100,100))
[[   0    1    2 ...,   97   98   99]
 [ 100  101  102 ...,  197  198  199]
 [ 200  201  202 ...,  297  298  299]
 ...,
 [9700 9701 9702 ..., 9797 9798 9799]
 [9800 9801 9802 ..., 9897 9898 9899]
 [9900 9901 9902 ..., 9997 9998 9999]]
复制代码

若是想要 NumPy 输出整个数组,你能够用 set_printoptions 改变输出设置。

>>> np.set_printoptions(threshold=np.nan)
复制代码


基础运算

数组中的算术运算通常是元素级的运算,运算结果会产生一个新的数组。以下所示减法、加法、平方、对应元素乘积和逻辑运算都是元素级的操做。

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False])
复制代码

不一样于许多科学计算语言,乘法算子 * 或 multiple 函数在 NumPy 数组中用于元素级的乘法运算,矩阵乘法可用 dot 函数或方法来执行。

>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A*B                         # elementwise product
array([[2, 0],
       [0, 4]])
>>> A.dot(B)                    # matrix product
array([[5, 4],
       [3, 4]])
>>> np.dot(A, B)                # another matrix product
array([[5, 4],
       [3, 4]])
复制代码

有一些操做,如 += 和 *=,其输出结果会改变一个已存在的数组,而不是如上述运算建立一个新数组。

>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
       [3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022  ,  3.72032449,  3.00011437],
       [ 3.30233257,  3.14675589,  3.09233859]])
>>> a += b                  # b is not automatically converted to integer type
Traceback (most recent call last):
  ...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
复制代码

当操做不一样数据类型的数组时,最后输出的数组类型通常会与更广泛或更精准的数组相同(这种行为叫作 Upcasting)。

>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = a+b
>>> c
array([ 1.        ,  2.57079633,  4.14159265])
>>> c.dtype.name
'float64'
>>> d = np.exp(c*1j)
>>> d
array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
       -0.54030231-0.84147098j])
>>> d.dtype.name
'complex128'
复制代码

许多一元运算,如计算数组中全部元素的总和,是属于 ndarray 类的方法。

>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021,  0.34556073,  0.39676747],
       [ 0.53881673,  0.41919451,  0.6852195 ]])
>>> a.sum()
2.5718191614547998
>>> a.min()
0.1862602113776709
>>> a.max()
0.6852195003967595
复制代码

默认状态下,这些运算会把数组视为一个数列而不论它的 shape。然而,若是在指定 axis 参数下,你能够指定针对哪个维度进行运算。以下 axis=0 将针对每个列进行运算,例如 b.sum(axis=0) 将矩阵 b 中每个列的全部元素都相加为一个标量。

>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>
>>> b.sum(axis=0)                            # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1)                            # min of each row
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1)                         # cumulative sum along each row
array([[ 0,  1,  3,  6],
       [ 4,  9, 15, 22],
       [ 8, 17, 27, 38]])
复制代码


索引、截取和迭代

一维数组能够被索引、截取(Slicing)和迭代,就像 Python 列表和元组同样。注意其中 a[0:6:2] 表示从第 1 到第 6 个元素,并对每两个中的第二个元素进行操做。

>>> a = np.arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
>>> a[ : :-1]                                 # reversed a
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
>>> for i in a:
...     print(i**(1/3.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0
复制代码

多维数组每一个轴均可以有一个索引。这些索引在元组中用逗号分隔:

>>> def f(x,y):
...     return 10*x+y
...
>>> b = np.fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1]                       # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1]                        # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ]                      # each column in the second and third row of b
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])
复制代码

当有些维度没有指定索引时,空缺的维度被默认为取全部元素。

>>> b[-1]                                  # the last row. Equivalent to b[-1,:]
array([40, 41, 42, 43])
复制代码

如上由于省略了第二维,b[i] 表示输出第 i 行。固然咱们也能够用「:」表示省略的维度,例如 b[i] 等价于 b[i, :]。此外,NumPy 还容许使用 dots (...) 表示足够多的冒号来构建完整的索引元组。

好比,若是 x 是 5 维数组:

  • x[1,2,...] 等于 x[1,2,:,:,:],
  • x[...,3] 等于 x[:,:,:,:,3]
  • x[4,...,5,:] 等于 x[4,:,:,5,:]
>>> c = np.array( [[[  0,  1,  2],               # a 3D array (two stacked 2D arrays)
...                 [ 10, 12, 13]],
...                [[100,101,102],
...                 [110,112,113]]])
>>> c.shape
(2, 2, 3)
>>> c[1,...]                                   # same as c[1,:,:] or c[1]
array([[100, 101, 102],
       [110, 112, 113]])
>>> c[...,2]                                   # same as c[:,:,2]
array([[  2,  13],
       [102, 113]])
复制代码

多维数组中的迭代以第一条轴为参照完成,以下每一次循环都输出一个 b[i]:

>>> for row in b:
...     print(row)
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
复制代码

然而,若是想在数组的每一个元素上进行操做,能够用 flat 方法。flat 是一个在数组全部元素中运算的迭代器,以下将逐元素地对数组进行操做。

>>> for element in b.flat:
...     print(element)
...
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
复制代码

Shape 变换

改变数组的 shape

一个数组的 shape 是由轴及其元素数量决定的,它通常由一个整型元组表示,且元组中的整数表示对应维度的元素数。

>>> a = np.floor(10*np.random.random((3,4)))
>>> a
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
>>> a.shape
(3, 4)
复制代码

一个数组的 shape 能够由许多方法改变。例如如下三种方法均可输出一个改变 shape 后的新数组,它们都不会改变原数组。其中 reshape 方法在实践中会常常用到,由于咱们须要改变数组的维度以执行不一样的运算。

>>> a.ravel()  # returns the array, flattened
array([ 2.,  8.,  0.,  6.,  4.,  5.,  1.,  1.,  8.,  9.,  3.,  6.])
>>> a.reshape(6,2)  # returns the array with a modified shape
array([[ 2.,  8.],
       [ 0.,  6.],
       [ 4.,  5.],
       [ 1.,  1.],
       [ 8.,  9.],
       [ 3.,  6.]])
>>> a.T  # returns the array, transposed
array([[ 2.,  4.,  8.],
       [ 8.,  5.,  9.],
       [ 0.,  1.,  3.],
       [ 6.,  1.,  6.]])
>>> a.T.shape
(4, 3)
>>> a.shape
(3, 4)
复制代码

ravel() 和 flatten() 都是将多维数组降位一维,flatten() 返回一份新的数组,且对它所作的修改不会影响原始数组,而 ravel() 返回的是 view,会影响原始矩阵。

在矩阵的转置中,行和列的维度将交换,且矩阵中每个元素将沿主对角线对称变换。此外,reshape 以下所示返回修改过维度的新数组,而 resize 方法将直接修改原数组自己的维度。

>>> a
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
>>> a.resize((2,6))
>>> a
array([[ 2.,  8.,  0.,  6.,  4.,  5.],
       [ 1.,  1.,  8.,  9.,  3.,  6.]])
复制代码

若是在 shape 变换中一个维度设为-1,那么这一个维度包含的元素数将会被自动计算。以下所示,a 一共有 12 个元素,在肯定一共有 3 行后,-1 会自动计算出应该须要 4 列才能安排全部的元素。

>>> a.reshape(3,-1)
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
复制代码


数组堆叠

数组能够在不一样轴上被堆叠在一块儿。以下所示 vstack 将在第二个维度(垂直)将两个数组拼接在一块儿,而 hstack 将在第一个维度(水平)将数组拼接在一块儿。

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8.,  8.],
       [ 0.,  0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1.,  8.],
       [ 0.,  4.]])
>>> np.vstack((a,b))
array([[ 8.,  8.],
       [ 0.,  0.],
       [ 1.,  8.],
       [ 0.,  4.]])
>>> np.hstack((a,b))
array([[ 8.,  8.,  1.,  8.],
       [ 0.,  0.,  0.,  4.]])
复制代码

column_stack 函数可堆叠一维数组为二维数组的列,做用相等于针对二维数组的 hstack 函数。

>>> from numpy import newaxis
>>> np.column_stack((a,b))     # with 2D arrays
array([[ 8.,  8.,  1.,  8.],
       [ 0.,  0.,  0.,  4.]])
>>> a = np.array([4.,2.])
>>> b = np.array([3.,8.])
>>> np.column_stack((a,b))     # returns a 2D array
array([[ 4., 3.],
       [ 2., 8.]])
>>> np.hstack((a,b))           # the result is different
array([ 4., 2., 3., 8.])
>>> a[:,newaxis]               # this allows to have a 2D columns vector
array([[ 4.],
       [ 2.]])
>>> np.column_stack((a[:,newaxis],b[:,newaxis]))
array([[ 4.,  3.],
       [ 2.,  8.]])
>>> np.hstack((a[:,newaxis],b[:,newaxis]))   # the result is the same
array([[ 4.,  3.],
       [ 2.,  8.]])
复制代码

与 column_stack 类似,row_stack 函数相等于二维数组中的 vstack。通常在高于二维的状况中,hstack 沿第二个维度堆叠、vstack 沿第一个维度堆叠,而 concatenate 更进一步能够在任意给定的维度上堆叠两个数组,固然这要求其它维度的长度都相等。concatenate 在不少深度模型中都有应用,例如权重矩阵的堆叠或 DenseNet 特征图的堆叠。

在复杂状况中,r_ 和 c_ 能够有效地在建立数组时帮助沿着一条轴堆叠数值,它们一样容许使用范围迭代「:」生成数组。

>>> np.r_[1:4,0,4]
array([1, 2, 3, 0, 4])
复制代码

当用数组为参数时,r_ 和 c_ 在默认行为下与 vstack 和 hstack 类似,但它们如 concatenate 同样容许给定须要堆叠的维度。


拆分数组

使用 hsplit 能够顺着水平轴拆分一个数组,咱们指定切分后输出的数组数,或指定在哪一列拆分数组:

>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9.,  5.,  6.,  3.,  6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 1.,  4.,  9.,  2.,  2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])
>>> np.hsplit(a,3)   # Split a into 3
[array([[ 9.,  5.,  6.,  3.],
       [ 1.,  4.,  9.,  2.]]), array([[ 6.,  8.,  0.,  7.],
       [ 2.,  1.,  0.,  6.]]), array([[ 9.,  7.,  2.,  7.],
       [ 2.,  2.,  4.,  0.]])]
>>> np.hsplit(a,(3,4))   # Split a after the third and the fourth column
[array([[ 9.,  5.,  6.],
       [ 1.,  4.,  9.]]), array([[ 3.],
       [ 2.]]), array([[ 6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])]
复制代码

vsplit 沿着垂直轴拆分,array_split 可指定顺着哪一条轴拆分。

复制与 views

在进行数组运算或操做时,入门者常常很难判断数据究竟是复制到了新的数组仍是直接在原始数据上修改。这对进一步的运算有很大的影响,所以有时候咱们也须要复制内容到新的变量内存中,而不能仅将新变量指向原内存。目前通常有三种复制方法,即不复制内存、浅复制以及深复制。

实际不复制

简单的任务并不会复制数组目标或它们的数据,以下先把变量 a 赋值于 b,而后修改变量 b 就会同时修改变量 a,这种通常的赋值方法会令变量间具备关联性。

>>> a = np.arange(12)
>>> b = a            # no new object is created
>>> b is a           # a and b are two names for the same ndarray object
True
>>> b.shape = 3,4    # changes the shape of a
>>> a.shape
(3, 4)
复制代码

Pythan 将不定对象做为参照(references)传递,因此调用函数不会产生目标识别符的变化,也不会发生实际的内容复制。

>>> def f(x):
...     print(id(x))
...
>>> id(a)                           # id is a unique identifier of an object
148293216
>>> f(a)
148293216
复制代码

View 或浅复制

不一样数组对象能够共享相同数据,view 方法能够建立一个新数组对象来查看相同数据。以下 c 和 a 的目标识别符并不一致,且改变其中一个变量的 shape 并不会对应改变另外一个。但这两个数组是共享全部元素的,因此改变一个数组的某个元素一样会改变另外一个数组的对应元素。

>>> c = a.view()
>>> c is a
False
>>> c.base is a                        # c is a view of the data owned by a
True
>>> c.flags.owndata
False
>>>
>>> c.shape = 2,6                      # a's shape doesn't change
>>> a.shape
(3, 4)
>>> c[0,4] = 1234                      # a's data changes
>>> a
array([[   0,    1,    2,    3],
       [1234,    5,    6,    7],
       [   8,    9,   10,   11]])
复制代码

分割数组输出的是它的一个 view,以下将数组 a 分割为子数组 s,那么 s 就是 a 的一个 view,修改 s 中的元素一样会修改 a 中对应的元素。

>>> s = a[ : , 1:3]     # spaces added for clarity; could also be written "s = a[:,1:3]"
>>> s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])
复制代码


深复制

copy 方法可完整地复制数组及数据,这种赋值方法会令两个变量有不同的数组目标,且数据不共享。

>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a                           # d doesn't share anything with a
False
>>> d[0,0] = 9999
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])
复制代码

深刻理解 NumPy

广播机制

广播操做是 NumPy 很是重要的一个特色,它容许 NumPy 扩展矩阵间的运算。例如它会隐式地把一个数组的异常维度调整到与另外一个算子相匹配的维度以实现维度兼容。例如将一个维度为 [3,2] 的矩阵与另外一个维度为 [3,1] 的矩阵相加是合法的,NumPy 会自动将第二个矩阵扩展到等同的维度。

为了定义两个形状是不是可兼容的,NumPy 从最后开始往前逐个比较它们的维度大小。在这个过程当中,若是二者的对应维度相同,或者其一(或者全是)等于 1,则继续进行比较,直到最前面的维度。若不知足这两个条件,程序就会报错。

以下展现了一个广播操做:

>>>a = np.array([1.0,2.0,3.0,4.0, 5.0, 6.0]).reshape(3,2)
>>>b = np.array([3.0])
>>>a * b

array([[  3.,   6.],
       [  9.,  12.],
       [ 15.,  18.]])
复制代码


高级索引

NumPy 比通常的 Python 序列提供更多的索引方式。除了以前看到的用整数和截取的索引,数组能够由整数数组和布尔数组 indexed。


经过数组索引

以下咱们能够根据数组 i 和 j 索引数组 a 中间的元素,其中输出数组保持索引的 shape。

>>> a = np.arange(12)**2                       # the first 12 square numbers
>>> i = np.array( [ 1,1,3,8,5 ] )              # an array of indices
>>> a[i]                                       # the elements of a at the positions i
array([ 1,  1,  9, 64, 25])

>>> j = np.array( [ [ 3, 4], [ 9, 7 ] ] )      # a bidimensional array of indices
>>> a[j]                                       # the same shape as j
array([[ 9, 16],
       [81, 49]])
复制代码

当使用多维数组做为索引时,每个维度就会索引一次原数组,并按索引的 shape 排列。下面的代码展现了这种索引方式,palette 能够视为简单的调色板,而数组 image 中的元素则表示索引对应颜色的像素点。

>>> palette = np.array( [ [0,0,0],                # black
...                       [255,0,0],              # red
...                       [0,255,0],              # green
...                       [0,0,255],              # blue
...                       [255,255,255] ] )       # white
>>> image = np.array( [ [ 0, 1, 2, 0 ],           # each value corresponds to a color in the palette
...                     [ 0, 3, 4, 0 ]  ] )
>>> palette[image]                            # the (2,4,3) color image
array([[[  0,   0,   0],
        [255,   0,   0],
        [  0, 255,   0],
        [  0,   0,   0]],
       [[  0,   0,   0],
        [  0,   0, 255],
        [255, 255, 255],
        [  0,   0,   0]]])
       [81, 49]])
复制代码

咱们也可使用多维索引获取数组中的元素,多维索引的每一个维度都必须有相同的形状。以下多维数组 i 和 j 能够分别做为索引 a 中第一个维度和第二个维度的参数,例如 a[i, j] 分别从 i 和 j 中抽取一个元素做为索引 a 中元素的参数。

>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i = np.array( [ [0,1],                        # indices for the first dim of a
...                 [1,2] ] )
>>> j = np.array( [ [2,1],                        # indices for the second dim
...                 [3,3] ] )
>>>
>>> a[i,j]                                     # i and j must have equal shape
array([[ 2,  5],
       [ 7, 11]])
>>>
>>> a[i,2]
array([[ 2,  6],
       [ 6, 10]])
>>>
>>> a[:,j]                                     # i.e., a[ : , j]
array([[[ 2,  1],
        [ 3,  3]],
       [[ 6,  5],
        [ 7,  7]],
       [[10,  9],
        [11, 11]]])
复制代码

一样,咱们把 i 和 j 放在一个序列中,而后用它做为索引:

>>> l = [i,j]
>>> a[l]                                       # equivalent to a[i,j]
array([[ 2,  5],
       [ 7, 11]])
复制代码

然而,咱们不能如上把 i 和 j 放在一个数组中做为索引,由于数组会被理解为索引 a 的第一维度。

>>> s = np.array( [i,j] )
>>> a[s]                                       # not what we want
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: index (3) out of range (0<=index<=2) in dimension 0
>>>
>>> a[tuple(s)]                                # same as a[i,j]
array([[ 2,  5],
       [ 7, 11]])
复制代码

另外一个将数组做为索引的经常使用方法是搜索时间序列的最大值:

>>> time = np.linspace(20, 145, 5)                 # time scale
>>> data = np.sin(np.arange(20)).reshape(5,4)      # 4 time-dependent series
>>> time
array([  20.  ,   51.25,   82.5 ,  113.75,  145.  ])
>>> data
array([[ 0.        ,  0.84147098,  0.90929743,  0.14112001],
       [-0.7568025 , -0.95892427, -0.2794155 ,  0.6569866 ],
       [ 0.98935825,  0.41211849, -0.54402111, -0.99999021],
       [-0.53657292,  0.42016704,  0.99060736,  0.65028784],
       [-0.28790332, -0.96139749, -0.75098725,  0.14987721]])
>>>
>>> ind = data.argmax(axis=0)                  # index of the maxima for each series
>>> ind
array([2, 0, 3, 1])
>>>
>>> time_max = time[ind]                       # times corresponding to the maxima
>>>
>>> data_max = data[ind, range(data.shape[1])] # => data[ind[0],0], data[ind[1],1]...
>>>
>>> time_max
array([  82.5 ,   20.  ,  113.75,   51.25])
>>> data_max
array([ 0.98935825,  0.84147098,  0.99060736,  0.6569866 ])
>>>
>>> np.all(data_max == data.max(axis=0))
True
复制代码

你也能够用数组索引做为一个分配目标:

>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a[[1,3,4]] = 0
>>> a
array([0, 0, 2, 0, 0])
复制代码

然而,当索引列表中有重复时,赋值任务会执行屡次,并保留最后一次结果。

>>> a = np.arange(5)
>>> a[[0,0,2]]=[1,2,3]
>>> a
array([2, 1, 3, 3, 4])
复制代码

这是合理的,但注意若是你使用 Python 的 +=建立,可能不会得出预期的结果:

>>> a = np.arange(5)
>>> a[[0,0,2]]+=1
>>> a
array([1, 1, 3, 3, 4])
复制代码

虽然 0 在索引列表中出现两次,第 0 个元素只会增长一次。这是由于 Python 中「a+=1」等于「a = a + 1」.


用布尔数组作索引

当咱们索引数组元素时,咱们在提供索引列表。但布尔值索引是不一样的,咱们须要清楚地选择被索引数组中哪一个元素是咱们想要的哪一个是不想要的。

布尔索引须要用和原数组相同 shape 的布尔值数组,以下只有在大于 4 的状况下才输出 True,而得出来的布尔值数组可做为索引。

>>> a = np.arange(12).reshape(3,4)
>>> b = a > 4
>>> b                                          # b is a boolean with a's shape
array([[False, False, False, False],
       [False,  True,  True,  True],
       [ True,  True,  True,  True]])
>>> a[b]                                       # 1d array with the selected elements
array([ 5,  6,  7,  8,  9, 10, 11])
复制代码

这个性质在任务中很是有用,例如在 ReLu 激活函数中,只有大于 0 才输出激活值,所以咱们就能使用这种方式实现 ReLU 激活函数。

>>> a[b] = 0                                   # All elements of 'a' higher than 4 become 0
>>> a
array([[0, 1, 2, 3],
       [4, 0, 0, 0],
       [0, 0, 0, 0]])
复制代码

第二种使用布尔索引的方法与整数索引更加类似的;在数组的每一个维度中,咱们使用一维布尔数组选择咱们想要的截取部分:

>>> a = np.arange(12).reshape(3,4)
>>> b1 = np.array([False,True,True])             # first dim selection
>>> b2 = np.array([True,False,True,False])       # second dim selection
>>>
>>> a[b1,:]                                   # selecting rows
array([[ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>
>>> a[b1]                                     # same thing
array([[ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>
>>> a[:,b2]                                   # selecting columns
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])
>>>
>>> a[b1,b2]                                  # a weird thing to do
array([ 4, 10])
复制代码

注意一维布尔数组的长度必须和想截取轴的长度相同。在上面的例子中,b1 的长度 三、b2 的长度为 4,它们分别对应于 a 的第一个维度与第二个维度。


线性代数

简单的数组运算

以下仅展现了简单的矩阵运算更多详细的方法可在实践中遇到在查找 API。以下展现了矩阵的转置、求逆、单位矩阵、矩阵乘法、矩阵的迹、解线性方程和求特征向量等基本运算:

>>> import numpy as np
>>> a = np.array([[1.0, 2.0], [3.0, 4.0]])
>>> print(a)
[[ 1.  2.]
 [ 3.  4.]]

>>> a.transpose()
array([[ 1.,  3.],
       [ 2.,  4.]])

>>> np.linalg.inv(a)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])

>>> u = np.eye(2) # unit 2x2 matrix; "eye" represents "I"
>>> u
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> j = np.array([[0.0, -1.0], [1.0, 0.0]])

>>> np.dot (j, j) # matrix product
array([[-1.,  0.],
       [ 0., -1.]])

>>> np.trace(u)  # trace
2.0

>>> y = np.array([[5.], [7.]])
>>> np.linalg.solve(a, y)
array([[-3.],
       [ 4.]])

>>> np.linalg.eig(j)
(array([ 0.+1.j,  0.-1.j]), array([[ 0.70710678+0.j        ,  0.70710678-0.j        ],
       [ 0.00000000-0.70710678j,  0.00000000+0.70710678j]]))

Parameters:
    square matrix
Returns
    The eigenvalues, each repeated according to its multiplicity.
    The normalized (unit "length") eigenvectors, such that the
    column ``v[:,i]`` is the eigenvector corresponding to the
    eigenvalue ``w[i]`` .
复制代码

原文档连接:docs.scipy.org/doc/numpy/u…

相关文章
相关标签/搜索