2014-04-25 67 views
4

我正在尋找一個乾淨的方式改變整數的向量成二進制值,其中的有在對應於作爲索引向量的值的列的2D陣列numpy的變換向量,以二元矩陣

v = np.array([1, 5, 3]) 
C = np.zeros((v.shape[0], v.max())) 

什麼我要找的是變換C++這個方式:

array([[ 1., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 1.], 
     [ 0., 0., 1., 0., 0.]]) 

我想出了這一點:

C[np.arange(v.shape[0]), v.T-1] = 1 

但我不知道是否有較少的詳細/更優雅的方法?

謝謝!

UPDATE

感謝您的意見!我的代碼中有一個錯誤:如果v中有0,它會將1放入錯誤的位置(最後一列)。相反,我必須將分類數據擴展爲包含0.

只要您僅處理稀疏矩陣,jrennie的答案對大型向量來說是一個巨大的勝利。在我來說,我需要返回的兼容性數組和轉化率的優勢完全 - 看到這兩個解決方案:

def permute_array(vector): 
     permut = np.zeros((vector.shape[0], vector.max()+1)) 
     permut[np.arange(vector.shape[0]), vector] = 1 
     return permut 

    def permute_matrix(vector): 
     indptr = range(vector.shape[0]+1) 
     ones = np.ones(vector.shape[0]) 
     permut = sparse.csr_matrix((ones, vector, indptr)) 
     return permut 

    In [193]: vec = np.random.randint(1000, size=1000) 
    In [194]: np.all(permute_matrix(vec) == permute_array(vec)) 
    Out[194]: True 

    In [195]: %timeit permute_array(vec) 
    100 loops, best of 3: 3.49 ms per loop 

    In [196]: %timeit permute_matrix(vec) 
    1000 loops, best of 3: 422 µs per loop 

現在,增加轉換:

def permute_matrix(vector): 
     indptr = range(vector.shape[0]+1) 
     ones = np.ones(vector.shape[0]) 
     permut = sparse.csr_matrix((ones, vector, indptr)) 
     return permut.toarray() 

    In [198]: %timeit permute_matrix(vec) 
    100 loops, best of 3: 4.1 ms per loop 
+3

你的方式對我來說很好!你可以不使用'.T'來執行 – YXD

+0

你試圖實現一個置換矩陣。我認爲你的解決方案很好。正如E先生所說,沒有T.請參閱[https://stackoverflow.com/]中的這個問題[SO]。想知道是否在實現置換矩陣的scipy.linalg中有一些函數。 – Tengis

+0

@Tengis你的鏈接不起作用。 – askewchan

回答

4

到您的解決方案的缺點是,對於大值而言效率低下。如果你想要一個更有效的表示,創建SciPy的稀疏矩陣,例如:

import scipy.sparse 
import numpy 

indices = [1, 5, 3] 
indptr = range(len(indices)+1) 
data = numpy.ones(len(indices)) 
matrix = scipy.sparse.csr_matrix((data, indices, indptr)) 

閱讀有關Yale Formatscipy's csr_matrix更好地瞭解對象(索引,indptr,數據)和用法。

請注意,我沒有從上述代碼中的索引中減去1。如果這是你想要的,使用indices = numpy.array([1, 5, 3])-1