当前位置:主页 > python教程 > numpy存取数据

numpy存取数据(tofile/fromfile)的实现

发布:2023-04-04 10:30:01 59


给大家整理一篇相关的编程文章,网友蒙向露根据主题投稿了本篇教程内容,涉及到numpy存取数据、numpy存取tofile/fromfile、numpy tofile fromfile、numpy存取数据相关内容,已被516网友关注,如果对知识点想更进一步了解可以在下方电子资料中获取。

numpy存取数据

我们知道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

到此这篇关于numpy存取数据(tofile/fromfile)的实现的文章就介绍到这了,更多相关numpy存取数据内容请搜索码农之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持码农之家!


参考资料

相关文章

网友讨论