2015-10-26 54 views
2

我想了解SciPy的尤其是csr_matrix格式稀疏矩陣指針在稀疏矩陣在python SciPy的

假設我有以下文字

docs = ['hello world hello', 'goodbye cruel world'] 

我記號化他們,並得到字典列表帶有令牌出現和帶有token_ids的字典。

ids_token = {0: 'world', 1: 'hello', 2: 'cruel', 3: 'goodbye'} 
token_counts = [{0: 1, 1: 2}, {0: 1, 2: 1, 3: 1}] 

我怎麼能改造token_counts在csr_matrix?

這裏是我試過到目前爲止:

data = [item for sublist in token_counts for item in sublist.values()] 
print 'data:', data 

indices = [item for sublist in token_counts for item in sublist.keys()] 
print 'indices:', indices 

indptr = [0] + [len(item) for item in token_counts] 
print 'pointers:', indptr 

#now I create the matrix 
sp_matrix = csr_matrix((data, indices, indptr), dtype=int) 
print sp_matrix.toarray() 

import pandas as pd 
pd.DataFrame(sp_matrix.toarray().transpose(), index = ids_token.values()) 

結果是不是有什麼期望,在最後一行其中零。

我懷疑問題出在指針indptr,我錯過了什麼?

任何幫助讚賞

更新 這就是我想獲得

 doc0 doc11 
cruel 0 1 
goodbye 0 1 
hello 2 0 
world 1 1 

PS:例子從scipy documentation

回答

2

拍攝,如果你給一個這將有助於樣本矩陣;你試圖製作的東西。

通常我們不會嘗試直接指定csr值。特別是indptr值有點模糊。 coo風格的投入一般較好,(Data_array, (i_array, j_array)),其中M[i,j] = datasparse自動將其轉換爲csr格式。

dok格式也很方便。那裏矩陣被存儲爲字典,其中元組(i,j)是關鍵。

In [151]: data = [item for sublist in token_counts for item in sublist.values()] 
In [152]: rows = [item for sublist in token_counts for item in sublist.keys()] 
In [153]: cols = [i for i,sublist in enumerate(token_counts) for item in sublist.keys()] 
In [155]: M=sparse.csr_matrix((data,(rows,cols))) 
In [156]: M 
Out[156]: 
<4x2 sparse matrix of type '<class 'numpy.int32'>' 
    with 5 stored elements in Compressed Sparse Row format> 
In [157]: M.A 
Out[157]: 
array([[1, 1], 
     [2, 0], 
     [0, 1], 
     [0, 1]], dtype=int32) 

看的M屬性,看看你能如何與indptr格式構造它:

In [158]: M.data 
Out[158]: array([1, 1, 2, 1, 1], dtype=int32) 
In [159]: M.indices 
Out[159]: array([0, 1, 0, 1, 1], dtype=int32) 
In [160]: M.indptr 
Out[160]: array([0, 2, 3, 4, 5], dtype=int32) 

稀疏矩陣的str顯示列舉了非零元素(一個DOK格式會是什麼樣子這在內部)。

In [161]: print(M) 
    (0, 0) 1 
    (0, 1) 1 
    (1, 0) 2 
    (2, 1) 1 
    (3, 1) 1 
+1

剛剛在維基百科上看到,應該使用另一種格式來構建csr。感謝您指出它 – user1043144

+0

@ user1043144感謝您提到維基百科。 [稀疏矩陣](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR.2C_CRS_or_Yale_format.29)頁確實做了一個乾淨而徹底的工作,解釋壓縮中使用'indptr'的複雜方式稀疏行(CSR)aka壓縮行存儲(CRS)又名耶魯格式。關於這個東西的scipy文檔實在令人失望,但我一直假設他們正在定義一些特定於其實現的東西。 – nealmcb

+0

通常我們不直接操作'indptr'。用於乘法等的'csr'代碼是編譯好的,不能直接使用。甚至諸如行總和或索引的任務都是用矩陣乘法執行的。但是有直接訪問CSR行的問題。在'[scipy] indptr'上搜索。 – hpaulj