2016-06-16 35 views
17

我走了Udacity課程深學習,我碰到下面的代碼來:在numpy中,[:,None]選擇了什麼?

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]實際上在這裏做?

回答

15

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

numpy.newaxis

的newaxis對象可以在所有切片操作可以用來創建一個長度的軸線。 :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]]) 
13

None的一部分演示是NP.newaxis的別名。它創建一個長度爲1軸這對於矩陣multiplcation等

>>>> 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]]  
1

我來這裏了做同樣Udacity課程完全相同的問題後非常有用。我想要做的是轉換一個numpy.transpose([1,2,3])不起作用的一維numpy序列/數組。 所以我想添加就可以轉像這樣(source):

numpy.matrix([1, 2, 3]).T 

它導致:

matrix([[1], 
     [2], 
     [3]]) 

這是幾乎相同的(類型是不同的)到:

x=np.array([1, 2, 3]) 
x[:,None] 

但我認爲這是更容易記住...

相關問題