Python:如何使用python存储稀疏矩阵?

Bhu*_*raj 8 python numpy sparse-matrix

我在python中使用稀疏矩阵输出,我需要将这个稀疏矩阵存储在我的硬盘中,我该怎么办?如果我应该创建一个数据库,那我该怎么办?这是我的代码:

import nltk
import cPickle
import numpy
from scipy.sparse import lil_matrix
from nltk.corpus import wordnet as wn
from nltk.corpus import brown
f = open('spmatrix.pkl','wb')
def markov(L):
    count=0
    c=len(text1)
    for i in range(0,c-2):
        h=L.index(text1[i])
        k=L.index(text1[i+1])
        mat[h,k]=mat[h,k]+1//matrix
    cPickle.dump(mat,f,-1)



text = [w for g in brown.categories() for w in brown.words(categories=g)]
text1=text[1:500]
arr=set(text1)
arr=list(arr)
mat=lil_matrix((len(arr),len(arr)))
markov(arr)
f.close()
Run Code Online (Sandbox Code Playgroud)

我需要将这个"mat"存储在一个文件中,并且应该使用坐标来访问矩阵的值.

稀疏矩阵的结果是这样的:`稀疏矩阵的结果是这样的:

(173, 168) 2.0 (173, 169) 1.0 (173, 172) 1.0 (173, 237) 4.0 (174, 231) 1.0 (175, 141) 1.0 (176, 195) 1.0 
Run Code Online (Sandbox Code Playgroud)

但是当我将它存储到一个文件中并阅读相同的内容时我会这样:

(0, 68) 1.0 (0, 77) 1.0 (0, 95) 1.0 (0, 100)    1.0 (0, 103)    1.0 (0, 110) 1.0 (0, 112)   2.0 (0, 132)    1.0 (0, 133)    2.0 (0, 139)    1.0 (0, 146)    2.0 (0, 156)    1.0 (0, 157)    1.0 (0, 185)    1.0
Run Code Online (Sandbox Code Playgroud)

ide*_*ide 6

假设你有一个numpy matrix或者ndarray你的问题和标签暗示,你可以使用一种dump方法和load功能:

your_matrix.dump('output.mat')
another_matrix = numpy.load('output.mat')
Run Code Online (Sandbox Code Playgroud)


Jos*_*del 4

注意:这个答案是为了回应现在提供代码的修改问题。

你不应该调用cPickle.dump()你的函数。创建稀疏矩阵,然后将其内容转储到文件中。

尝试:

def markov(L):
   count=0
   c=len(text1)
   for i in range(0,c-2):
       h=L.index(text1[i])
       k=L.index(text1[i+1])
       mat[h,k]=mat[h,k]+1 #matrix


text = [w for g in brown.categories() for w in brown.words(categories=g)]
text1=text[1:500]
arr=set(text1)
arr=list(arr)
mat=lil_matrix((len(arr),len(arr)))
markov(arr)
f = open('spmatrix.pkl','wb')
cPickle.dump(mat,f,-1)
f.close()
Run Code Online (Sandbox Code Playgroud)

  • 您现在似乎正在使用其他方法,因为 mat.dump() 没有出现在您的代码或我的建议中。我很抱歉,但我没有时间为您提供进一步的帮助。祝你好运。 (3认同)