在numpy中,[:,None]的选择是做什么的?

Hue*_*uey 32 python numpy

我正在深入学习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
Run Code Online (Sandbox Code Playgroud)

labels[:,None]这里到底做了什么?

hpa*_*ulj 30

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

numpy.newaxis

newaxis对象可用于所有切片操作,以创建长度为1的轴.:const:newaxis是'None'的别名,'None'可以代替它使用相同的结果.

http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.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]])
Run Code Online (Sandbox Code Playgroud)


GWW*_*GWW 22

NoneNP.newaxis的别名.它创建一个长度为1的轴.这对于矩阵乘法等很有用.

>>>> 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]]    
Run Code Online (Sandbox Code Playgroud)

  • 所以它与 np.reshape(a, (-1,1)) 相同,假设 a 的形状为 (n,) 其中 n 是任意整数? (2认同)

joh*_*jik 10

用简单的英语解释它,它允许在不同维数的两个数组之间进行操作。

它通过添加一个新的空维度来实现这一点,该维度将自动适应另一个数组的大小。

所以基本上如果:

Array1 = shape[100] 和 Array2 = shape[10,100]

Array1 * Array2 一般会报错。

Array1[:,None] * Array2 将工作。


Cod*_*ife 6

我在完成相同的 Udacity 课程后遇到完全相同的问题后来到这里。我想做的是转置一维 numpy 系列/数组,它不适用于 numpy.transpose([1, 2, 3])。所以我想补充一点,你可以像这样转置(来源):

numpy.matrix([1, 2, 3]).T
Run Code Online (Sandbox Code Playgroud)

其结果是:

matrix([[1],
        [2],
        [3]])
Run Code Online (Sandbox Code Playgroud)

这与以下内容几乎相同(类型不同):

x=np.array([1, 2, 3])
x[:,None]
Run Code Online (Sandbox Code Playgroud)

但我觉得这样更容易记住...