为什么 scipy.sparse.csr_matrix 没有存储传递给它的所有值?

Why is the scipy.sparse.csr_matrix not storing all the values being passed to it?

所以我目前正在尝试在 csr_format 中存储一个大型稀疏数据集(490 万行和 6000 列)。密集格式会导致内存错误,因此我从 tsv 文件中逐行加载它。 这是我的做法:

import numpy as np
from scipy.sparse import csr_matrix
rows=np.empty(4865518,dtype=np.int16)
cols=np.empty(165050535,dtype=np.int16)
values=np.empty(165050535,dtype=np.int16)
labels=np.empty(4865517,dtype=np.int8)
file=open(r'HI-union-allFeatures\HI-union-allFeatures-nonZero-train0.tsv','r')
count=0
nnz=0
col_count=0
for l in file:
    if count>0:
        l=l.strip().split("\t")
        line=l[2:-1]
        labels[count-1]=l[-1]
        for pair in line:
            pair=pair.split()
            cols[col_count]=pair[0]
            cols[col_count]-=3
            values[col_count]=pair[1]
            col_count+=1
        nnz+=len(line)
        rows[count]=nnz        
    count+=1
cols.astype(np.int16,copy=False) #cols gets stored as 32 bit for some reason.
cols.shape #(165050535,)
rows.shape #(4865518,)
values.shape #(165050535,)
data=csr_matrix((values, cols, rows),copy=False)
data.nnz #30887
data.data.shape #should match values.shape but output is (30887,)
data.indices.shape #should match cols.shape but output is (30887,)
data.indptr.shape #matches rows.shape (4865518,)

但是在创建 csr_matrix 之后,它只是删除了一些值。我不明白为什么。这是显示 data.data.shape 与 values.shape 不匹配的屏幕截图。我还验证了原始行、列和值数组中的数据,它们完美地代表了数据,所以我不明白这种行为。我的电脑没有 运行 内存不足,我有 16gb 的内存,这个程序几乎不占用 1GB。编辑:这是我在这里的第一个问题,如果我没有 post 正确,我很抱歉。任何帮助都会很棒。 Link to the screenshot

np.empty 不会将数组初始化为零。 rows[0] 的值可以是任何值。

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution

Int16 的最大值为 32767。您的行指针的最大值为 1.65 亿。这就是为什么您的数据现在小于 int16。

这两件事都是大问题。没有示例数据,无法提供有效的修复作为答案。