从二进制文件存储/加载numpy数组 [英] store/load numpy array from binary files

查看:78
本文介绍了从二进制文件存储/加载numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从二进制文件存储和加载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.

最良好的祝愿

哈维尔

推荐答案

使用

Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.

这篇关于从二进制文件存储/加载numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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