博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python手动读取MNIST数据集
阅读量:2136 次
发布时间:2019-04-30

本文共 7511 字,大约阅读时间需要 25 分钟。

注意,这里读取的文件都是gz文件解压后的,不是gz文件

 

法①

import numpy as npimport structimport osimport matplotlib.pyplot as pltdef load_mnist_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)    with open(labels_path, 'rb') as lbpath:        magic, n = struct.unpack('>II',lbpath.read(8))        labels = np.fromfile(lbpath,dtype=np.uint8)    with 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, labelsdef load_mnist_test(path, kind='t10k'):    labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind)    images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind)    with open(labels_path, 'rb') as lbpath:        magic, n = struct.unpack('>II',lbpath.read(8))        labels = np.fromfile(lbpath,dtype=np.uint8)    with 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, labelspath='D:/py/dataset/MNIST/raw'train_images,train_labels=load_mnist_train(path)test_images,test_labels=load_mnist_test(path)fig=plt.figure(figsize=(8,8))fig.subplots_adjust(left=0,right=1,bottom=0,top=1,hspace=0.05,wspace=0.05)for i in range(30):    images = np.reshape(train_images[i], [28,28])    ax=fig.add_subplot(6,5,i+1,xticks=[],yticks=[])    ax.imshow(images,cmap=plt.cm.binary,interpolation='nearest')    ax.text(0,7,str(train_labels[i]))plt.show()

 

法②

使用python的open()和struct.unpack_from()函数操作

