Python 调换数组维度的一些注意事项
import numpy as np
随机一个多维数组
a = np.random.randint(0,10,(2,3,4,5))
print(a)
[[[[5 3 2 0 5]
[5 3 0 3 6]
[3 1 3 8 3]
[2 3 9 0 6]]
[[7 1 6 2 3]
[2 2 4 7 6]
[4 1 3 4 0]
[1 2 0 2 1]]
[[2 8 4 2 7]
[5 9 1 8 1]
[0 0 1 9 3]
[1 8 0 1 5]]]
[[[0 7 8 8 2]
[6 6 1 7 1]
[4 0 2 6 3]
[4 6 5 5 4]]
[[1 4 8 0 0]
[9 9 3 4 7]
[3 6 9 2 0]
[2 3 6 4 3]]
[[3 8 6 5 2]
[8 8 4 8 7]
[1 9 0 2 2]
[6 9 9 8 2]]]]
现在想要将数组维度改变为(2,3,4,5)->(4,3,5,2)
使用reshape函数改变维度
b = np.reshape(a,(4,3,5,2))
比较二者差异
import itertools as IT
all(b[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, b.shape)))
False
使用Einstein summation convention
c = np.einsum('qjip->ijpq',a)
all(c[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, c.shape)))
True
使用transpose
d = np.transpose(a,(2,1,3,0))
all(d[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, d.shape)))
True
换用不同的order
b1 = np.reshape(a,(4,3,5,2),order='C')
b2 = np.reshape(a,(4,3,5,2),order='A')
b3 = np.reshape(a,(4,3,5,2),order='F')
for array in [b1,b2,b3]:
print(all(array[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, array.shape))))
False
False
False
总结一句话就是,别用reshape!!!