Reputation: 193
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.
I made two [28x28]
images and put them into a [28x28x2]
array and saved Matlab
file.
Then I used scipy.io
load the array into python
.
However, my network is expecting a [2, 28, 28, 1]
tensor.
How can I convert [28x28x2]
array to a [2, 28, 28, 1]
tensor?
Upvotes: 1
Views: 192
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 usedtranspose
because I believe you wantarr[0]
to be a picture, and the same forarr[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