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
剛剛在維基百科上看到,應該使用另一種格式來構建csr。感謝您指出它 – user1043144
@ user1043144感謝您提到維基百科。 [稀疏矩陣](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR.2C_CRS_or_Yale_format.29)頁確實做了一個乾淨而徹底的工作,解釋壓縮中使用'indptr'的複雜方式稀疏行(CSR)aka壓縮行存儲(CRS)又名耶魯格式。關於這個東西的scipy文檔實在令人失望,但我一直假設他們正在定義一些特定於其實現的東西。 – nealmcb
通常我們不直接操作'indptr'。用於乘法等的'csr'代碼是編譯好的,不能直接使用。甚至諸如行總和或索引的任務都是用矩陣乘法執行的。但是有直接訪問CSR行的問題。在'[scipy] indptr'上搜索。 – hpaulj