为了账号安全,请及时绑定邮箱和手机立即绑定

以可移植数据格式保存/加载scipy稀疏csr_matrix

以可移植数据格式保存/加载scipy稀疏csr_matrix

米琪卡哇伊 2020-02-01 15:58:19
如何csr_matrix以可移植格式保存/加载稀疏稀疏?稀疏稀疏矩阵是在Python 3(Windows 64位)上创建的,可在Python 2(Linux 64位)上运行。最初,我使用pickle(协议= 2,fix_imports = True),但是从Python 3.2.2(Windows 64位)到Python 2.7.2(Windows 32位)不起作用,并出现错误:TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).接下来,尝试了numpy.save,numpy.load以及,scipy.io.mmwrite()并且scipy.io.mmread()这些方法都不起作用。
查看完整描述

3 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

 SciPy 1.19现在具有scipy.sparse.save_npz和scipy.sparse.load_npz。


from scipy import sparse


sparse.save_npz("yourmatrix.npz", your_matrix)

your_matrix_back = sparse.load_npz("yourmatrix.npz")

对于这两个函数,file参数也可以是类似文件的对象(即的结果open),而不是文件名。


从Scipy用户组得到了答案:


一个csr_matrix有3个数据属性此事:.data,.indices,和.indptr。都是简单的ndarray,因此numpy.save可以在它们上使用。使用numpy.save或保存三个数组numpy.savez,使用加载它们numpy.load,然后使用以下方法重新创建稀疏矩阵对象:


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(filename):

    loader = np.load(filename)

    return csr_matrix((loader['data'], loader['indices'], loader['indptr']),

                      shape=loader['shape'])


查看完整回答
反对 回复 2020-02-01
?
呼如林

TA贡献1798条经验 获得超3个赞

尽管您写的内容scipy.io.mmwrite并scipy.io.mmread没有为您工作,但我只想补充一下它们的工作方式。这个问题是没有。1 Google命中,所以我本人开始np.savez并开始使用pickle.dump简单明显的scipy函数。它们为我工作,不应由尚未尝试过它们的人监督。


from scipy import sparse, io


m = sparse.csr_matrix([[0,0,0],[1,0,0],[0,1,0]])

m              # <3x3 sparse matrix of type '<type 'numpy.int64'>' with 2 stored elements in Compressed Sparse Row format>


io.mmwrite("test.mtx", m)

del m


newm = io.mmread("test.mtx")

newm           # <3x3 sparse matrix of type '<type 'numpy.int32'>' with 2 stored elements in COOrdinate format>

newm.tocsr()   # <3x3 sparse matrix of type '<type 'numpy.int32'>' with 2 stored elements in Compressed Sparse Row format>

newm.toarray() # array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=int32)


查看完整回答
反对 回复 2020-02-01
  • 3 回答
  • 0 关注
  • 435 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信