如何保存和加载 scipy 稀疏 csr 矩阵的字典? [英] How to save and load a dictionary of scipy sparse csr matrices?

查看:92
本文介绍了如何保存和加载 scipy 稀疏 csr 矩阵的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dictscipy.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 稀疏矩阵类型 ''以压缩稀疏行格式存储 10 个元素>不是 JSON 可序列化的

如何使用整数键和稀疏 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