Emil
Emil

Reputation: 1722

Reshaping tensor in Numpy from 2D to 3D

I am using the EMNIST dataset and have the following variable X_train:

import scipy .io
emnist = scipy.io.loadmat(DIRECTORY + '/emnist-letters.mat')
data = emnist ['dataset']
X_train = data ['train'][0, 0]['images'][0, 0]

The shape of X_train is (124800, 784).

Now, I want to reshape this dataset so that it becomes a 3D tensor of the shape (124800, 28, 28).

I can reshape one instance of the data as follows:

X_train[index].reshape((28,28))

However, the following loop does not work:

for i in range(len(X_train)):
    X_train[i] = X_train[i].reshape((28,28))

What can I do to reshape my dataset so it gets the shape (124800, 28, 28)?

Upvotes: 0

Views: 420

Answers (1)

Stef
Stef

Reputation: 30579

You can reshape the whole array like this:

X_train = X_train.reshape((-1,28,28), order='F')

Matlab uses column-major order (see here), so you need to specify the order as order='F' in order to get the correct orientation. See the following example for the first letter (w): enter image description here

Upvotes: 1

Related Questions