Numpy矩阵操作短代码

创建一个5x5的矩阵,并设置值1,2,3,4落在其对角线下方位置

1
2
3
4
import numpy as np

Z = np.diag(1+np.arange(4),k=-1)
print(Z)

创建一个8x8的矩阵,并且设置成棋盘样式

1
2
3
4
5
6
import numpy as np

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)

用tile函数去创建一个8x8的棋盘样式矩阵

1
2
3
4
import numpy as np

Z = np.tile(np.array([[0,1],[1,0]]), (4,4)) # 将原矩阵横向、纵向地复制
print(Z)

将一个整数向量转换为二进制矩阵

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

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])

# Author: Daniel T. McDonald

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))

矩阵归一化

1
2
3
4
5
6
import numpy as np

Z = np.random.random((5,5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)

矩阵的秩

1
2
3
4
5
6
import numpy as np

Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)

两个矩阵相乘

1
2
3
4
import numpy as np

Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)

构造一个二维高斯矩阵

1
2
3
4
5
6
7
8
import numpy as np

X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10))
D = np.sqrt(X**2 + Y**2)

sigma, mu = 1.0, 0.0
G = np.exp(-((D-mu)**2 / (2.0*sigma**2)))
print(G)