Save / load scipy array,sparse csr_matrix

本文介绍如何使用NumPy保存和加载CSR格式的稀疏矩阵,并提供了具体的方法实现。通过将CSR矩阵的三个关键属性:.data, .indices 和 .indptr 分别保存为NumPy数组文件,可以有效地进行稀疏矩阵的持久化存储。

A csr_matrix has 3 data attributes that matter: .data.indices, and .indptr. All are simple ndarrays, so numpy.save will work on them. Save the three arrays with numpy.save or numpy.savez, load them back with numpy.load, and then recreate the sparse matrix object with:

new_csr = csr_matrix((data, indices, indptr), shape=(M, N))



def save_sparse_csr(filename,array):

        np.savez(filename,data = array.data ,indices=array.indices,indptr =array.indptr, shape=array.shape )


def load_sparse_csr(npzfilename):
        loader = np.load(npzfilename)
        return csr_matrix((  loader['data'], loader['indices'], loader['indptr']),shape = loader['shape'])


def save_ids_array(filename,array):
        np.savez(filename+'.ids',data = array)


def load_ids_array(npzfilename):
        loader = np.load(npzfilename)
        return loader['data']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值