zoukankan      html  css  js  c++  java
  • 鱼书学习笔记:MNIST数据集与pickle

    MNIST是机器学习领域最有名的数据集之一,被应用于从简单的实验到发表的论文研究等各种场合。实际上,在阅读图像识别或机器学习的论文时,MNIST数据集经常作为实验用的数据出现

    MNIST数据集是由0到9的数字图像构成的。训练图像有6万张,测试图有1万张,图像数据是28像素×28像素的灰度图像(1通道),各个像素的取值在0到255之间。每个图像数据都相应地标有“7”“2”“1”等标签。鱼书提供了MNIST数据集的下载脚本,我再做了一些细微的调整如下:

     mnist.py

    # coding: utf-8
    try:
        import urllib.request
    except ImportErros:
        raise ImportError('You should use Python 3.x')
    import os.path
    import gzip
    import pickle
    import os
    import numpy as np
    
    key_file = {
            'train_img':'train-images-idx3-ubyte.gz',
            'train_label':'train-labels-idx1-ubyte.gz',
            'test_img':'t10k-images-idx3-ubyte.gz',
            'test_label':'t10k-labels-idx1-ubyte.gz'
    }
    
    dataset_dir = os.path.dirname(os.path.abspath(__file__))
    save_file = dataset_dir + "/mnist.pkl"
    
    train_num = 60000
    test_num = 10000
    img_dim = (1, 28, 28)
    img_size = 784
    
    def init_mnist():
        #download_mnist()
        dataset = _convert_numpy()
        print("Creating pickle file ...")
        with open(save_file, 'wb') as f:
            pickle.dump(dataset, f, -1)
        print("Done!")
    
    def load_mnist(normalize=True, flatten=True, one_hot_label=False):
        """
        Load MNIST dataset
        :param normalize: normalize the pixel value of the image to 0.0~1.0
        :param one_hot_label: [0,0,1,0,0,0,0,0,0,0]
        :param flatten: expand the image into a one-dimensional array
        :returns: (training image, training label), (test image, test label) 
        """
        if not os.path.exists(save_file):
            init_mnist()
        
        with open(save_file, 'rb') as f:
            dataset = pickle.load(f)
    
        if normalize:
            for key in ('train_img', 'test_img'):
                dataset[key] = dataset[key].astype(np.float32)
                dataset[key] /= 255.0
    
        if one_hot_label:
            dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
            dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
    
        if not flatten:
            for key in ('train_img', 'test_img'):
                dataset[key] = dataset[key].reshape(-1, 1, 28, 28)
    
        return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])
    
    def _change_one_hot_label(X):
        T = np.zeros((X.size, 10))
        for idx, row in enumerate(T):
            row[X[idx]] = 1
    
        return T
    
    def _convert_numpy():
        dataset = {}
        dataset['train_img'] = _load_img(key_file['train_img'])
        dataset['train_label'] = _load_label(key_file['train_label'])
        dataset['test_img'] = _load_img(key_file['test_img'])
        dataset['test_label'] = _load_label(key_file['test_label'])
    
        return dataset
    
    def _load_img(file_name):
        file_path = dataset_dir + "/" + file_name
    
        print("Converting " + file_name + " to NumPy Array ...")
        with gzip.open(file_path, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=16)
        data = data.reshape(-1, img_size)
        print("Done")
    
        return data
    
    def _load_label(file_name):
        file_path = dataset_dir + "/" + file_name
    
        print("Converting " + file_name + " to NumPy Array ...")
        with gzip.open(file_path, 'rb') as f:
            labels = np.frombuffer(f.read(), np.uint8, offset=8)
        print("Done")
    
        return labels
    
    if __name__ == '__main__':
        init_mnist()

     注:原代码中的download_mnist()运行报503错误,原因似乎是目前mnist的官方数据集网址http://yann.lecun.com/exdb/mnist/正在维护,因此我直接从https://discuss.pytorch.org/t/mnist-server-down/114433/13里手动下载了四个数据集文件到路径下

    Python有pickle这个便利的功能。这个功能可以将程序运行中的对象保存为文件。如果加载保存过的pickle文件,可以立刻复原之前程序运行中的对象。用于读入MNIST数据集的load_mnist()函数内部也使用了pickle功能(在第2次及以后读入时)。利用pickle功能可以高效地完成MNIST数据地准备工作(鱼书原文)

    我检索pickle文档和部分资料了解到,pickle是Python对object对象进行序列化和反序列化的工具,与json相似,pickle也可以完成两个不同进程之间的数据同行,也可以序列化后通过web传输后再在远程端反序列化后使用,是一种多程序间通信的一种有效手段。

    通过运行下面的代码可以一窥pickle在上述mnist.py的作用

    读取mnist数据集:

    import sys, os
    sys.path.append(os.pardir)
    from dataset.mnist import load_mnist
    
    (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
    
    print(x_train.shape)
    print(t_train.shape)
    print(x_test.shape)
    print(t_test.shape)

    PIL模块确认数据:

    import sys, os
    sys.path.append(os.pardir)
    import numpy as np
    from dataset.mnist import load_mnist
    from PIL import Image
    
    def img_show(img):
        pil_img = Image.fromarray(np.uint8(img))
        pil_img.show()
    
    (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
    img = x_train[0]
    label = t_train[0]
    print(label)
    
    print(img.shape)
    img = img.reshape(28, 28)
    print(img.shape)
    
    img_show(img)

    这里需要注意的是,flatten=True时读入的图像是以一列(一维)NumPy数组的形式保存的。因此,显示图像时,需要把它变为原来的28像素×28像素的形状。可以通过reshape()方法的参数指定期望的形状,更改NumPy数组的形状。此外,还需要把保存为NumPy数组的图像数据转换为PIL用的数据对象,这个转换处理由Image.fromarray()来完成

  • 相关阅读:
    woocommerce调用产品相册gallery图片如何操作?wordpress技巧
    phpcms切换到php7.2后无法修改文章提示Uncaught Error: [] operator not supported for strings
    yandexbot ip列表整理做俄罗斯市场的站长可以关注一下
    phpcms网站迁移无法更新内容提示Table 'led_com.lz_' doesn't exist的解决方法
    phpcms邮箱smtp配置163企业邮测试可用
    phpcms添加https后台分页错误的解决方法
    linux防止恶意采集攻防战
    ThinkPHP获取当前页URL添加canonical
    如何让ThinkPHP支持模糊搜索
    火车头内容发布规则为保存本地文件时的注意事项
  • 原文地址:https://www.cnblogs.com/J14nWe1/p/14565766.html
Copyright © 2011-2022 走看看