numpy——数值科学计算Python库

numpy

创建ndarray

np.array(some_np_array)

clone a nd-array (e.g. a vector, a matrix).

np.array(list) 一阶

如果是类似一维数组,则返回向量(1D-array,不存在行、列之分,shape都是(n,)而非(n,1),因此其转置不会变为1xn的2D-array),如果list类似二维数组,则返回2D-array。1D-array可通过reshape转为2D-array,或者.array()时令ndmin=2。

np.array(['one', 'dim', 'list']) -> 1D-array

np.array([],[],...) 二阶

np.array([['two', 'dim'] ['list', 'like']]) -> 2D-array

np.array(..., ndmin=阶数)

np.array(['one', 'dim', 'list'], ndmin=2); np.array(list).reshape(len(list), -1) -> row vector(single-row matrix, 1xn)

np.empty(dim, dtype)

np.empty(n, dtype=) 创建具有指定长度的数组 create an empty array with size n

np.full(dim, fill_value) 填充初始值

np.array(['one', 'dim', 'list'], ndim=2).T -> column vector(single-column matrix, nx1)

np.asmatrix(list)返回矩阵,如果list是一维的,则返回nx1矩阵(行向量),转置后成为1xn矩阵(列向量)。

np.unique(arr, return_index, return_counts) 查找数组中具有唯一性的元素。

矩阵元素访问
matrix[i]表示访问第i行,同matrix[i,:],matrix[:,j]表示第j列。matrix[i1:i2, j1:j2] i1行~i2行,j1~j2列的子矩阵。
matrix切片时轴可提供索引的列表,如mat[[1,5,7], 2:4]取得行索引在第1、5、7行,列索引在[2,4)的子矩阵。但是,如果索引列表中只有一个索引,此时获得的是一个向量(而不是包含一个向量的矩阵),即返回值的0索引值是标量,而不是行向量(列向量)。若需保证返回是矩阵(而非在特殊情况下成为向量),……。

expand_dims() 扩展数组维度

np.expand_dims(arr, axis)
参数:

  • arr 扩展多维数组arr的维度,为其增加1维,这里的维度指的是数组的维度,当将数组视为张量时,即扩展张量的阶数。
  • axis 参数指,将被扩展出的维度的位置,可为表示逆向的负数。形状上的变化:形状为$(n_0,n_1,...,n_{m-1})$(注意这里的下标从0开始)的m维数组arrnp.expand_dims(arr, axis)将返回m+1维的数组,在axis=k时,返回的数组的形状为$(...,n_{k-1}, 1, n_{k+1},...)$(即在第k+1维度处增加元素个数为1个的维度,此处是k+1而非k是因轴索引axis是从0开始计,而“第x维度”的说法是将维度从1开始计)。

例:

import numpy as np

a = np.array([
    [0.1, 0.2, 0.3],
    [0.4, 0.5, 0.6]
])

print(a.shape)
print(a)
print()

b0 = np.expand_dims(a, axis=0)
print(b0.shape)
print(b0)
print()

b1 = np.expand_dims(a, axis=1)
print(b1.shape)
print(b1)
print()

b2 = np.expand_dims(a, axis=2)
print(b2.shape)
print(b2)
print()

输出:

(2, 3)
[[0.1 0.2 0.3]
 [0.4 0.5 0.6]]
 
(1, 2, 3)
[[[0.1 0.2 0.3]
  [0.4 0.5 0.6]]]

(2, 1, 3)
[[[0.1 0.2 0.3]]
 [[0.4 0.5 0.6]]]

(2, 3, 1)
[[[0.1]
  [0.2]
  [0.3]]
 [[0.4]
  [0.5]
  [0.6]]]

numpy.squeeze()

the inverse operation of expand_dims

argmax() 查找最大值

np.argmax(arr, axis=) 求解轴向axis上最大值出现(若有多个时则指首次出现)的位置(索引),默认轴向为0
对于一个形状为$(n_1, n_2, ...,n_m)$m阶张量$\bf X$,求解最大值时若指定在第k阶上进行(此时实参axis=k-1,因轴从0开始计算,而非1),则返回一个m-1阶张量,设为$\bf Y$,其形状为$(..., n_{k-1}, n_{k+1},...)$(即除去第k阶)。对于返回的张量在索引$\bm j$(由上述可知此时$\bm j$的维度为m-1)处的值为x(显然该值为标量),因而标量值不会超过$n_k$(即$x\leq n_k$,索引从1开始;而计算机中一般从0开始,此时$x\lt n_k$)。

np.mean(a, axsi)

默认计算展平后的所有元素的均值。如需逐行均值则需显式指定np.mean(, axis=0),如需逐列均值则需显式指定np.mean(, axis=1)。

np.random.randint()生成随机数据

np.random.randint(low, high=, size=, dtype=) 生成指定size个随机整数,每个值在指定的区间范围[low, high]内。

np.random.choice() sampling

sampling, weighted sampling.

  • a: source elements
  • size:
  • replace: sampling with or without replacement. True(default, a value can be sampled multiple times) or False.
  • p: probabilities of elements.

np.random.rand(d0,d1,...dn)

生成由[0,1)之间随机数构成的指定维度数组,参数:

  • d0, d1, ... 维度

np.random.randn(d0,d1,...dn)

生成由[0,1)之间随机数构成且服从正态分布的数组,参数:

  • d0, d1, ... 维度

np.dot(x,y)

点击、内积、或矩阵乘法

*, np.multiply()

对应元素积 (element-wise product)

np.divide()

逐元素除(element-wise division)

np.matmul() (或符号@)

矩阵乘积

np.linalg.norm(x) L2-Norm

