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.
JavaScript
x
25
25
1
import numpy as np
2
x = array([[ 3.38286851e-02, -6.11905173e-05, -9.08147798e-03,
3
-2.46860166e-02],
4
[-6.11905173e-05, 1.74237508e-03, -4.52140165e-04,
5
-1.22904439e-03],
6
[-9.08147798e-03, -4.52140165e-04, 1.91939979e-01,
7
-1.82406361e-01],
8
[-2.46860166e-02, -1.22904439e-03, -1.82406361e-01,
9
2.08321422e-01]])
10
print(np.shape(x)) # 4 x 4
11
12
y = array([[ 6.76573701e-02, -1.22381035e-04, -1.81629560e-02,
13
-4.93720331e-02],
14
[-1.22381035e-04, 3.48475015e-03, -9.04280330e-04,
15
-2.45808879e-03],
16
[-1.81629560e-02, -9.04280330e-04, 3.83879959e-01,
17
-3.64812722e-01],
18
[-4.93720331e-02, -2.45808879e-03, -3.64812722e-01,
19
4.16642844e-01]])
20
print(np.shape(y)) # 4 x 4
21
22
d = np.dstack((x,y))
23
np.shape(d) # indeed it is 4,4,2... but if I do d[1] then it is not the first x matrix.
24
d[1] # should be y
25
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):
JavaScript
1
3
1
(x == d[ , 0]).all()
2
(y == d[ , 1]).all()
3
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
JavaScript
1
3
1
d[:, :, 0]
2
d[:, :, 1]
3
If you want to access the leaves along the first axis, your array must be (2, 4, 4)
:
JavaScript
1
4
1
d = np.stack((x, y), axis=0)
2
(x == d[0]).all()
3
(y == d[1]).all()
4