如何在python中检索julia存储在.jld文件中的稀疏矩阵?

2024-06-09 20:54:39 发布

您现在位置:Python中文网/ 问答频道 /正文

使用julia,我可以将稀疏矩阵保存在.jld文件中(该文件使用HDF5格式),如下所示:

a=spzeros(3,3);
a[1,1]=2.0
a[2,1]=1.0
a[3,1]=5
@save("sparsematrix.jld",a)

现在我想用python检索这个矩阵(使用h5py),所以我尝试了以下操作:

^{pr2}$

打印data将返回(3, 3, <HDF5 object reference>, <HDF5 object reference>, <HDF5 object reference>),因此我尝试使用:f[data[2]]访问对象引用,它返回<HDF5 dataset "00000001": shape (4,), type "<i8">,但现在我卡住了。在

那么如何从.jld文件中获取稀疏矩阵呢?在


Tags: 文件对象dataobjectsave格式矩阵hdf5
1条回答
网友
1楼 · 发布于 2024-06-09 20:54:39

好吧,我自己找到的,在我脑子里想着CSC格式之后:

import h5py 
from scipy.sparse import csc_matrix

filename="sparsematrix.jld"
f = h5py.File(filename, 'r')
data= f["a"][()]

column_ptr=f[data[2]][:]-1 ## correct indexing from julia (starts at 1)
indices=f[data[3]][:]-1 ## correct indexing
values =f[data[4]][:]
csc_matrix((values,indices,column_ptr), shape=(data[0],data[1])).toarray()

f.close()

相关问题 更多 >