读取 MNIST

STEP1. 下载MNIST训练数据集

方法一:使用tensorflow下载

from tensorflow.examples.tutorials.mnist import input_data
# 下载mnist数据集
mnist = input_data.read_data_sets('/mydata/', one_hot=True)

当前文件位置就会出现mydata文件夹,里面有4个压缩文件

方法二:手动下载        下载地址:http://yann.lecun.com/exdb/mnist/ 

将得到的压缩文件解压,

         

STEP2. 读取图片

用法一:

 MNIST 网站上对数据集的介绍:

以Training set image为例,读取时需要跳过 4个integer 类型        而 Training set label 需要跳过2个integer 类型

读取 Training set 的 image 和 label 文件 

def readfile():
    with open('data/MNIST_data/train-images.idx3-ubyte','rb') as f:
        train_image = f.read()
    with open('data/MNIST_data/train-labels.idx1-ubyte', 'rb') as f:
        train_labels = f.read()
    return train_image,train_labels

读取第一张图并显示

image,label=readfile()
index = struct.calcsize('>IIII')    # I代表一个无符号整数 ,跳过四个
temp = struct.unpack_from('>784B', image, index) #MNIST中的图片都是28*28的,所以读取784bit
img=np.reshape(temp, (28, 28))     
plt.imshow(img,cmap='gray')
plt.show()

写了个读取前 n 张图片和标签的

import tensorflow as tf
import struct
import matplotlib.pyplot as plt
import numpy as np

def readfile():
    with open('data/MNIST_data/train-images.idx3-ubyte','rb') as f:
        train_image = f.read()
    with open('data/MNIST_data/train-labels.idx1-ubyte', 'rb') as f:
        train_labels = f.read()
    return train_image,train_labels
'''
读取前n张图片
'''
def get_images(buf,n):
    im=[]
    index = struct.calcsize('>IIII')
    for i in range(n):
        temp = struct.unpack_from('>784B', buf, index)
        im.append(np.reshape(temp, (28, 28)))
        index += struct.calcsize('>784B')
    return im
'''
读取前n个标签
'''
def get_labels(buf,n):
    l=[]
    index = struct.calcsize('>II')
    for i in range(n):
        temp = struct.unpack_from('>1B', buf, index)
        l.append(temp[0])
        index += struct.calcsize('>1B')
    return l

'''
读取
'''
image,label=readfile()
n=16
train_img=get_images(image,n)
train_label=get_labels(label,n)

'''
显示
'''
for i in range(16):
    plt.subplot(4,4,1+i)
    title = u"label:" + str(train_label[i])
    plt.title(title)
    plt.imshow(train_img[i],cmap='gray')
plt.show()

用法二:

原始的 MNIST 数据集有6000张训练图片,1000张验证图片,而 Tensorflow 又将训练图片划分成 5500 张训练图片和 500 张验证图片

from tensorflow.examples.tutorials.mnist import input_data
# 下载mnist数据集
mnist = input_data.read_data_sets('/mydata/', one_hot=True)
'''
查看一下各个变量的大小
'''
print(mnist.train.images.shape)       #(55000, 784)   训练图像 55000个样本
print(mnist.train.labels.shape)       #(55000, 10)    训练标签
print(mnist.validation.images.shape)  #(5000, 784)    验证图像 55000个样本
print(mnist.validation.labels.shape)  #(5000, 10)     验证标签
print(mnist.test.images.shape)        #(10000, 784)   测试图像 55000个样本
print(mnist.test.labels.shape)        #(10000, 10)    测试标签

读取一张 mnist.train.images 里的图片

temp = mnist.train.images[0]
img=np.reshape(temp, (28, 28))
plt.imshow(img,cmap='gray')
plt.show()

猜你喜欢

转载自blog.csdn.net/afeiererer/article/details/81152265