从二进制文件存储/加载numpy数组
我想把numpy数组存储到二进制文件中,并且从这些文件中加载它们。为此,我写了两个小函数。每个二进制文件应该包含给定矩阵的维度信息。
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
下面是如何使用这些函数的一个例子:
myarr=np.array([[7, 4],[3, 9],[1, 3]])
saveArrayToFile(myarr,'myfile.txt')
_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')
但是,我遇到了一个错误信息:'ValueError: total size of new array must be unchanged'。我的数组可能是MxN或MxM的大小。欢迎任何建议。
我觉得问题可能出在saveArrayToFile这个函数里。
祝好,
哈维尔