TensorFlow——MNIST手写数字数据集

1、np_mnist_read

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


def read_image_files(filename, num):
    bin_file = open(filename, 'rb')
    buf = bin_file.read()
    index = 0
    # # 读取前四个数字
    # magic, numImage, numRows, numCols = struct.unpack_from('>IIII', buf, index)
    # 索引移动到第一张图片的位置 ‘I’代表4个字节 两个数字一个字节
    # 前四个字节表示magic number,接下来四个字节代表容量,接下来从第8个字节表示行数和列数
    index += struct.calcsize('>IIII')
    # 索引移动到第num张图片的位置
    index += struct.calcsize('>784B') * num
    # 读取一张完整的图片数据
    images = struct.unpack_from('>784B', buf, index)
    plt.imshow(np.array(images).reshape(28, 28), cmap='Greys')
    plt.show()
    plt.imshow(np.array(images).reshape(28, 28), cmap='gray')
    plt.show()
    for i in range(784):
        if (i % 28 == 0 and i != 0):
            print()
        print(images[i], end="\t")
    bin_file.close()


def read_labels_files(filename, num):
    bin_file = open(filename, 'rb')
    buf = bin_file.read()
    index = 0
    # 索引移动到第一张图片的位置
    index += struct.calcsize('>II')
    # 索引移动到第num张图片的位置
    index += struct.calcsize('>1B') * num
    # 读取labels数据
    labels = struct.unpack_from('>1B', buf, index)
    print("labels:", labels)


if __name__ == '__main__':
    num = 50000
    read_image_files('./train-images.idx3-ubyte', num)
    read_labels_files('./train-labels.idx1-ubyte', num)

2、tf_mnist_read

import matplotlib.pyplot as plt
import tensorflow.examples.tutorials.mnist.input_data as input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 训练集
train_images = mnist.train.images
train_labels = mnist.train.labels

# 验证集
validation_images = mnist.validation.images
validation_labels = mnist.validation.labels

# 测试集
test_images = mnist.test.images
test_labels = mnist.test.labels

# 打印数据集中的数据个数
print('训练集个数:', mnist.train.num_examples)
print('验证集个数:', mnist.validation.num_examples)
print('测试集个数:', mnist.test.num_examples)

im = mnist.train.images[1]
print(im.shape)

# 显示图片
im = im.reshape(28, 28)
print(im.shape)
plt.imshow(im, cmap='Greys')
plt.show()
plt.imshow(im, cmap='gray')
plt.show()

 

©️2020 CSDN 皮肤主题: 我行我“速” 设计师:Amelia_0503 返回首页