kumaran ragunathan
kumaran ragunathan

Reputation: 447

Correct way to reshape 3D array

I have a dataset with the shape (n, 4, 5, 5) in which "n" is the number of records, 4 channels, and each channel have 5 X 5 matrix. Keras CNN only accepts input with shape (n, width, height, channels). when I apply reshape to my dataset like

reshaped_dataset = dataset.reshape(-1, 5, 5, 4)

the reshaped_dataset is containing the data in the wrong order. I have posted 1 sample in my dataset .

[[[ 0.          0.          0.          1.42413757  0.        ]
  [ 0.          0.          1.82047845  0.          0.91023923]
  [ 0.          1.82047845  0.          0.          1.82047845]
  [ 1.42413757  0.          0.          0.          0.        ]
  [ 0.          0.91023923  1.82047845  0.          0.        ]]

 [[ 1.          0.          0.          0.5         0.        ]
  [ 0.          1.          0.25        0.          0.2       ]
  [ 0.          0.25        1.          0.          0.25      ]
  [ 0.5         0.          0.          1.          0.        ]
  [ 0.          0.2         0.25        0.          1.        ]]

 [[ 9.          9.         21.          9.          9.        ]
  [ 9.          9.         21.          9.          9.        ]
  [21.         21.         49.         21.         21.        ]
  [ 9.          9.         21.          9.          9.        ]
  [ 9.          9.         21.          9.          9.        ]]

 [[ 0.80952381  0.          0.          0.47619048  0.        ]
  [ 0.          1.66666667  0.66666667  0.          0.33333333]
  [ 0.          0.66666667  3.03333333  0.          0.66666667]
  [ 0.47619048  0.          0.          0.80952381  0.        ]
  [ 0.          0.33333333  0.66666667  0.          1.66666667]]]

how can I reshape my dataset in (n,5,5,4)

Upvotes: 0

Views: 328

Answers (2)

unutbu
unutbu

Reputation: 879511

You could use np.transpose to permute the dimensions of the array:

reshaped_dataset = dataset.transpose(0, 2, 3, 1)

If the axes of dataset represent (n, channel, width, height) then reshaped_dataset will have axes representing (n, width, height, channel).

Upvotes: 2

Aditya
Aditya

Reputation: 553

You can go from channel first to channel last using the following code:

import numpy as np

n = 5
data = np.random.randn(n, 4, 5, 5)

print(data.shape) # output - (5, 4, 5, 5)

data_in = np.moveaxis(data, 1, -1)

print(data_in.shape) # output - (5, 5, 5, 4)

Upvotes: 0

Related Questions