如何保存和加载 scipy 稀疏 csr 矩阵的字典? [英] How to save and load a dictionary of scipy sparse csr matrices?
问题描述
我有一个 dict
的 scipy.sparse.csr_matrix
对象作为值,带有整数键.如何将其保存在单独的文件中?
I have a dict
of scipy.sparse.csr_matrix
objects as values, with integer keys. How can I save this in a separate file?
如果我对每个条目都有一个常规的 ndarray
,那么我可以用 json
序列化它,但是当我用稀疏矩阵尝试这个时:
If I had a regular ndarray
for each entry, then I could serialize it with json
, but when I try this with a sparse matrix:
with open('filename.txt', 'w') as f:
f.write(json.dumps(the_matrix))
我收到一个类型错误:
TypeError: <75x75 稀疏矩阵类型 '
如何使用整数键和稀疏 csr 矩阵值保存字典?
How can I save my dictionary with keys that are integers and values that are sparse csr matrices?
推荐答案
我在尝试保存值为 csr_matrix 的字典时遇到了同样的问题.使用pickle将其转储到磁盘.文件处理程序应以wb"模式打开.
I faced this same issue trying to save a dictionary whose values are csr_matrix. Dumped it to disk using pickle. file handler should be opened in "wb" mode.
import pickle
pickle.dump(csr_dict_obj, open("csr_dict.pkl","wb"))
使用重新加载字典.
csr_dict = pickle.load(open("csr_dict.pkl","rb"))
这篇关于如何保存和加载 scipy 稀疏 csr 矩阵的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!