python - 如何更新csr_matrix中的值

标签 python numpy scipy

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

我还尝试过 twoByte.toarray()[i] += 1twoByte.toarray()[0][i] += 1twoByte[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)

关于python - 如何更新csr_matrix中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56981077/

相关文章:

python - 等价于 Matlab 的聚类质量函数?

python - 使用 Selenium 时如何选择要启用的 Chrome 扩展

python - 如何更改 Python 安装的 tk 版本?

python - 将列表的列表转换为 Numpy 数组而不携带列表

machine-learning - sp_randint 是如何工作的?

python - scipy.ndimage.median_filter 如何处理均匀尺寸

python - python中的数值精确线性编程用于检查点是否可以线性分离?

python - 将单个 numpy 数组的值添加到其他 numpy 数组中的所有列

python - 检查两个 3D numpy 数组是否包含重叠的 2D 数组

python - numpy.getbuffer 导致 AttributeError : 'module' object has no attribute 'getbuffer'