我使用scipy.io
将Mat文件读取到python中,加载3D张量。我在网上找到的大多数参考资料只讨论 2 个维度,而且我很难在维度超过 2 的数据中围绕列主要到行主要。
- scipy.io 是否自动处理从列主(顺序 = 'F'(到行主(订单 = 'C'(的转换?
- 如果不是 1,有没有比使用
ravel
和reshape
与order
结合使用更好的方法来更改 3D 张量? - 如果不是 2,有没有办法以编程方式确定转换后的张量应该是什么形状?在下面的例子中,我使用了解开和重塑,但很明显原始形状不合适?
例
在此示例中,假设我有一个在列主列中读入的 (2, 4, 3( 维矩阵,我想将其反转为主要行。
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]]]
相关
- numpy 数组行主和列主
- https://cran.r-project.org/web/packages/reticulate/vignettes/arrays.html
- https://craftofcoding.wordpress.com/2017/02/03/column-major-vs-row-major-arrays-does-it-matter/
八度:
>> 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)
以八度显示:
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]])