一、概述
本博文基于tensorflow的官方指南,演示一个基本分类的例子,环境为win10+spyder3.3.3+python3.6,直接上代码。
二、代码与运行结果
1、导入依赖库
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
####################以下是运行结果####################
1.12.0
2、导入Fashion MNIST 数据集
Fashion-MNIST包含了70000 张灰度图像,涵盖 10 个类别。以下图像显示了单件服饰在较低分辨率(28x28 像素)下的效果:
使用load_data即可导入数据集文件。
fashion_mnist = keras.datasets.fashion_mnist
'''
train_images 和 train_labels 数组是训练集,即模型用于学习的数据。
测试集 test_images 和 test_labels 数组用于测试模型。
'''
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
####################以下是运行结果####################
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
32768/29515 [=================================] - 0s 7us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz
26427392/26421880 [==============================] - 175s 7us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz
8192/5148 [===============================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz
4423680/4422102 [==============================] - 22s 5us/step
导入成功后,可以在PC上看到对应的文件:
3、数据预处理
我们将这些值缩小到 0 到 1 之间,然后将其馈送到神经网络模型。为此,将图像组件的数据类型从整数转换为浮点数,然后除以 255。以下是预处理图像的函数:
train_images = train_images / 255.0
test_images = test_images / 255.0
4、构建模型
(1)配置模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
(2)编译模型
模型还需要再进行几项设置才可以开始训练。这些设置会添加到模型的编译步骤:
- 损失函数 - 衡量模型在训练期间的准确率。我们希望尽可能缩小该函数,以“引导”模型朝着正确的方向优化。
- 优化器 - 根据模型看到的数据及其损失函数更新模型的方式。
- 指标 - 用于监控训练和测试步骤。以下示例使用准确率,即图像被正确分类的比例。
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
5、训练模型
训练神经网络模型需要执行以下步骤:
- 将训练数据馈送到模型中,在本示例中为
train_images
和train_labels
数组。 - 模型学习将图像与标签相关联。
- 我们要求模型对测试集进行预测,在本示例中为
test_images
数组。我们会验证预测结果是否与test_labels
数组中的标签一致。
要开始训练,请调用 model.fit
方法,使模型与训练数据“拟合”:
model.fit(train_images, train_labels, epochs=5)
####################以下是运行结果####################
Epoch 1/5
60000/60000 [==============================] - 2s 38us/step - loss: 0.5011 - acc: 0.8249
Epoch 2/5
60000/60000 [==============================] - 2s 34us/step - loss: 0.3776 - acc: 0.8634
Epoch 3/5
60000/60000 [==============================] - 2s 33us/step - loss: 0.3406 - acc: 0.8759
Epoch 4/5
60000/60000 [==============================] - 2s 31us/step - loss: 0.3160 - acc: 0.8840
Epoch 5/5
60000/60000 [==============================] - 2s 32us/step - loss: 0.3006 - acc: 0.8876
在模型训练期间,系统会显示损失和准确率指标。该模型在训练数据上的准确率达到 0.88(即 88%)。
6、评估准确率
est_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
结果表明,模型在测试数据集上的准确率略低于在训练数据集上的准确率。训练准确率和测试准确率之间的这种差异表示出现过拟合。如果机器学习模型在新数据上的表现不如在训练数据上的表现,就表示出现过拟合。
7、预测
predictions = model.predict(test_images)
print("模型预测值为:{0}".format(np.argmax(predictions[0])))
print("对应标签值为:{0}".format(test_labels[0]))
print("模型预测值为:{0}".format(np.argmax(predictions[2])))
print("对应标签值为:{0}".format(test_labels[2]))
print("模型预测值为:{0}".format(np.argmax(predictions[6])))
print("对应标签值为:{0}".format(test_labels[6]))
####################以下是运行结果####################
模型预测值为:9
对应标签值为:9
模型预测值为:1
对应标签值为:1
模型预测值为:4
对应标签值为:4
从运行结果来看,训练出来的模型能够准确预测。