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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM