I have a 2D numpy array X
(batch x channels
х pool_size * pool_size
),
where first row corresponds to the first channel in first batch, second row -
to the second channel in the first batch, third row - to the first channel
in the second batch and the last - to the second channel in the second batch:
[[ 1, 0, 0, 0],
[ 0, 2, 0, 0],
[ 0, 0, 3, 0],
[ 0, 0, 0, 4]]
Is it possible to convert it into 4D array Y
(batch
x pool_size
x pool_size
x channels
)
without any loops using only numpy methods so that
Y[0, :, :, 0]
is
[[1, 0],
[0, 0]]
Y[0, :, :, 1]
is
[[0, 2],
[0, 0]]
Y[1, :, :, 0]
is
[[0, 0],
[3, 0]]
Y[1, :, :, 1]
is
[[0, 0],
[0, 4]]
UPD: For the input array
[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[ 13, 14, 15, 16]]
expected results are:
Y[0, :, :, 0]
is
[[1, 2],
[3, 4]]
Y[0, :, :, 1]
is
[[5, 6],
[7, 8]]
Y[1, :, :, 0]
is
[[9, 10],
[11, 12]]
Y[1, :, :, 1]
is
[[13, 14],
[15, 16]]
CodePudding user response:
y = y.reshape(y.shape[0],28,28,1)
CodePudding user response:
You can use the reshape and then use the swapaxes.
A = np.array([[ 1, 0, 0, 0],
[ 0, 2, 0, 0],
[ 0, 0, 3, 0],
[ 0, 0, 0, 4]])
B = A.reshape(2,2,2, 2)
Here is the output:
array([[[[1, 0],
[0, 0]],
[[0, 2],
[0, 0]]],
[[[0, 0],
[3, 0]],
[[0, 0],
[0, 4]]]])
2:
array([[[[ 1, 2],
[ 3, 4]],
[[ 5, 6],
[ 7, 8]]],
[[[ 9, 10],
[11, 12]],
[[13, 14],
[15, 16]]]])