内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我正在上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
如何理解labels[:,None]
?
可以参考:
http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_duds.html
部分代码如下:
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]])
>>>> import numpy as NP >>>> a = NP.arange(1,5) >>>> print a [1 2 3 4] >>>> print a.shape (4,) >>>> print a[:,None].shape (4, 1) >>>> print a[:,None] [[1] [2] [3] [4]]