首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以便携数据格式保存/加载scipy sparse csr_matrix

以便携数据格式保存/加载scipy sparse csr_matrix
EN

Stack Overflow用户
提问于 2012-01-22 02:20:42
回答 6查看 62.9K关注 0票数 89

如何以便携格式保存/加载scipy sparse csr_matrix?scipy稀疏矩阵是在Python 3 (Windows 64位)上创建的,以在Python 2 (Linux 64位)上运行。最初,我使用pickle (与protocol=2和fix_imports=True一起使用),但从Python3.2.2(Windows64位)到Python2.7.2(Windows32位)不起作用,并得到以下错误:

TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).

接下来,我尝试了numpy.savenumpy.load以及scipy.io.mmwrite()scipy.io.mmread(),但这些方法都不起作用。

EN

回答 6

Stack Overflow用户

发布于 2015-03-12 05:55:28

尽管你写了,但scipy.io.mmwritescipy.io.mmread并不适合你,我只想补充一下它们是如何工作的。这个问题是谷歌的头号热门问题,所以我自己从np.savezpickle.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)
票数 38
EN

Stack Overflow用户

发布于 2017-04-03 18:36:23

票数 17
EN

Stack Overflow用户

发布于 2012-01-22 05:17:10

假设您在两台机器上都安装了scipy,那么您可以只使用pickle

但是,在酸洗numpy数组时,请务必指定二进制协议。否则你会得到一个很大的文件。

无论如何,你应该能够做到这一点:

import cPickle as pickle
import numpy as np
import scipy.sparse

# Just for testing, let's make a dense array and convert it to a csr_matrix
x = np.random.random((10,10))
x = scipy.sparse.csr_matrix(x)

with open('test_sparse_array.dat', 'wb') as outfile:
    pickle.dump(x, outfile, pickle.HIGHEST_PROTOCOL)

然后,您可以使用以下命令加载它:

import cPickle as pickle

with open('test_sparse_array.dat', 'rb') as infile:
    x = pickle.load(infile)
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8955448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档