I’m facing some problems getting an array into the right shape to use it as an input into a convolutional neural net:
My array has the shape (100,64,64)
, but I’d need it to be (100,64,64,1)
. I realize it looks a bit odd, but I basically want to pack every single entry into a separate array.
A simplified example, with a 2D array, where the analogous would be from (3,3)
to (3,3,1)
:
[[0,1,0], [[[0],[1],[0]],
[1,1,1], [[1],[1],[1]],
[0,0,1]] [[0],[0],[1]]]
Is there a convenient way to do this using numpy?
I’ve tried to use the function numpy.reshape
: With which I know, how to “add” another array wrapping the original one.
import numpy as np
data = data.reshape((1,)+data.shape)
This gives the output for data.shape
: (1,100,64,64)
.
Is there a way to add a dimension at the “inner end”?
If I try data.reshape(data.shape+(,1))
, I get an invalid syntax error.
Advertisement
Answer
You can reshape using:
a[:,:,None]
Or, programmatically (works for any number of dimensions):
a.reshape((*a.shape,1))
example
a = np.array([[0,1,0],
[1,1,1],
[0,0,1]])
# array([[0, 1, 0],
# [1, 1, 1],
# [0, 0, 1]])
a[:,:,None] # or a.reshape((*a.shape,1))
# array([[[0], [1], [0]],
# [[1], [1], [1]],
# [[0], [0], [1]]])