Mnist数据集图像分类

数据集介绍

一、Keras方法

1.读取数据集

MNIST 数据集预先加载在Keras 库中,其中包括4 个Numpy 数组。

from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

2.查看数据集属性

图像被编码为Numpy 数组,而标签是数字数组,取值范围为0~9。图像和标签一一对应。

>>> train_images.shape
(60000, 28, 28)
>>> len(train_labels)
60000
>>> train_labels
array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)

>>> test_images.shape
(10000, 28, 28)
>>> len(test_labels)
10000
>>> test_labels
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)

显示图像:

digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()

3.构建网络:目的就是通过训练得出网络的最佳参数。

网络包含2 个Dense 层,它们是密集连接(也叫全连接)的神经层。第二层(也是最后一层)是一个10 路softmax 层,它将返回一个由10 个概率值(总和为1)组成的数组。每个概率值表示当前数字图像属于10 个数字类别中某一个的概率。

from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))

4.编译网络:设定评价指标、损失函数、优化器。

network.compile( optimizer='rmsprop',
				 loss='categorical_crossentropy',
				 metrics=['accuracy']
				)

5.送入网络前,对样本数据进行预处理

将其变换为网络要求的形状,并缩放到所有值都在[0, 1] 区间。

之前训练图像保存在一个uint8 类型的数组中,其形状为(60000, 28, 28),取值区间为[0, 255]。我们需要将其变换为一个float32 数组,其形状为(60000, 28 * 28),取值范围为0~1。

train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

6.送入网络前,准备标签

对标签进行分类编码。

from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

7.把样本和标签送入网络,训练模型

在Keras 中这一步是通过调用网络的fit 方法来完成的——我们在训练数据上拟合(fit)模型。

>>> network.fit(train_images, train_labels, epochs=5, batch_size=128)
Epoch 1/5
60000/60000 [=============================] - 9s - loss: 0.2524 - acc: 0.9273
Epoch 2/5
51328/60000 [=======================>.....] - ETA: 1s - loss: 0.1035 - acc: 0.9692

训练过程中显示了两个数字:一个是网络在训练数据上的损失(loss),另一个是网络在训练数据上的精度(acc)。

8.检查模型在测试集上的性能。

在Keras 中这一步是通过调用网络的evaluate方法来完成的。

>>> test_loss, test_acc = network.evaluate(test_images, test_labels)
>>> print('test_acc:', test_acc)
test_acc: 0.9785

测试集精度为97.8%,比训练集精度低不少。训练精度和测试精度之间的这种差距是过拟合(overfit)造成的。过拟合是指机器学习模型在新数据上的性能往往比在训练数据上要差。

发布了195 篇原创文章 · 获赞 59 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_36622009/article/details/105645182