Skip to main content
 首页 » 编程设计

Python:3D 列主要张量到行主要

2024年12月31日9lhb25

我使用 scipy.io 将 Mat 文件读入 python,加载 3D 张量。我在网上找到的大多数引用文献只讨论 2 个维度,而且我很难在维度超过 2 的数据中围绕列专业到行专业进行思考。

  1. scipy.io 是否自动处理从列主(order = 'F')到行主(order = 'C')的转换?
  2. 如果不是 1,是否有比结合使用 ravel 和 reshape 和 order 更好的方法来更改 3D 张量?
  3. 如果不是 2,有没有办法以编程方式确定转换后的张量的形状?在下面的例子中,我使用了unravel和reshape,但是很明显原来的形状不合适?

示例

在这个例子中,假设我有一个以列优先读入的 (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]]] 

相关

请您参考如下方法:

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]])