如何在numpy中转储布尔矩阵? [英] How to dump a boolean matrix in numpy?

查看:95
本文介绍了如何在numpy中转储布尔矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示为numpy布尔数组(G.adj.dtype == bool)的图.这是编写我自己的图形库的功课,因此我不能使用networkx.我想将其转储到文件中,以便我可以摆弄它,但是为了我的一生,我不知道如何使numpy以可恢复的方式转储它.

I have a graph represented as a numpy boolean array (G.adj.dtype == bool). This is homework in writing my own graph library, so I can't use networkx. I want to dump it to a file so that I can fiddle with it, but for the life of me I can't work out how to make numpy dump it in a recoverable fashion.

我尝试了G.adj.tofile,它正确地将图形写成(真)作为True/False的一长行.但是fromfile会在阅读此内容时使用barfs,给出一个1x1数组,而loadtxt会引发一个ValueError: invalid literal for int. np.savetxt有效,但将矩阵保存为0/1浮点数列表,并且loadtxt(..., dtype=bool)失败,并出现相同的ValueError.

I've tried G.adj.tofile, which wrote the graph correctly (ish) as one long line of True/False. But fromfile barfs on reading this, giving a 1x1 array, and loadtxt raises a ValueError: invalid literal for int. np.savetxt works but saves the matrix as a list of 0/1 floats, and loadtxt(..., dtype=bool) fails with the same ValueError.

最后,我用networkx.write_dot尝试了networkx.from_numpy_matrix,但是这使点源中的每个边缘[weight=True]破损了networkx.read_dot.

Finally, I've tried networkx.from_numpy_matrix with networkx.write_dot, but that gave each edge [weight=True] in the dot source, which broke networkx.read_dot.

推荐答案

保存包含元数据(dtype,维)的数组的最简单方法是使用

The easiest way to save your array including metadata (dtype, dimensions) is to use numpy.save() and numpy.load():

a = array([[False,  True, False],
           [ True, False,  True],
           [False,  True, False],
           [ True, False,  True],
           [False,  True, False]], dtype=bool)
numpy.save("data.npy", a)
numpy.load("data.npy")
# array([[False,  True, False],
#        [ True, False,  True],
#        [False,  True, False],
#        [ True, False,  True],
#        [False,  True, False]], dtype=bool)

a.tofile()numpy.fromfile()也可以工作,但是不保存任何元数据.您需要将dtype=bool传递给fromfile(),并将获得一维数组,该数组必须reshape() d为其原始形状.

a.tofile() and numpy.fromfile() would work as well, but don't save any metadata. You need to pass dtype=bool to fromfile() and will get a one-dimensional array that must be reshape()d to its original shape.

这篇关于如何在numpy中转储布尔矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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