在python中保存和加载一个Numpy矩阵

时间:2021-08-24 16:02:43

Can someone gives me an example of how to save a 2-d matrix in a file and reloading it for further use?

有人能给我一个如何在文件中保存一个二维矩阵并重新加载它以供进一步使用的例子吗?

2 个解决方案

#1


20  

>>> import numpy
>>> mat = numpy.matrix("1 2 3; 4 5 6; 7 8 9")
>>> mat.dump("my_matrix.dat")
>>> mat2 = numpy.load("my_matrix.dat")

#2


5  

you can pickle your matrix:

你可以腌制你的矩阵:

 >> import numpy
 >> import pickle
 >> b=numpy.matrix('1 2; 3 4')
 >> f=open('test','w')
 >> pickle.dump(b, f)
 >> f.close()

 >> f2 = open('test', 'r')
 >> s = pickle.load(f2)
 >> f2.close()
 >> s

    matrix([[1, 2],
            [3, 4]])

Tamas answer is much better than this: numpy matrixes objects have a direct method to pickle them.

Tamas的回答要比这个好得多:numpy矩阵对象有一个直接的方法来pickle它们。

In any case take into account that the pickle library is a general tool for saving python objects including classes.

无论如何,请考虑到pickle库是保存python对象(包括类)的通用工具。

#1


20  

>>> import numpy
>>> mat = numpy.matrix("1 2 3; 4 5 6; 7 8 9")
>>> mat.dump("my_matrix.dat")
>>> mat2 = numpy.load("my_matrix.dat")

#2


5  

you can pickle your matrix:

你可以腌制你的矩阵:

 >> import numpy
 >> import pickle
 >> b=numpy.matrix('1 2; 3 4')
 >> f=open('test','w')
 >> pickle.dump(b, f)
 >> f.close()

 >> f2 = open('test', 'r')
 >> s = pickle.load(f2)
 >> f2.close()
 >> s

    matrix([[1, 2],
            [3, 4]])

Tamas answer is much better than this: numpy matrixes objects have a direct method to pickle them.

Tamas的回答要比这个好得多:numpy矩阵对象有一个直接的方法来pickle它们。

In any case take into account that the pickle library is a general tool for saving python objects including classes.

无论如何,请考虑到pickle库是保存python对象(包括类)的通用工具。