繁体   English   中英

从二维数组(Python)创建 3d 张量数组

[英]Creating 3d Tensor Array from 2d Array (Python)

我有两个 numpy arrays(每个 4x4)。 我想将它们连接到 (4x4x2) 的张量,其中第一个“工作表”是第一个数组,第二个“工作表”是第二个数组,等等。但是,当我尝试np.stack时, d[1]的 output d[1]没有显示第一个矩阵的正确值。

import numpy as np
x = array([[ 3.38286851e-02, -6.11905173e-05, -9.08147798e-03,
        -2.46860166e-02],
       [-6.11905173e-05,  1.74237508e-03, -4.52140165e-04,
        -1.22904439e-03],
       [-9.08147798e-03, -4.52140165e-04,  1.91939979e-01,
        -1.82406361e-01],
       [-2.46860166e-02, -1.22904439e-03, -1.82406361e-01,
         2.08321422e-01]])
print(np.shape(x)) # 4 x 4

y = array([[ 6.76573701e-02, -1.22381035e-04, -1.81629560e-02,
        -4.93720331e-02],
       [-1.22381035e-04,  3.48475015e-03, -9.04280330e-04,
        -2.45808879e-03],
       [-1.81629560e-02, -9.04280330e-04,  3.83879959e-01,
        -3.64812722e-01],
       [-4.93720331e-02, -2.45808879e-03, -3.64812722e-01,
         4.16642844e-01]])
print(np.shape(y)) # 4 x 4

d = np.dstack((x,y))
np.shape(d) # indeed it is 4,4,2... but if I do d[1] then it is not the first x matrix.
d[1] # should be x

如果您执行np.dstack((x, y)) ,这与更明确的np.stack((x, y), axis=-1)相同,那么您将沿最后一个而不是第一个轴连接(即大小为2的那个):

(x == d[..., 0]).all()
(y == d[..., 1]).all()

省略号 ( ... ) 是 python object 在索引中使用时表示“ :根据需要多次”。 对于 3D 数组,您可以等效地访问叶子为

d[:, :, 0]
d[:, :, 1]

如果要沿第一个轴访问叶子,则数组必须是(2, 4, 4)

d = np.stack((x, y), axis=0)
(x == d[0]).all()
(y == d[1]).all()

使用np.stack而不是np.dstack

>>> d = np.stack([y, x])

>>> np.all(d[0] == y)
True

>>> np.all(d[1] == x)
True

>>> d.shape
(2, 4, 4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM