Reshape 2D into 4D array
Asked Answered
P

2

6

Hello question regarding reshaping an array.

I have an array train_x (2D) which content is (103,784)

In this case 103 is the amount of examples.

784 is the input of my neural network.

Now I want to reshape from 2D to 4D

I use the following command:

train_x = np.reshape(train_x, (103, 28, 28, 1))

Is it correct that in this case 103 is still the amount of training examples and that in this case my input 784 is devided into a matrix of 28x28? 1 in this case is my channel, not using RGB (otherwhise the channel should be 3).

If my assumption is not correct please can somebody advice how to reshape from 2D to 4D to archive the above? tnx

Paulson answered 4/10, 2018 at 7:12 Comment(1)
Test this with a smaller example, for example np.arange(12).reshape(3,4).reshape(3,2,2,1)Dancer
S
2

Your assumption is correct. The NumPy doc about reshape states:

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.

train_x with shape (103, 784) would ravel to:

[img_0[0], ..., img_0[783], img_1[0], ..., img_1[783], ..., img_102[0], img_102[783]]

Which is then reshaped to 103 images of 28x28x1 with the reshape command from your question, as intended.

You should make sure that the flat 784 values have been raveled in the same order that you are using to unravel them, row-major or column-major. If you are unsure, a quick sanity check would be to plot one of the images after reshaping.

Slat answered 4/10, 2018 at 12:15 Comment(0)
P
1

Alternatively, you can use the following.

train_X = X_train.reshape(X_train.shape[0],28,28,1)

provided X-train has shape of (103,784)

Peashooter answered 6/10, 2020 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.