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

作者:michaelchengjl 时间:2021-12-12 02:06:24 

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

来源:https://www.cnblogs.com/michaelcjl/p/15959131.html

标签:numpy,存取数据
0
投稿

猜你喜欢

  • Android界面与交互设计原则

    2012-02-04 09:28:32
  • Python爬虫之BeautifulSoup的基本使用教程

    2022-03-27 18:35:31
  • Yii2基于Ajax自动获取表单数据的方法

    2023-11-21 00:59:56
  • PHP设计模式 注册表模式(多个类的注册)

    2023-11-20 06:45:13
  • Python+Pika+RabbitMQ环境部署及实现工作队列的实例教程

    2021-08-19 13:13:13
  • python通过加号运算符操作列表的方法

    2023-11-12 13:44:04
  • Python爬虫PyQuery库基本用法入门教程

    2022-06-26 05:13:02
  • go smtp实现邮件发送示例详解

    2023-06-23 22:05:14
  • PyCharm Anaconda配置PyQt5开发环境及创建项目的教程详解

    2022-03-12 07:15:47
  • asp.net DropDownList实现二级联动效果

    2023-07-23 07:48:41
  • ASP实现控制虚拟主机功能的函数ADSI

    2008-10-12 13:12:00
  • Django单元测试工具test client使用详解

    2021-04-11 22:25:58
  • 使用Python的Django和layim实现即时通讯的方法

    2022-05-29 00:41:33
  • windows下python和pip安装教程

    2022-04-07 13:00:44
  • 为你的网页添加背景音乐

    2007-02-03 11:39:00
  • Python运算符教程之逻辑门详解

    2021-05-17 04:32:54
  • PHP实现异步定时多任务消息推送

    2023-05-25 09:51:29
  • Python logging简介详解

    2022-05-12 09:27:02
  • 浅谈Pandas 排序之后索引的问题

    2022-03-18 12:28:32
  • Python数字图像处理代数之加减乘运算

    2023-03-20 07:51:26
  • asp之家 网络编程 m.aspxhome.com