numpy存取数据(tofile/fromfile)

numpy存取数据(tofile/fromfile)

我们知道numpy的array是可以保存到文件的,一个常用的做法是通过to_file()保存到而进行.bin文件中,然后再通过from_file()从.bin文件中将其读取出来,下面看一个例子。

data_in 是一个二维numpy数组,其shape为[3,4]

import numpy as np
data_in = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).astype(np.int64)
print(data_in)
data_in.tofile("C:/Users/Desktop/data_in.bin")
data_out = np.fromfile("C:/Users/Desktop/data_in.bin", dtype=np.int64)
print(data_out)
print(data_out.shape)
print(data_out.reshape(3,4))

接下来将其存入文件中,使用tofile方法即可,参数填入想要保存到的文件路径,然后使用fromfile可以将其从文件中读取出来。
但是可以发现,读取出来的data_out的shape变成1维了

首先,使用tofile方法,会默认将所有数据按顺序排成一个向量,然后以二进制形式存入文件中,而读取的时候自然会变成1维了,如果已知原始数组的维数,将它reshape一下就行了

有时候data_out的最前面几个值和之前看到的data_in的值也不一样啊,这是为什么呢?
这需要 line 14 的数据类型和 line 9 的数据类型一致

[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[ 1 2 3 4 5 6 7 8 9 10 11 12]
(12,)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
import numpy as np
input = np.random.randn(20, 224, 224, 3)
arr1 = np.array(input, dtype=np.float32)
print(arr1.shape)
print(arr1.dtype)
arr1.tofile("resnet50_input_batch20.bin")

https://cloud.tencent.com/developer/article/1670550

https://mlhowto.readthedocs.io/en/latest/numpy.html

posted @   michaelchengjl  阅读(5642)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示