分享

深度学习实战 mnist数据集预处理技术分析

 算法与编程之美 2020-08-08

mnist数据集可以从https://s3./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./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./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)

END

主  编   |   张祯悦

责  编   |   chen   

 where2go 团队


微信号:算法与编程之美          

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多