让我们有一个形状为$n imes d imes h imes w imes p imes p$的张量,我们想要将内网矩阵与形状为$p ime p$连接起来,这样我们就制作了一个形状为$n imes d imes ph的矩阵imes pw$。我该怎么办?
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, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]]]]])
连接后
array([[[[0, 1, 2, 9, 10, 11],
[3, 4, 5, 12, 13, 14],
[6, 7, 8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]]]])
我使用reshape做了很多实验,但没有成功。我的实验之一
a.reshape(n, d, p*h, p*w)
我可以使用 for 循环来做到这一点,但我认为没有这个也是可能的。 请帮我。 使用for循环的代码
p = 3
arr = np.arange(1*1*2*2*p*p).reshape(1, 1, 2, 2, p, p)
answer = np.zeros(shape=(1, 1, 2*p, 2*p))
for (n, d, h, w) in np.ndindex(*arr.shape[:4]):
answer[n, d, h:h+p, w:w+p] = arr[n, d, h, w]
In [15]: arr=np.arange(0,36).reshape(2,2,3,3)
reshape
无法对数组的元素重新排序。我从 [0,1,...35] 开始,reshape
保留了这一点:
In [18]: arr.reshape(2,3,6)
Out[18]:
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, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]]])
我们必须以某种方式重新排序元素,将 [9,10,11] 块放在 [0,1,2] 旁边。
transpose
就是这样一种工具:
In [19]: arr.transpose(0,2,1,3)
Out[19]:
array([[[[ 0, 1, 2],
[ 9, 10, 11]],
[[ 3, 4, 5],
[12, 13, 14]],
[[ 6, 7, 8],
[15, 16, 17]]],
[[[18, 19, 20],
[27, 28, 29]],
[[21, 22, 23],
[30, 31, 32]],
[[24, 25, 26],
[33, 34, 35]]]])
In [20]: arr.transpose(0,2,1,3).reshape(6,6)
Out[20]:
array([[ 0, 1, 2, 9, 10, 11],
[ 3, 4, 5, 12, 13, 14],
[ 6, 7, 8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]])