在numpy Python中从稀疏矩阵生成密集矩阵

55

我有一个包含以下模式的Sqlite数据库:

termcount(doc_num, term , count)
Term Count
like 3
(doc1 , term1 ,12)
(doc1, term 22, 2)
.
.
(docn,term1 , 10)

这个矩阵可以被视为稀疏矩阵,因为每个文档都只包含非零值的很少词语。

我应该如何使用numpy从这个稀疏矩阵创建一个密集矩阵,因为我需要使用余弦相似度计算文档之间的相似性。

这个密集矩阵将看起来像一个表格,其中docid是第一列,所有的词语将列在第一行,其余单元格将包含计数。

2个回答

107
 from scipy.sparse import csr_matrix
 A = csr_matrix([[1,0,2],[0,3,0]])
 >>>A
 <2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>
 >>> A.todense()
   matrix([[1, 0, 2],
           [0, 3, 0]])
 >>> A.toarray()
      array([[1, 0, 2],
            [0, 3, 0]])

这是一个示例,演示了如何从scipy中将稀疏矩阵转换为密集矩阵。


11

我使用Pandas解决了这个问题。因为我们想要保留文档ID和术语ID。

from pandas import DataFrame 

# A sparse matrix in dictionary form (can be a SQLite database). Tuples contains doc_id        and term_id. 
doc_term_dict={('d1','t1'):12, ('d2','t3'):10, ('d3','t2'):5}

#extract all unique documents and terms ids and intialize a empty dataframe.
rows = set([d for (d,t) in doc_term_dict.keys()])  
cols = set([t for (d,t) in doc_term_dict.keys()])
df = DataFrame(index = rows, columns = cols )
df = df.fillna(0)

#assign all nonzero values in dataframe
for key, value in doc_term_dict.items():
    df[key[1]][key[0]] = value   

print df

输出:

    t2  t3  t1
d2  0  10   0
d3  5   0   0
d1  0   0  12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接