mnist数据集预处理实战

欢迎点击「算法与编程之美」↑关注我们!

本文首发于微信公众号:"算法与编程之美",欢迎关注,及时了解更多此系列文章。

mnist数据集可以从https://s3.amazonaws.com/img-datasets/mnist.npz 这个网址进行下载,下载的文件是一种称为npz格式的文件,这是numpy库生成的特有的压缩包格式。

numpy可以将numpy.array格式的数组以文件的形式进行序列化存储到文件,然后以反序列化的方式读取文件并直接还原成之前的数组。

存储的文件主要有两种形式:*.npy和*.npz。

npy的基本用法

 

import numpy as np

 

a = np.array([x for x in range(3)])

 

np.save('test-a', a) #文件的扩展名默认为.npy,因此完整文件名是test-a.npy

 

aa = np.load('test-a.npy')

print(aa) # [0 1 2]


npz的基本用法

当需要将多个数组保存在一个文件的时候,则需要用到npz文件格式存储。

 

import numpy as np

a = np.array([x for x in range(3)])

b = np.array([y for y in range(3,6)])

 

np.savez('test-ab.npz', a = a, b = b)

 

data = np.load('test-ab.npz')

print(data['a']) # [0 1 2]

print(data['b']) # [3 4 5]

了解npy和npz的基本用法之后,接下来将介绍keras中mnist的数据集加载过程。

 

from tensorflow import keras

import numpy as np

 

fname = 'mnist.npz'

path = keras.utils.get_file(fname=fname,

                   origin='https://s3.amazonaws.com/img-datasets/mnist.npz')

 

with np.load(path, allow_pickle=True) as f:

   x_train, y_train = f['x_train'], f['y_train']

   x_test, y_test = f['x_test'], ['y_test']

   

   print(x_train.shape) # (60000, 28, 28)

   print(x_test.shape)  # (10000, 28, 28)

注:keras中下载的数据集默认的存放位置是:~/.keras/datasets/ 目录下。

可以看到mnist数据集的处理流程是将28x28x1的图片文件处理成四个numpy数组:x_train, y_train, x_test, y_test。然后将这四个数组写入到文件生成mnist.npz文件。

在使用数据集的时候,利用keras的get_file()先从指定的URL地址下载npz文件,然后加载得到两个tuple,下面是keras官方提供的mnist数据集load_data()方法:

 

def load_data(path='mnist.npz'):

   """Loads the MNIST dataset.

   # Arguments

       path: path where to cache the dataset locally

           (relative to ~/.keras/datasets).

   # Returns

       Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.

   """

   path = get_file(path,

                   origin='https://s3.amazonaws.com/img-datasets/mnist.npz',

                   file_hash='8a61469f7ea1b51cbae51d4f78837e45')

   with np.load(path, allow_pickle=True) as f:

       x_train, y_train = f['x_train'], f['y_train']

       x_test, y_test = f['x_test'], f['y_test']

   return (x_train, y_train), (x_test, y_test)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

算法与编程之美

欢迎关注『算法与编程之美』

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值