import numpy as npimport structimport matplotlib.pyplot as plt# 训练集文件train_images_idx3_ubyte_file = 'dataset/MNIST/raw/train-images-idx3-ubyte'# 训练集标签文件train_labels_idx1_ubyte_file = 'dataset/MNIST/raw/train-labels-idx1-ubyte'# 测试集文件test_images_idx3_ubyte_file = 'dataset/MNIST/raw/t10k-images-idx3-ubyte'# 测试集标签文件test_labels_idx1_ubyte_file = 'dataset/MNIST/raw/t10k-labels-idx1-ubyte'def decode_idx3_ubyte(idx3_ubyte_file):    """    解析idx3文件的通用函数    :param idx3_ubyte_file: idx3文件路径    :return: 数据集    """    # 读取二进制数据    bin_data = open(idx3_ubyte_file, 'rb').read()    # 解析文件头信息,依次为魔数、图片数量、每张图片高、每张图片宽    offset = 0    fmt_header = '>iiii' #因为数据结构中前4行的数据类型都是32位整型,所以采用i格式,但我们需要读取前4行数据,所以需要4个i。我们后面会看到标签集中,只使用2个ii。    magic_number, num_images, num_rows, num_cols = struct.unpack_from(fmt_header, bin_data, offset)    print('魔数:%d, 图片数量: %d张, 图片大小: %d*%d' % (magic_number, num_images, num_rows, num_cols))    # 解析数据集    image_size = num_rows * num_cols    offset += struct.calcsize(fmt_header)  #获得数据在缓存中的指针位置,从前面介绍的数据结构可以看出,读取了前4行之后,指针位置(即偏移位置offset)指向0016。    print(offset)    fmt_image = '>' + str(image_size) + 'B'  #图像数据像素值的类型为unsigned char型,对应的format格式为B。这里还有加上图像大小784,是为了读取784个B格式数据,如果没有则只会读取一个值(即一副图像中的一个像素值)    print(fmt_image,offset,struct.calcsize(fmt_image))    # print((num_images, num_rows, num_cols))    images = np.empty((num_images, num_rows, num_cols))    #plt.figure()    for i in range(num_images):        if (i + 1) % 10000 == 0:            print('已解析 %d' % (i + 1) + '张')            print(offset)        images[i] = np.array(struct.unpack_from(fmt_image, bin_data, offset)).reshape((num_rows, num_cols))        #print(images[i])        offset += struct.calcsize(fmt_image)#        plt.imshow(images[i],'gray')#        plt.pause(0.00001)#        plt.show()    #plt.show()    return imagesdef decode_idx1_ubyte(idx1_ubyte_file):    """    解析idx1文件的通用函数    :param idx1_ubyte_file: idx1文件路径    :return: 数据集    """    # 读取二进制数据    bin_data = open(idx1_ubyte_file, 'rb').read()    # 解析文件头信息,依次为魔数和标签数    offset = 0    fmt_header = '>ii'    magic_number, num_images = struct.unpack_from(fmt_header, bin_data, offset)    print('魔数:%d, 图片数量: %d张' % (magic_number, num_images))    # 解析数据集    offset += struct.calcsize(fmt_header)    fmt_image = '>B'    labels = np.empty(num_images)    for i in range(num_images):        if (i + 1) % 10000 == 0:            print ('已解析 %d' % (i + 1) + '张')        labels[i] = struct.unpack_from(fmt_image, bin_data, offset)[0]        offset += struct.calcsize(fmt_image)    return labelsdef load_train_images(idx_ubyte_file=train_images_idx3_ubyte_file):    """    TRAINING SET IMAGE FILE (train-images-idx3-ubyte):    [offset] [type]          [value]          [description]    0000     32 bit integer  0x00000803(2051) magic number    0004     32 bit integer  60000            number of images    0008     32 bit integer  28               number of rows    0012     32 bit integer  28               number of columns    0016     unsigned byte   ??               pixel    0017     unsigned byte   ??               pixel    ........    xxxx     unsigned byte   ??               pixel    Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black).    :param idx_ubyte_file: idx文件路径    :return: n*row*col维np.array对象,n为图片数量    """    return decode_idx3_ubyte(idx_ubyte_file)def load_train_labels(idx_ubyte_file=train_labels_idx1_ubyte_file):    """    TRAINING SET LABEL FILE (train-labels-idx1-ubyte):    [offset] [type]          [value]          [description]    0000     32 bit integer  0x00000801(2049) magic number (MSB first)    0004     32 bit integer  60000            number of items    0008     unsigned byte   ??               label    0009     unsigned byte   ??               label    ........    xxxx     unsigned byte   ??               label    The labels values are 0 to 9.    :param idx_ubyte_file: idx文件路径    :return: n*1维np.array对象,n为图片数量    """    return decode_idx1_ubyte(idx_ubyte_file)def load_test_images(idx_ubyte_file=test_images_idx3_ubyte_file):    """    TEST SET IMAGE FILE (t10k-images-idx3-ubyte):    [offset] [type]          [value]          [description]    0000     32 bit integer  0x00000803(2051) magic number    0004     32 bit integer  10000            number of images    0008     32 bit integer  28               number of rows    0012     32 bit integer  28               number of columns    0016     unsigned byte   ??               pixel    0017     unsigned byte   ??               pixel    ........    xxxx     unsigned byte   ??               pixel    Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black).    :param idx_ubyte_file: idx文件路径    :return: n*row*col维np.array对象,n为图片数量    """    return decode_idx3_ubyte(idx_ubyte_file)def load_test_labels(idx_ubyte_file=test_labels_idx1_ubyte_file):    """    TEST SET LABEL FILE (t10k-labels-idx1-ubyte):    [offset] [type]          [value]          [description]    0000     32 bit integer  0x00000801(2049) magic number (MSB first)    0004     32 bit integer  10000            number of items    0008     unsigned byte   ??               label    0009     unsigned byte   ??               label    ........    xxxx     unsigned byte   ??               label    The labels values are 0 to 9.    :param idx_ubyte_file: idx文件路径    :return: n*1维np.array对象,n为图片数量    """    return decode_idx1_ubyte(idx_ubyte_file)if __name__ == '__main__':    train_images = load_train_images()    train_labels = load_train_labels()    # test_images = load_test_images()    # test_labels = load_test_labels()    # 查看前十个数据及其标签以读取是否正确    for i in range(10):        print(train_labels[i])        plt.imshow(train_images[i], cmap='gray')        plt.pause(0.000001)        plt.show()    print('done')

 

转载地址:http://qqygf.baihongyu.com/

你可能感兴趣的文章
【Loadrunner】性能测试报告实战
查看>>
【自动化测试】自动化测试需要了解的的一些事情。
查看>>
【selenium】selenium ide的安装过程
查看>>
【手机自动化测试】monkey测试
查看>>
【英语】软件开发常用英语词汇
查看>>
Fiddler 抓包工具总结
查看>>
【雅思】雅思需要购买和准备的学习资料
查看>>
【雅思】雅思写作作业(1)
查看>>
【雅思】【大作文】【审题作业】关于同不同意的审题作业(重点)
查看>>
【Loadrunner】通过loadrunner录制时候有事件但是白页无法出来登录页怎么办?
查看>>
【English】【托业】【四六级】写译高频词汇
查看>>
【托业】【新东方全真模拟】01~02-----P5~6
查看>>
【托业】【新东方全真模拟】03~04-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST05~06-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST09~10-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST07~08-----P5~6
查看>>
solver及其配置
查看>>
JAVA多线程之volatile 与 synchronized 的比较
查看>>
Java集合框架知识梳理
查看>>
笔试题(一)—— java基础
查看>>