L2-norm

and the Euclidean distance can be calculated by np.linalg.norm(x1-x2).

np.linalg.lstsq()

以最小二乘法求解方程。

np.squeeze(data, axis)

remove axes of length one.

e.g.
squeeze an array of shape (1,3,4) on axis=0 results in a data of shape (3,4)

np.stack(data, axis)

join a sequence of arrays along a new axis.

np.vstack(), np.hstack()

函数的输入的张量阶数得相同,如,不能是一个(2,)的向量堆叠到(2,3)的矩阵中,而该是(2,1)的矩阵水平向堆叠到(2,3)矩阵。

np.vstack(): stack vertically (column-wise)

np.hstack(): stack horizontally (row-wise)

np.diagflat()

construct diagonal matrix from a vector.

np.diag()

从矩阵取对角元作为向量(若输入为矩阵),或从向量构造出对角阵(若输入为向量)。

extract diagonal elements (from a matrix) or construct a diagonal matrix (from a vector).

np.diag(np.reshape([5,6,7], (3,1))) =>  [5]
np.diag(np.reshape([5,6,7], (1,3))) =>  [5]
np.diag([5,6,7]) =>  a diagonal matrix      # same as np.diag(np.reshape([5,6,7], (3,)))

np.diagflat(np.reshape([5,6,7], (1,3))) => a diagonal matrix with shape 3x3

np.repeat()

np.repeat([[1,2]], 2, axis=0)
#  [[1,2],
#   [1,2]]
np.repeat([[1,2]], 2, axis=1)
# [[1,1,2,2]]

np.minimum()

pair-wise minimum of two arrays.

np.partition(a, kth)

  • a. input array
  • kth. partition index or indices.

在多维数组的某个维度上,重新组织该维数组,使其以kth指定的索引为分界点切分出的两个或多个(当给定多个切分索引时)分区之间保持有序。该函数仅保证分区之间有序,不保证分区内的元素之间的序。该函数返回的仍是一个与输入同形状的数组,并非多个切分出的子数组。

a = np.array([3, 4, 2, 1])
np.partition(a, 3)      # 即,返回的数组中,其索引3之前的所有元素比索引3及之后的元素值小。
array([2, 1, 3, 4])
np.argsort()

排序输入的数组,返回有序元素在原数组中的索引。

np.searchsorted()

在有序数组中搜索特定值的索引。

np.ndindex(*shape)

generator of indices of ndarray

“外”操作 Outer

numpy为很多二元操作定义了“外”操作版本,其一般表达,对于输入的二元操作数,以第一个操作数数组中的每个元素作用于另一个操作数数组中的每一个元素以得到结果多维数组中的一个元素。如 outer(a,b)其中a,b为两个数组,长度分别为m,n,则输出m×n的数组,其中第i,j元素为a_i*b_j,其中*表示该操作的标量版本,如对于“减法”的outer版,则这里代表a_i-b_j

numpy.substract.outer(a,b):

numpy.float_power.outer()

numpy.power.outer()

numpy.outer() 张量积

Indexing

# boolean indexing

x=np.array([1,2,3,4])
a=x>2       # [false, false, true, true]
x[a]        # [3,4]


# indexing by row indices and column indices
rows=[0,1,3]
cols=[0,2]
X[np.ix_(rows, cols)]

# generator of indices of ndarray
for ix1, ix2 in np.ndindex(*arr2d.shape):
    pass

symmetric matrix

no builtin function for symmetric matrices creating

import itertools
import numpy as np

def symmetric_matrix(values,index_pairs,n=None):
    """
    symmetric_matrix([1,2,3], [(0, 1), (0, 2), (1, 2)]) ->
    [[0., 1., 2.],
     [1., 0., 3.],
     [2., 3., 0.]]
    :param values: list of values
    :param index_pairs: list of pairs of indices corresponding to values  (len(index_pairs)==len(values))
    :param n: the dimension of squared symmetric matrix. If none, the dimension will be the 1+maximum of indices
    ( indices started at 0)
    :return: the symmetric matrix
    """
    if len(values)!=len(index_pairs):
        raise ValueError
    if n is None:
        n=max(itertools.chain.from_iterable(index_pairs))+1
    X=np.zeros(shape=(n,n))
    for v,(i,j) in zip(values,index_pairs):
        X[i,j]=v
        X[j,i]=v
    return X

triangular matrix

no builtin function for creating from values with indices

extracting the triangular part as a mtrix from a matrix

numpy.tril(X)        # lower triangular
numpy.triu(X)       # uppoer triangular
numpy.tril(X, k=)    # below( and including) the k-th diagonal

numpy.matrix

a slice of numpy.matrix is always a matrix instead of a 1-d array.

x: m-by-n numpy.matrix, x[2] -> 1-by-n numpy.matrix, instead of 1-d array with shape (n,). Indexing here for a numpy.matrix is not like indexing for a 2-d array.

find top k smallest/largest values

完全可以用sort排序所有元素后取前k个,但这种方法不必要地对其余元素排序。

用.partition+sort方式可以降低计算复杂度。

np.partition, np.argpartition, np.sort, np.argsort


# If we want only values and don't care indices
# for 1-d array
x = [1, ...]
top_k = 
vals=np.parition(x, top_k)[:top_k]
vals = np.sort(vals)

# If we care both values and indices
x = 
top_k = 
ind = np.argpartition(x, top_k)[:top_k]
ind = np.argsort(x[ind])
vals = x[ind]

FAQ

"ValueError: setting an array element with a sequence."

posted @ 2022-07-06 23:29  二球悬铃木  阅读(50)  评论(0编辑  收藏  举报