Skip to content
Advertisement

Creating 3d Tensor Array from 2d Array (Python)

I have two numpy arrays (4×4 each). I would like to concatenate them to a tensor of (4x4x2) in which the first ‘sheet’ is the first array, second ‘sheet’ is the second array, etc. However, when I try np.stack the output of d[1] is not showing the correct values of the first matrix.

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 y

Advertisement

Answer

If you do np.dstack((x, y)), which is the same as the more explicit np.stack((x, y), axis=-1), you are concatenating along the last, not the first axis (i.e., the one with size 2):

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

Ellipsis (...) is a python object that means “: as many times as necessary” when used in an index. For a 3D array, you can equivalently access the leaves as

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

If you want to access the leaves along the first axis, your array must be (2, 4, 4):

d = np.stack((x, y), axis=0)
(x == d[0]).all()
(y == d[1]).all()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement