fireman
fireman

Reputation: 193

convert [28,28,2] matlab array to [2, 28, 28, 1] tensor

I am learning tensorflow. After completing the tensorflow tutorial MNist for expert (https://www.tensorflow.org/get_started/mnist/pros), I am trying to use the trained model to run inference.

Upvotes: 1

Views: 192

Answers (1)

grovina
grovina

Reputation: 3077

Firstly, transpose the array so that 28x28x2 becomes 2x28x28 (3rd dimension goes first, then 1st then 2nd).

arr = arr.transpose((2, 0, 1))

Attention: you could have obtained the shape 2x28x28 by using arr.reshape((2, 28, 28)), but that would have messed up the order of your data. I used transpose because I believe you want arr[0] to be a picture, and the same for arr[1].

Then expand the array so that you get that last dimension

arr = np.expand_dims(arr, -1)

An example with 4x4 instead of 28x28:

>>> arr = np.empty((4, 4, 2))  # an empty array
>>> arr[..., :] = 0, 1  # first picture is all 0s and second is all 1s
>>> arr[..., 0]
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> arr[..., 1]
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
>>> arr.shape
(4, 4, 2)

Now the transformations

>>> arr = arr.transpose((2, 0, 1))
>>> arr = np.expand_dims(arr, -1)
>>> arr.shape
(2, 4, 4, 1)

Upvotes: 2

Related Questions