You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在内存不足时将scipy.sparse.csr_matrix直接保存为TXT/CSV?

解决方法

一、直接将csr_matrix保存为常规矩阵格式(无需转换为np.array)

csr_matrix是按行存储的结构,我们可以逐行生成完整行数据并写入文件,全程只占用单一行的内存:

from scipy.sparse import csr_matrix

# 假设你的稀疏矩阵为csr_mat
rows, cols = csr_mat.shape

# 保存为txt格式
with open('output.txt', 'w') as f:
    for row_idx in range(rows):
        # 提取当前行的非零元素位置与值
        start = csr_mat.indptr[row_idx]
        end = csr_mat.indptr[row_idx + 1]
        non_zero_cols = csr_mat.indices[start:end]
        non_zero_vals = csr_mat.data[start:end]
        
        # 初始化当前行为全0列表
        current_row = [0.0] * cols
        # 填充非零值
        for col, val in zip(non_zero_cols, non_zero_vals):
            current_row[col] = val
        
        # 写入文件
        f.write(' '.join(map(str, current_row)) + '\n')

如果要保存为csv格式,只需把' '.join替换为','.join即可。

二、无需Python加载直接解压.npz文件

.npz本质是ZIP压缩包,内部包含多个.npy文件(对应稀疏矩阵的data、indices、indptr、shape等核心属性)。直接用Bash的unzip命令就能解压:

unzip your_matrix.npz

解压后会得到类似arr_0.npy、arr_1.npy的文件,若要查看文件内容,可通过简单的Python命令行执行:

python -c "import numpy as np; print(np.load('arr_0.npy'))"

内容的提问来源于stack exchange,提问作者Qba Liu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:05:20