我有一个文档术语矩阵,使用语料库中共同出现的术语构建,如here所述:
vocabulary = {} # map terms to column indices
data = [] # values (maybe weights)
row = [] # row (document) indices
col = [] # column (term) indices
import scipy
for i, doc in enumerate(bloblist):
for term in doc:
# get column index, adding the term to the vocabulary if needed
j = vocabulary.setdefault(term, len(vocabulary))
data.append(1) # uniform weights
row.append(i)
col.append(j)
A = scipy.sparse.coo_matrix((data, (row, col)))
>>>print A
(0, 0) 1
(0, 1) 1
(0, 2) 1
(0, 3) 1
...
现在我想将它导出到csv或在db中写入。我无法弄清楚如何去做,我不知道如何处理稀疏矩阵。
当我尝试时,我总是收到此错误:
TypeError: 'coo_matrix' object has no attribute '__getitem__'
答案 0 :(得分:2)
请查看input/output section of scipy.您可以使用mmwrite
使用matrix market format来编写矩阵,DEMO是稀疏矩阵存储的标准格式。
以下示例创建随机稀疏矩阵并将其写为MM文件:
>>> import scipy.sparse
>>> A = scipy.sparse.rand(20, 20)
>>> print A
(3, 4) 0.0579085844686
(14, 9) 0.914421740712
(15, 10) 0.622861279405
(5, 17) 0.83146022149
>>> import scipy.io
>>> scipy.io.mmwrite('output', A)
output.mtx的内容:
→ cat output.mtx
%%MatrixMarket matrix coordinate real general
%
20 20 4
4 5 0.05790858446861069
15 10 0.9144217407118101
16 11 0.6228612794046831
6 18 0.8314602214903816
答案 1 :(得分:0)
scipy
有许多稀疏矩阵格式。您可以使用允许访问其成员的to_csc()
或to_csr()
等方法将矩阵转换为其他类型之一