从二进制文件存储/加载numpy数组 [英] store/load numpy array from binary files
问题描述
我想从二进制文件存储和加载numpy数组.为此,我创建了两个小功能.每个二进制文件都应包含给定矩阵的维数.
I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix.
def saveArrayToFile(data, fileName):
with open(fileName, 'w') as file:
a = array.array('f')
nSamples, ndim = data.shape
a.extend([nSamples, ndim]) # write number of elements and dimensions
a.fromstring(data.tostring())
a.tofile(file)
def readArrayFromFile(fileName):
_featDesc = np.fromfile(fileName, 'f')
_ndesc = int(_featDesc[0])
_ndim = int(_featDesc[1])
_featDesc = _featDesc[2:]
_featDesc = _featDesc.reshape([_ndesc, _ndim])
return _featDesc, _ndesc, _ndim
有关如何使用功能的示例是:
An example on how to use the functions is:
myarr=np.array([[7, 4],[3, 9],[1, 3]])
saveArrayToFile(myarr,'myfile.txt')
_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')
但是,将显示错误消息"ValueError:新数组的总大小必须保持不变".我的数组的大小可以为MxN和MxM.任何建议都值得欢迎.我认为问题可能出在saveArrayToFile函数中.
However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed. I think the problem might be in the saveArrayToFile function.
最良好的祝愿
哈维尔
推荐答案
使用 numpy.load )以将numpy数组转储(从二进制文件中提取).
Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.
这篇关于从二进制文件存储/加载numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!