【发布时间】:2016-01-26 04:15:57
【问题描述】:
我正在尝试理解 scipy 中的稀疏矩阵,尤其是 csr_matrix 格式
假设我有以下文本
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}]
如何转换 csr_matrix 中的 token_counts ?
这是我目前尝试过的:
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
P.S:示例取自scipy documentation
【问题讨论】:
标签: python scipy sparse-matrix