当前位置 博文首页 > python读取mnist数据集方法案例详解

    python读取mnist数据集方法案例详解

    作者:Luna2137 时间:2021-09-12 18:05

    mnist手写数字数据集在机器学习中非常常见,这里记录一下用python从本地读取mnist数据集的方法。

    数据集格式介绍

    这部分内容网络上很常见,这里还是简明介绍一下。网络上下载的mnist数据集包含4个文件:

    在这里插入图片描述

    前两个分别是测试集的image和label,包含10000个样本。后两个是训练集的,包含60000个样本。.gz表示这个一个压缩包,如果进行解压的话,会得到.ubyte格式的二进制文件。

    在这里插入图片描述

    上图是训练集的label和image数据的存储格式。两个文件最开始都有magic number和number of images/items两个数据,有用的是第二个,表示文件中存储的样本个数。另外要注意的是数据的位数,有32位整型和8位整型两种。

    读取方法

    .gz格式的文件读取

    需要import gzip
    读取训练集的代码如下:

    def load_mnist_train(path, kind='train'): 
    '‘'
    path:数据集的路径
    kind:值为train,代表读取训练集
    ‘'‘   
        labels_path = os.path.join(path,'%s-labels-idx1-ubyte.gz'% kind)
        images_path = os.path.join(path,'%s-images-idx3-ubyte.gz'% kind)
        #使用gzip打开文件
        with gzip.open(labels_path, 'rb') as lbpath:
    	    #使用struct.unpack方法读取前两个数据,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次从文件中读取8个字节
    	    #这样读到的前两个数据分别是magic number和样本个数
            magic, n = struct.unpack('>II',lbpath.read(8))
            #使用np.fromstring读取剩下的数据,lbpath.read()表示读取所有的数据
            labels = np.fromstring(lbpath.read(),dtype=np.uint8)
        with gzip.open(images_path, 'rb') as imgpath:
            magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
            images = np.fromstring(imgpath.read(),dtype=np.uint8).reshape(len(labels), 784)
        return images, labels
    

    读取测试集的代码类似。

    非压缩文件的读取

    如果在本地对四个文件解压缩之后,得到的就是.ubyte格式的文件,这时读取的代码有所变化。

    def load_mnist_train(path, kind='train'): 
    '‘'
    path:数据集的路径
    kind:值为train,代表读取训练集
    ‘'‘   
        labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind)
        images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind)
        #不再用gzip打开文件
        with open(labels_path, 'rb') as lbpath:
    	    #使用struct.unpack方法读取前两个数据,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次从文件中读取8个字节
    	    #这样读到的前两个数据分别是magic number和样本个数
            magic, n = struct.unpack('>II',lbpath.read(8))
            #使用np.fromfile读取剩下的数据
            labels = np.fromfile(lbpath,dtype=np.uint8)
        with gzip.open(images_path, 'rb') as imgpath:
            magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
            images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
        return images, labels
    

    读取之后可以查看images和labels的长度,确认读取是否正确。

    jsjbwy