python - 在 numpy 中 reshape 时如何保持特定维度不变?

标签 python numpy matrix

我有一个巨大的 (N*20) 矩阵,其中每 5 行都是有效样本,即。每个(5*20)矩阵。我试图将其 reshape 为 (N/5,1,20,5) 矩阵,其中维度 20 保持不变。我可以使用 keep_dim 在tensroflow中做到这一点,但是如何在numpy中实现这一点?

提前致谢。

最佳答案

reshape 形状,然后交换轴:

 arr1 = arr.reshape(N/5,5,1,20)
 arr2 = arr1.transpose(0,2,3,1)

例如

In [476]: arr = np.arange(24).reshape(6,4)
In [477]: arr
Out[477]: 
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]])
In [478]: arr1 = arr.reshape(2,3,1,4)
In [479]: arr2 = arr1.transpose(0,2,3,1)
In [480]: arr2.shape
Out[480]: (2, 1, 4, 3)
In [482]: arr2
Out[482]: 
array([[[[ 0,  4,  8],
         [ 1,  5,  9],
         [ 2,  6, 10],
         [ 3,  7, 11]]],


       [[[12, 16, 20],
         [13, 17, 21],
         [14, 18, 22],
         [15, 19, 23]]]])

关于python - 在 numpy 中 reshape 时如何保持特定维度不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918691/

相关文章:

python - 如何确定一组元组中的公共(public)元素 - Python

python - 根据 c 中的值乘以 pandas DataFrame 中的行

python - 从椭球置信区域均匀采样

python - 在 Python 中订购 Logit?

python - 合并非重叠数组 block

c++ - 数组的行操作

python - 将 dict 转换为嵌套列表,将键插入每个子列表

Java:坐标变换 - 旋转和缩放

javascript - 如何找到对 Angular 线值

python - 操纵样条的导数