Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to wrap every single entry of an numpy.ndarray into a separate array?

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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.

>Solution :

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]]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading