Python 如何更新csr_矩阵中的值

Python 如何更新csr_矩阵中的值,python,numpy,scipy,Python,Numpy,Scipy,我创建了一个大小分别为16^4和16^8的csr_矩阵。但是我需要更新csr_矩阵中的值,那么如何更新稀疏矩阵中的值呢 我还尝试了twoByte.toarray()[I]+=1,twoByte.toarray()[0][I]+=1和twoByte[0].toarray()[I]+=1,但它不起作用。下面是代码片段 feature_matrix_two = csr_matrix((len(files),16**4),dtype=int) feature_matrix_four = csr_matr

我创建了一个大小分别为16^4和16^8的csr_矩阵。但是我需要更新csr_矩阵中的值,那么如何更新稀疏矩阵中的值呢

我还尝试了
twoByte.toarray()[I]+=1
twoByte.toarray()[0][I]+=1
twoByte[0].toarray()[I]+=1
,但它不起作用。下面是代码片段

feature_matrix_two = csr_matrix((len(files),16**4),dtype=int)
feature_matrix_four = csr_matrix((len(files),16**6),dtype=int)

k=0

byte_feature_file=open('bigramresult.csv','w+')

for file in files:
    byte_feature_file.write(file+",")
    if(file.endswith("txt")):
        with open('byteFiles/'+file,"r") as byte_code:
            twoByte = csr_matrix((1,16**4),dtype = int)
            fourByte = csr_matrix((1,16**8),dtype = int)
            for row in byte_code:
                codes = row.rstrip().split(" ")
                codes_2g = codes[:-1]
                codes_4g = codes[:-2]
                for i in range(len(codes_2g)):
                    codes_2g[i] += codes[i+1]
                for i in range(len(codes_4g)):
                    codes_4g[i] += codes[i+1]+codes[i+2]

                twoByteCode = []
                for i in codes_2g:
                    if '??' not in i:
                        twoByteCode += [int(i,16)]
                fourByteCode = []
                for i in codes_4g:
                    if '??' not in i:
                        fourByteCode += [int(i,16)]

                for i in twoByteCode:
                    twoByte[i] += 1

                for i in fourByteCode:
                    fourByte[i] += 1
            byte_code.close()
            feature_matrix_two[k] = twoByte
            feature_matrix_four[k] = fourByte

    for i in feature_matrix_two[k]:
        byte_feature_file.write(str(i)+",")
    for i in feature_matrix_four[k]:
        byte_feature_file.write(str(i)+",")

    byte_feature_file.write("\n")
    k+=1

根据代码,我认为您不需要稀疏矩阵,您可以使用dict对象,例如:

from collections import defaultdict 
twoByte = defaultdict(int)
fourByte = defaultdict(int)

根据代码,我认为您不需要稀疏矩阵,您可以使用dict对象,例如:

from collections import defaultdict 
twoByte = defaultdict(int)
fourByte = defaultdict(int)

您是否阅读了
scipy.sparse
文档,特别是关于
csr
(但也包括
lil
)的文档?你玩过小矩阵吗,比如(1,10)或(10,10)形状?我认为你不应该马上就开始制作类似于
csv
文件的大数组。你的出发点是什么?一些“机器学习”教程?是的,我阅读了文档,但没有发现它对这个查询有用。我首先尝试了(1,16)的小尺寸数组,但它不起作用。稀疏矩阵是2d(根据定义)的,您将其创建为(1,N)形状
twoByte[0,n]=1
将元素设置为1(但您将得到警告)。因为第一个维度是1,所以唯一允许的索引是0。但一般来说,您不应该逐个设置或增加
csr
矩阵的元素值。这种格式不是为此而设计的。演示如何以增量方式构建csr矩阵。您是否阅读了
scipy.sparse
文档,尤其是
csr
(还有
lil
)文档?你玩过小矩阵吗,比如(1,10)或(10,10)形状?我认为你不应该马上就开始制作类似于
csv
文件的大数组。你的出发点是什么?一些“机器学习”教程?是的,我阅读了文档,但没有发现它对这个查询有用。我首先尝试了(1,16)的小尺寸数组,但它不起作用。稀疏矩阵是2d(根据定义)的,您将其创建为(1,N)形状
twoByte[0,n]=1
将元素设置为1(但您将得到警告)。因为第一个维度是1,所以唯一允许的索引是0。但一般来说,您不应该逐个设置或增加
csr
矩阵的元素值。这种格式不是为此而设计的。演示如何增量构造csr矩阵。