我使用scipy.io
将Mat文件读入python,加载3D张量。我在网上找到的大多数参考文献都只讨论了2个维度,而且我很难将我的头部围绕专业列重叠到维度大于2的数据行。
ravel
和reshape
与order
的组合? 示例
在这个例子中,假设我有一个(2,4,3)维矩阵在Column-Major中读入,我想将它反转为Row-Major。
import numpy as np
lst3d = [[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]], [[13, 14, 15], [17, 18, 19], [21, 22, 23], [25, 26, 27]]]
print(lst3d)
a = np.array(lst3d)
b = np.array(lst3d)
print(a.shape)
print('----------')
print(a.ravel(order='C').reshape(a.shape))
print('----------')
print(b.ravel(order='F').reshape(b.shape))
输出:
[[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]], [[13, 14, 15], [17, 18, 19], [21, 22, 23], [25, 26, 27]]]
(2, 4, 3)
----------
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[13 14 15]
[17 18 19]
[21 22 23]
[25 26 27]]]
----------
[[[ 0 13 3]
[17 6 21]
[ 9 25 1]
[14 4 18]]
[[ 7 22 10]
[26 2 15]
[ 5 19 8]
[23 11 27]]]
相关
答案 0 :(得分:1)
在Octave:
>> x=0:23;
>> x=reshape(x,2,4,3);
>> x
x =
ans(:,:,1) =
0 2 4 6
1 3 5 7
ans(:,:,2) =
8 10 12 14
9 11 13 15
ans(:,:,3) =
16 18 20 22
17 19 21 23
>> save -v7 test3d x
在ipython中:
In [192]: data = io.loadmat('test3d')
In [194]: x=data['x']
In [195]: x
Out[195]:
array([[[ 0., 8., 16.],
[ 2., 10., 18.],
[ 4., 12., 20.],
[ 6., 14., 22.]],
[[ 1., 9., 17.],
[ 3., 11., 19.],
[ 5., 13., 21.],
[ 7., 15., 23.]]])
In [196]: x.shape
Out[196]: (2, 4, 3)
显示为Octave:
In [197]: x[:,:,0]
Out[197]:
array([[0., 2., 4., 6.],
[1., 3., 5., 7.]])
loadmat
已将其加载为F
订单,具有相同的2,4,3形状。右ravel
生成原始的0:23数字:
In [200]: x.ravel(order='F')
Out[200]:
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.])
x
的转置生成一个(3,4,2)阶'C'数组:
In [207]: x.T[0]
Out[207]:
array([[0., 1.],
[2., 3.],
[4., 5.],
[6., 7.]])
In [208]: y=np.arange(24).reshape(3,4,2)
In [209]: y[0]
Out[209]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])