一、操作 numpy 数组的常用函数
- where
使用 where 函数能将索引掩码转换成索引位置:
indices = where(mask)
indices
=> (array([11, 12, 13, 14]),)
x[indices] # this indexing is equivalent to the fancy indexing x[mask]
=> array([ 5.5, 6. , 6.5, 7. ])
- diag
使用 diag 函数能够提取出数组的对角线:
diag(A)
=> array([ 0, 11, 22, 33, 44])
diag(A, -1)
=> array([10, 21, 32, 43])
- take
take 函数与高级索引(fancy indexing)用法相似:
v2 = arange(-3,3)
v2
=> array([-3, -2, -1, 0, 1, 2])
row_indices = [1, 3, 5]
v2[row_indices] # fancy indexing
=> array([-2, 0, 2])
v2.take(row_indices)
=> array([-2, 0, 2])
但是 take 也可以用在 list 和其它对象上:
take([-3, -2, -1, 0, 1, 2], row_indices)
=> array([-2, 0, 2])
- choose
选取多个数组的部分组成新的数组:
which = [1, 0, 1, 0]
choices = [[-2,-2,-2,-2], [5,5,5,5]]
choose(which, choices)
=> array([ 5, -2, 5, -2])
二、线性代数
矢量化是用 Python/Numpy 编写高效数值计算代码的关键,这意味着在程序中尽量选择使用矩阵或者向量进行运算,比如矩阵乘法等。
1.标量运算
使用一般的算数运算符,比如加减乘除,对数组进行标量运算。
v1 = arange(0, 5)
v1 * 2
=> array([0, 2, 4, 6, 8])
v1 + 2
=> array([2, 3, 4, 5, 6])
A * 2, A + 2 #分别作用在矩阵每个元素上
2. Element-wise(逐项乘) 数组-数组 运算
在矩阵间进行加减乘除时,它的默认行为是 element-wise(逐项乘) 的:
A * A # 元素相乘
3. 矩阵代数
使用 dot 函数进行 矩阵-矩阵,矩阵-向量,数量积乘法:
dot(A, A)
dot(A, v1)
=> array([ 30, 130, 230, 330, 430])
dot(v1, v1)
=> 30
将数组对象映射到 matrix 类型。 加减乘除不兼容的维度时会报错
M = matrix(A)
v = matrix(v1).T # make it a column vector
v
=> matrix([[0],
[1],
[2],
[3],
[4]])
M * v
=> matrix([[ 30],
[130],
[230],
[330],
[430]])
v.T * v # inner product
=> matrix([[30]])
查看其它运算函数: inner, outer, cross, kron, tensordot可以使用 help(kron)。
4. 数组/矩阵 变换
之前使用 .T 对 v 进行了转置,也可以使用 transpose 函数完成同样的事情。其他函数:
共轭conjugate(C)
C = matrix([[1j, 2j], [3j, 4j]])
conjugate(C)
=> matrix([[ 0.-1.j, 0.-2.j],
[ 0.-3.j, 0.-4.j]])
共轭转置C.H
C.H
=> matrix([[ 0.-1.j, 0.-3.j],
[ 0.-2.j, 0.-4.j]])
real 与 imag 能够分别得到复数的实部与虚部:
real(C) # same as: C.real
=> matrix([[ 0., 0.],
[ 0.,