
2.4 机器学习的“Hello World”
2.4.1 MNIST 数据集
MNIST 数据集(Mixed National Institute of Standards and Technology database,美国国家标准与技术研究所数据库)是著名的公开数据库之一,它是一个入门级的计算机视觉数据集,包含大量的手写数字图片。在机器学习领域,MNIST 数据集可以说是入门基础。
在机器学习的学习过程中,需要有大量的数据集。一个机器学习构件,除了机器算法、模型,还要有丰富且大量的训练样本。
在MNIST 官方网站上可以下载以下4 个数据文件(分别是训练样本、训练标签、测试样本、测试标签)。

下载到的图片如图2-5 所示,是由不同人手写的数字图片组成的,并且数量很多。需要注意的是,提供的图片的格式并不是通用的图片格式,是经过处理的,无法用图片浏览器打开。

图2-5 MNIST 数据集中的手写数字图片
2.4.2 MNIST 模型训练
下面快速演示一下在TensorFlow 中,MNIST 模型训练的过程,使大家对机器学习有一个大体的了解。
第一步,下载并安装TensorFlow。在安装完成后,将TensorFlow 载入程序,如下所示。

第二步,载入准备好的MNIST 数据集,将样本从整数转换为浮点数,如下所示。

程序开始自动下载mnist.npz,如下所示。

第三步,定义和搭建 tf.keras.models.Sequential 模型,用于训练选择优化器和损失函数,如下所示。

第四步,运行以下语句以训练和验证模型。

训练的过程大致如下:

我们看到,这个数字识别器的准确度已经高达98%了。至此,我们完成了一个入门级机器学习的模型训练,实现了数字图片的识别功能。在这个模型训练中,我们使用了现成的数据集和算法,只设置了几个超参,因为数据量小,所以速度很快。有了MNIST模型训练的直观概念,我们就能很好地理解Kubeflow 中的MNIST 模型训练了。