当您想要将形状 (a,b,c,d)
的矩阵 X
展平为形状为 X_flatten
的矩阵时,这是一个技巧形状 (b **** c **** d, a)
使用:
X_flatten = X.reshape(X.shape[0], -1).T
我在 coursera DL 类(class)中读到了这个技巧,它是如何工作的? -1
从何而来,它的含义是什么?
最佳答案
X.shape[0] 返回原始数组的第一个维度:
X = np.random.rand(4, 4, 4, 4)
print(X.shape)
结果
(4, 4, 4, 4)
因此
X.shape[0]
返回
4
使用 reshape 命令,您可以通过使用 -1 作为占位符来省略目标矩阵维度之一, 因为其中一个维度可以通过 numpy 推断出来。
即通过提供 X.shape[0] 中的 4,numpy 知道剩余的第一个维度必须是什么,数组才能包含所有值。
在示例中
new_X = X.reshape(X.shape[0], -1).T
print(new_X.shape)
是
(64, 4)
这相当于调用
new_X = X.reshape(X.shape[0], 64).T
print(new_X.shape)
.T 函数只是转置 reshape 命令生成的数组。
关于python - python 中的展平矩阵 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461950/