我正在深入学习Udacity课程,我遇到了以下代码:
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
标签[:,无]实际上在这里做什么?
解决方法:
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.
使用部分代码进行演示
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]])
标签:python,numpy
来源: https://codeday.me/bug/20191003/1850762.html