gpt4 book ai didi

python - 从 npy 文件加载稀疏数组

转载 作者:太空狗 更新时间:2023-10-29 18:19:37 27 4
gpt4 key购买 nike

我正在尝试加载我之前保存的稀疏数组。保存稀疏数组很容易。尝试阅读它虽然很痛苦。 scipy.load 在我的稀疏数组周围返回一个 0d 数组。

import scipy as sp
A = sp.load("my_array"); A
array(<325729x325729 sparse matrix of type '<type 'numpy.int8'>'
with 1497134 stored elements in Compressed Sparse Row format>, dtype=object)

为了获得稀疏矩阵,我必须展平 0d 数组,或使用 sp.asarray(A)。这似乎是一种非常困难的做事方式。 Scipy 是否足够聪明,可以理解它加载了一个稀疏数组?有没有更好的方法来加载稀疏数组?

最佳答案

mmwrite/mmread scipy.io 中的函数可以以 Matrix Market 格式保存/加载稀疏矩阵。

scipy.io.mmwrite('/tmp/my_array',x)
scipy.io.mmread('/tmp/my_array').tolil()

mmwritemmread 可能就是您所需要的。它经过充分测试并使用众所周知的格式。

但是,以下可能会更快一些:

我们可以将行列坐标和数据保存为 npz 格式的一维数组。

import random
import scipy.sparse as sparse
import scipy.io
import numpy as np

def save_sparse_matrix(filename,x):
x_coo=x.tocoo()
row=x_coo.row
col=x_coo.col
data=x_coo.data
shape=x_coo.shape
np.savez(filename,row=row,col=col,data=data,shape=shape)

def load_sparse_matrix(filename):
y=np.load(filename)
z=sparse.coo_matrix((y['data'],(y['row'],y['col'])),shape=y['shape'])
return z

N=20000
x = sparse.lil_matrix( (N,N) )
for i in xrange(N):
x[random.randint(0,N-1),random.randint(0,N-1)]=random.randint(1,100)

save_sparse_matrix('/tmp/my_array',x)
load_sparse_matrix('/tmp/my_array.npz').tolil()

这是一些建议将稀疏矩阵保存在 npz 文件中的代码可能比使用 mmwrite/mmread 更快:

def using_np_savez():    
save_sparse_matrix('/tmp/my_array',x)
return load_sparse_matrix('/tmp/my_array.npz').tolil()

def using_mm():
scipy.io.mmwrite('/tmp/my_array',x)
return scipy.io.mmread('/tmp/my_array').tolil()

if __name__=='__main__':
for func in (using_np_savez,using_mm):
y=func()
print(repr(y))
assert(x.shape==y.shape)
assert(x.dtype==y.dtype)
assert(x.__class__==y.__class__)
assert(np.allclose(x.todense(),y.todense()))

产量

% python -mtimeit -s'import test' 'test.using_mm()'
10 loops, best of 3: 380 msec per loop

% python -mtimeit -s'import test' 'test.using_np_savez()'
10 loops, best of 3: 116 msec per loop

关于python - 从 npy 文件加载稀疏数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6282432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com