Python列表切片X[:,排列]是如何工作的



不确定此时[:,permutation]发生了什么。

permutation = list(np.random.permutation(m))
#print(permutation)
shuffled_X = X[:, permutation]
#print(shuffled_X.shape)
shuffled_Y = Y[:, permutation].reshape((1,m))

假设X只是m x m大小的二维数组

X[permutation, :] # permutes the rows of X
X[:, permutation] # permutes the columns of X
X[:, permutation].reshape((1, m**2)) # permutes the columns of X, and reorders X into a row vector
>>> import numpy as np
>>> m = 5
>>> permutation = list(np.random.permutation(m))
>>> permutation
[3, 2, 4, 0, 1] 
# new row 0 is old row 3
# new row 1 is old row 2
# new row 2 is old row 4
# new row 3 is old row 0
# new row 4 is old row 1
>>> X = np.arange(m**2).reshape((m,m))
>>> X
array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> X[permutation,:]
array([[15, 16, 17, 18, 19],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9]])
>>> X[:,permutation]
array([[ 3,  2,  4,  0,  1],
[ 8,  7,  9,  5,  6],
[13, 12, 14, 10, 11],
[18, 17, 19, 15, 16],
[23, 22, 24, 20, 21]])
>>> X[:,permutation].reshape((1,m**2))
array([[ 3,  2,  4,  0,  1,  8,  7,  9,  5,  6, 13, 12, 14, 10, 11, 18,
17, 19, 15, 16, 23, 22, 24, 20, 21]])```

最新更新