numpy笔记

对以前所学的numpy进行整理,详细使用说明参见官网,或者翻阅《Python for Data Analysis, 2nd Edition》一书,有其他博主进行翻译过。

数组和矩阵

numpy主要有两大类,数组<class 'numpy.ndarray'>和矩阵<class 'numpy.matrix'>。两大类方法有些类似,但在有些操作上是不同的,也可以相互转换。

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np

# 数组
a = np.array([[1, 2],
[3, 4]])
# 矩阵b
b = np.mat([[1, 2],
[3, 4]])
# 数组转矩阵
b = np.mat(a)
# 矩阵转数组
b.A

矩阵和数组在乘法上有所区别,矩阵可以直接相乘,而数组需要dot方法,如果数组直接相乘,结果是相应位置相乘,矩阵要实现相应位置相乘,要调用np.multiply方法。

  • $X = A_{m \times n} * B_{n \times m}$

    1
    2
    3
    4
    5
    6
    7
    # a.shape = (m, n)
    # b.shape = (n, m)
    # 矩阵相乘
    x = a * b
    # 数组相乘
    x = a.dot(b)
    x = np.dot(a, b)
  • $X_{ij} = A_{ij}*B_{ij}$

    1
    2
    3
    4
    5
    # a.shape = b.shape
    # 矩阵相乘
    x = np.multiply(a, b)
    # 数组相乘
    x = a * b

常用方法

摘自《Python for Data Analysis, 2nd Edition》。

数组创建

Function Description
array Convert input data (list, tuple, array, or other sequence type) to an ndarray either by inferring a dtype or explicitly specifying a dtype; copies the input data by default
asarray Convert input to ndarray, but do not copy if the input is already an ndarray
arange Like the built-in range but returns an ndarray instead of a list
ones, ones_like Produce an array of all 1s with the given shape and dtype; ones_like takes another array and produces a ones array of the same shape and dtype
zeros, zeros_like Like ones and ones_like but producing arrays of 0s instead
empty, empty_like Create new arrays by allocating new memory, but do not populate with any values like ones and zeros
full, full_like Produce an array of the given shape and dtype with all values set to the indicated “fill value”; full_like takes another array and produces a filled array of the same shape and dtype
eye, identity Create a square N × N identity matrix (1s on the diagonal and 0s elsewhere)

线性代数

使用numpy.linalg函数

Function Description
diag Return the diagonal (or off-diagonal) elements of a square matrix as a 1D array, or convert a 1D array into a square matrix with zeros on the off-diagonal
dot Matrix multiplication
trace Compute the sum of the diagonal elements
det Compute the matrix determinant
eig Compute the eigenvalues and eigenvectors of a square matrix
inv Compute the inverse of a square matrix
pinv Compute the Moore-Penrose pseudo-inverse of a matrix
qr Compute the QR decomposition
svd Compute the singular value decomposition (SVD)
solve Solve the linear system Ax = b for x, where A is a square matrix
lstsq Compute the least-squares solution to Ax = b

one-hot编码

使用numpy进行one-hot编码。

1
2
3
4
5
6
7
# label.shape = (1, )
# 将label转换成int,因为index是int
label_int = label.astype(int)
# 计算标签种类
k = len(set(label_int))
# one-hot编码
label = np.eye(k)[label_int]

-------------本文结束感谢您的阅读-------------
0%