I’m taking the Udacity course on deep learning and I came across the following code:
JavaScript
x
6
1
def reformat(dataset, labels):
2
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
3
# Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
4
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
5
return dataset, labels
6
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
JavaScript
1
20
20
1
In [154]: labels=np.array([1,3,5])
2
3
In [155]: labels[:,None]
4
Out[155]:
5
array([[1],
6
[3],
7
[5]])
8
9
In [157]: np.arange(8)==labels[:,None]
10
Out[157]:
11
array([[False, True, False, False, False, False, False, False],
12
[False, False, False, True, False, False, False, False],
13
[False, False, False, False, False, True, False, False]], dtype=bool)
14
15
In [158]: (np.arange(8)==labels[:,None]).astype(int)
16
Out[158]:
17
array([[0, 1, 0, 0, 0, 0, 0, 0],
18
[0, 0, 0, 1, 0, 0, 0, 0],
19
[0, 0, 0, 0, 0, 1, 0, 0]])
20