Numpy¶
NumPy Reference — NumPy v1.20 Manual
np.polyfit(x, y, 1)
np.poly1d()
cunmsum
ndarray¶
创建与初始化¶
import numpy as np
np.array(object, dtype = None, copy = True)
np.empty(shape, dtype=float, order='C', *, like=None) # 并不初始化为0
np.ones(shape, dtype=None, order='C', *, like=None) # 初始化为 1
np.zeros(shape, dtype=float, order='C', *, like=None) # 初始化为 0
np.arange(24).reshape((2,3,4)) # range创建list,arange创建array
np.arange(24).reshape((2,3,-1)) # 参数有-1时会自动根据其他的参数计算
np.linspace(start, stop, num) # [start, stop] 平均取 num 个数
维度变换¶
# transpose
np.transpose(a, axes) # axes: tuple or list of ints
ndarray.transpose(*axes) # axes: tuple of ints, or n ints
类型转换¶
数学计算与数据处理¶
np.random.normal()
numpy.random.normal — NumPy v1.21 Manual
random.normal(loc=0.0, scale=1.0, size=None)
np.random.uniform()
读取数据¶
# 一维
a[2]
a[1:4:2] # 切片 3 5 步长2
# 多维数组
a = np.arange(24).reshape((2,3,4))
a[1,2,3]
a[::,::,::] # 切片
a[[1,4],:] # 获取 1,4 行
# 多维数据只规定第一维
a[size:] # size~最后一行
数据赋值¶
增加数据¶
# concatenate axis=1 水平连接
np.concatenate((a1, a2, ...), axis=0) # 拼接
# append axis=0 列增加
np.append(arr, values, axis=None)
删除数据¶
数据处理¶
ndarray.astype()
数据统计¶
均值
# 求平均值 axis=0 求列均值, axis=1 求行均值,默认求所有数的均值
np.mean(matrix, axis=None)
求和
# 求和
np.sum(matrix, axis=None)
标准差
# 求标准差
np.std(matrix, axis=None)
方差
# 求方差
np.var(matrix, axis=None)
协方差
# 求协方差 rowvar=True以行为变量,否则以列为变量
np.cov(matrix, rowvar=True)
范数
x_norm=np.linalg.norm(x, ord=2, axis=None, keepdims=False)
默认 2 范数
参数 | 说明 | 式子 |
---|---|---|
ord=1 | 1范数 | $ |
ord=2(默认) | 2范数 | \(\sqrt{x_1^2+x_2^2+...}\) |
ord=np.inf | 无穷范数 | $max( |
np.argmax()
Returns the indices of the maximum values along an axis.
np.argmax(a, axis=None, out=None)
矩阵运算¶
矩阵转置
总的来说,1 维的 list 和 ndarray 无法转置
非一维的 list 只能用 np.transpose()
,ndarray 还可以用 ndarray.T
- 一维
# 无论 a 是 list 还是 ndarray
# 先变成 2 维的 list
at = np.transpose([a]) # [a] 是一个 list
# 先变成 2 维的 ndarray
a = np.array([a])
at = a.T # transpose 也行
- 二维
# list
at = np.transpose(a)
# ndarray
at = a.T
at = np.transpose(a)
矩阵乘法
- ndarray
# x, w 都是 ndarray
np.dot(x, w) # 点乘
np.corss(x, w) # 叉乘
- matrix
# x, w 都是 matrix
x = np.mat([1, 2, 3])
w = np.mat([1], [2], [3])
x * w
np.matmul()
np.matmul(a, b)
-
如果 a,b 都是 2 维的,那么就是普通的矩阵运算
-
如果 a,b 都是 \(N(N>2)\) 维的,那么会把 a,b 当成以最后 2 维为维度的若干矩阵分别做矩阵乘法,比如 a 是 \(2\times4\times3\),b 是 \(2\times3\times2\),那么就是 a 中第一个 \(4\times3\) 与 b 中第一个 \(3\times2\) 做矩阵乘法,第二个同理,结果是 \(2\times4\times2\)
-
如果 a,b 其中一个是 \(N(N>2)\) 维的或者两者的维数不同,那么低维的会向高维进行广播再计算
数学运算¶
四则运算
# ndarray 对应元素做四则运算, 低维会向高维广播
a = np.array([1, 2])
b = np.array([2, 3])
c = a * b # [2, 6]
# matrix 除了 * 是做矩阵运算外, 其他四则运算与 ndarray 相同
其他
# 都是对每个元素进行相应的运算
np.power(a, 2) # 对 a 中每个元素平方, 可以简写为 a**2
np.log2(a)
np.around(a)
np.abs(a)
astype()¶
# 数据类型转换
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
meshgrid() / mgird()¶
meshgrid()
# 生成网格点坐标矩阵
np.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
X, Y = np.meshgrid(x, y) # 把 x,y 进行笛卡尔积的结果的第一位元素放进 X, 第二位元素给 Y
mgird()
>>> np.mgrid[0:5,0:5] # 与 meshgird 的效果类似
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> np.mgrid[-1:1:5j] # 5j 表示生成5个点
array([-1. , -0.5, 0. , 0.5, 1. ])
>>> np.mgrid[0:1:100j, 0:1:100j] # 二维的例子
shape¶
ndarray.shape # 返回 shape
# 也可以用来 reshape
ndarray.shape = (int, int)
# eg:获取数据的列数
print(data.shape[1])
clip()¶
np.clip(a, a_min, a_max)
# a 中小于 a_min 的数都变成 a_min, 大于 a_max 的数都变成 a_max
random.shuffle()¶
# 打乱顺序
arr = np.arange(10)
np.random.shuffle(arr)
argsort()¶
获得对元素排序后的下标(排序前的索引)
np.argsort(x)[:3] # 返回 x 中最小的三个数的下标
np.argsort(x)[-3:] # 返回 x 中最大的三个数的下标
save() / load()¶
np.save('./test.npy', x)
x = np.load('./test.npy')
numpy.random.seed()
arr.ravel()
arr.flatten()
np.linalg¶
inv()
svd()
np.random¶
random.permutation()
产生 [1, x] 的随机序列
random.permutation(x)