官方文档:NumPy Reference — NumPy v1.23 Manual
文章目录
- 1. Array Objects
- 2. Constants
- 3. Universal Functions (ufunc)
- 4. Routines
- 4.1 Array creation routines
- 4.2 Array manipulation routines
- 4.3 Binary operations
- 4.4 String operations
- 4.5 C-Types Foreign Function Interface (numpy.ctypeslib)
- 4.6 Datetime Support Functions
- 4.7 Data type routines
- 4.8 Optionally SciPy-accelerated routines (numpy.dual)
- 4.9 Mathematical functions
- 4.10 Floating point error handling
- 4.11 Discrete Fourier Transform (numpy.fft)
- 4.12 Functional programming
- 4.13 NumPy-specific help functions
- 4.14 Indexing routines
- 4.15 Input and output
- 4.16 Linear algebra (numpy.linalg)
- 4.17 Logic functions
- 4.18 Masked array operations
- 4.19 Mathematical functions
- 4.20 Matrix library (numpy.matlib)
- 4.21 Miscellaneous routines
- 4.22 Padding Arrays
- 4.23 Polynomials
- 4.24 Random sampling (numpy.random)
- 4.24 Set routines
- 4.25 Sorting, searching, and counting
- 4.26 Statistics
- 5. 其他功能的实现
- 其他正文及脚注未提及的参考资料
1. Array Objects
1.1 The N-dimensional array ( ndarray )
1.1.1 numpy.ndarray
astype(dtype)
:复制array对象,并重置为指定type
实例代码:array2=array1.astype(np.float32)
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.htmlshape
:由array每一维度组成的tuple
如果想要改变array维度,可以直接改变shape
,但是不建议这么干
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.htmlmean()
等如numpy.mean()
2. Constants
3. Universal Functions (ufunc)
4. Routines
4.1 Array creation routines
array(object)
:创建一个值与object相同的numpy.ndarray对象(元素保持最高精度)
numpy.diag(v, k=0)
- 如v是一维向量:构建以v为值的对角阵
- k控制在对角线上方几行
https://numpy.org/doc/stable/reference/generated/numpy.diag.html
4.2 Array manipulation routines
numpy.expand_dims(a, axis)
:增加一维(感觉上比较类似PyTorch的unsqueeze()
)https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.htmlnumpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
:合并多个ndarray
https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html
常见问题:入参ndarray必须用稠密矩阵,如果使用了稀疏矩阵,将会报ValueError: zero-dimensional arrays cannot be concatenated
bugnumpy.transpose(a, axes=None)
https://numpy.org/doc/stable/reference/generated/numpy.transpose.html- 对二维矩阵:转置
numpy.reshape(a, /, shape=None, *, newshape=None, order='C', copy=None)
:改变张量的形状,但不改变数据。
4.3 Binary operations
4.4 String operations
4.5 C-Types Foreign Function Interface (numpy.ctypeslib)
4.6 Datetime Support Functions
4.7 Data type routines
- class numpy.finfo(dtype):机器对浮点类型的各项限制
4.8 Optionally SciPy-accelerated routines (numpy.dual)
4.9 Mathematical functions
numpy.power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
:element-wise计算幂numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
:当axis=None
时计算张量所有值的和
4.10 Floating point error handling
numpy.errstate(**kwargs)
:上下文管理器或者装饰器
kwargs{divide, over, under, invalid}
https://numpy.org/doc/stable/reference/generated/numpy.errstate.html
示例一:
with np.errstate(divide='ignore'):
d_inv_sqrt = np.power(rowsum, -0.5)
4.11 Discrete Fourier Transform (numpy.fft)
4.12 Functional programming
4.13 NumPy-specific help functions
4.14 Indexing routines
4.15 Input and output
ndarray.tolist()
:将ndarray对象转为nested list,元素为Python标量
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tolist.html
如果直接用list(ndarray)
会导致元素是numpy类型的数字
4.16 Linear algebra (numpy.linalg)
numpy.dot(a, b, out=None)
- 如果a和b都是二维矩阵:返回a和b的矩阵乘法结果
4.17 Logic functions
numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
:返回2个array是否所有元素都相同(允许一定误差)
可用于检测一个矩阵是否是对称阵:np.allclose(X, X.T)
numpy.isinf(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
:element-wise计算矩阵元素是否无限(可能是正负无限)
4.18 Masked array operations
4.19 Mathematical functions
4.20 Matrix library (numpy.matlib)
4.21 Miscellaneous routines
4.22 Padding Arrays
4.23 Polynomials
4.24 Random sampling (numpy.random)
https://numpy.org/doc/stable/reference/random/index.html
- Generator
https://numpy.org/doc/stable/reference/random/generator.html
Generator是代替RandomState的。numpy.random.default_rng(seed=None)
参数:seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional
示例代码:
import numpy as np rng = np.random.default_rng(12345) rfloat = rng.random() #生成一个随机float rints = rng.integers(low=0, high=10, size=3) #生成0(包含)-10(不包含)之间的3个integer
Generator.choice(a, size=None, replace=True, p=None, axis=0, shuffle=True)
https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html
从传入的一维数组(a)中产生随机抽样
参数:
size {int, tuple[int]}, optional:输出的shape
replace bool, optional:有放回抽样 / 无放回抽样
示例代码:
①从np.arange(5)
中生成一个大小为3的抽样rng.choice(5, 3) #输出:array([0, 3, 4]) # random #This is equivalent to rng.integers(0,5,3)
random.random(size=None)
返回 [0.0, 1.0) 范围内的一个随机浮点数random.rand(d0, d1, ..., dn)
返回给定尺寸的随机数ndarray
4.24 Set routines
numpy.unique(arr)
:直接的默认返回值是np.ndarray对象,arr
中唯一值从小到大排序
https://numpy.org/doc/stable/reference/generated/numpy.unique.html
4.25 Sorting, searching, and counting
numpy.where(condition, [x, y, ]/)
:condition是一个张量,返回的张量用x覆盖condition中值为True的元素,y覆盖值为False的
例子1,直接对每个元素进行替换:
例子2,用整个张量去覆盖(就相当于直接挨个儿对应元素):import numpy as np a = np.arange(10) a # 输出:array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) np.where(a < 5, a, 10*a) # 输出:array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
np.where([[True, False], [True, True]], [[1, 2], [3, 4]], [[9, 8], [7, 6]]) array([[1, 8], [3, 4]])
4.26 Statistics
numpy.mean(a)
:直接求整个array-like对象的平均值
https://numpy.org/doc/stable/reference/generated/numpy.mean.html
5. 其他功能的实现
- 切片:
按标准来将ndarray变成布尔张量:example_matrix[example_matrix>=0.98]