npz文件是numpy格式的压缩文件
(1)创建和读取npz文件
使用np.savez()函数可以将多个数组保存到同一个文件中。
np.savez()函数的第一个参数是文件名,其后的参数都是需要保存的数组。传递数组时可以使用关键字参数为数组命名,非关键字参数传递的数组会自动起名为arr_0、arr_1……;np.savez()函数输出的是一个扩展名为.npz的压缩文件,它包含多个与保存的数组对应的npy文件,文件名对应数组名;读取.npz文件时使用np.load()函数,返回的是一个类似于字典的对象,因此可以通过数组名作为关键字对多个数组进行访问
import numpy as np
a = np.arange(5)
b = np.arange(6)
c = np.arange(7)
np.savez('test', a, b, arr_test = c) # 将多个数组保存到磁盘
# 读取数组
data = np.load('test.npz') #类似于字典{‘arr_0’:a,’arr_1’:b,’arr_2’:c}
print('arr_0 : ', data['arr_0'])
print('arr_1 : ', data['arr_1'])
print('arr_test: ', data['arr_test'])
--------------------------------------------------------------------------------
arr_0 : [0 1 2 3 4]
arr_1 : [0 1 2 3 4 5]
arr_test : [0 1 2 3 4 5 6]
(2)实例
有时候从网上下载的数据集扩展名是npz,我们需要对数据集进行加载(读取):
例如:识别猫狗图片的二分类,下的数据集分别为cat.npz和dog.npz
import numpy as np
cat_data = np.load('cat.npz')
dog_data = np.load('dog.npz')
因为以npz结尾的数据集是压缩文件,里面还有其他的文件。使用:cat_data.files 命令进行查看
![](https://img.haomeiwen.com/i14155197/d2a095aabaea1ed2.png)
可以看出,cat.npz数据集中有:x_test,y_train,y_test,x_train 这四个数据集
接下来,进去数据集的读取:
![](https://img.haomeiwen.com/i14155197/38b694d2ac7f421a.png)
查看x_train数据集:
![](https://img.haomeiwen.com/i14155197/31b616a34dca470d.png)
这样cat.npz数据就完成的读取,dog.npz的读取同上。
网友评论