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

Time:12-31

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.

CodePudding user response:

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

CodePudding user response:

You can pass an Ellipsis plus None to the arrays indexer:

>>> a
array([[0, 1, 0],
       [1, 1, 1],
       [0, 0, 1]])

>>> a[..., None]
array([[[0],
        [1],
        [0]],

       [[1],
        [1],
        [1]],

       [[0],
        [0],
        [1]]])

(Credit to @hpaulj)

CodePudding user response:

As the docs points out, when the shapes are compatible as yours are, you can directly change the shape of the array too:

a = np.array([
    [0, 1, 0],
    [1, 1, 1],
    [0, 0, 1]
])

a.shape  = (1,)
a

# array([[[0], [1], [0]],
#        [[1], [1], [1]],
#        [[0], [0], [1]]])
  • Related