初识MINST

44 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。
MINST数据集的使用相当于机器学习领域的hello world. 看代码:(里面有详细的注释)

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

minst = tf.keras.datasets.mnist   # 加载数据集
(x_train, y_train), (x_test, y_test) = minst.load_data()
print(x_train.shape, y_train.shape)  # 1输出训练集的大小形状。1对应下面输出的第一行。
print(x_test.shape, y_test.shape)     # 2输出测试集的大小形状。
# 了解一下数据集的形状大小很重要的,因为后面的神经网络的输入是固定的,如果数据集和网络的输入不一致,
# 需要提前转换格式使之相同。

image_index = 123
plt.imshow(x_train[image_index], cmap='Greys')   # 以灰度图像打印出来。
# plt.imshow(x_train[image_index])  # 这个就是原图。
plt.show()
print(x_train[image_index].shape)   # 3
x_train = np.pad(x_train, ((0, 0), (2, 2), (2, 2)), 'constant', constant_values=0)  # 这里对原来的28*28的进行扩张,成32*32的。
# 第一个参数x_train是待扩张的数组, 第二个参数的意思是,第一个维度前后均增加0,(就是那个60000不变。)第二个维度前后均增加2,
# 第三个维度前后均增加2,(这两句话的意思是每个28前面加2,后面加2达到32.) 'constant'的意思是按照后面的constant_value指定的值扩张。
# https://numpy.org/devdocs/reference/generated/numpy.pad.html?highlight=pad#numpy.pad 个人觉得还是example看的清楚。。
print(x_train.shape)  # 4
x_train = x_train.astype('float32')  # 转换数据类型
x_train = x_train/255   # 归1化处理。原来的灰度图像是0-255的,现在统一转换到0-1
x_train = x_train.reshape(x_train.shape[0], 32, 32, 1)  # 至于这三句话的处理有什么实际的意义,实际上可以为下一个博客的神经网络的输入服务。
print(x_train.shape)  # 5

这是效果图: 在这里插入图片描述

这里新增一个官方doc: numpy的