Skip to content
Advertisement

In numpy, what does selection by [:,None] do?

I’m taking the Udacity course on deep learning and I came across the following code:

def reformat(dataset, labels):
    dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
    # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
    labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
    return dataset, labels

What does labels[:,None] actually do here?

Advertisement

Answer

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

numpy.newaxis

The newaxis object can be used in all slicing operations to create an axis of length one. :const: newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.

http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.html

Demonstrating with part of your code

In [154]: labels=np.array([1,3,5])

In [155]: labels[:,None]
Out[155]: 
array([[1],
       [3],
       [5]])
 
In [157]: np.arange(8)==labels[:,None]
Out[157]: 
array([[False,  True, False, False, False, False, False, False],
       [False, False, False,  True, False, False, False, False],
       [False, False, False, False, False,  True, False, False]], dtype=bool)

In [158]: (np.arange(8)==labels[:,None]).astype(int)
Out[158]: 
array([[0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0]])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement