In [1]:
import warnings
warnings.simplefilter(action='ignore')
In [2]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

1. 数据预处理

In [3]:
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
In [4]:
x_train_flatten = x_train.reshape(x_train.shape[0], 784).astype('float32')
x_test_flatten = x_test.reshape(x_test.shape[0], 784).astype('float32')
In [5]:
x_train_normalize = x_train_flatten / 255.0
x_test_normalize = x_test_flatten / 255.0
In [6]:
y_train_one_hot = tf.keras.utils.to_categorical(y_train)
y_test_one_hot = tf.keras.utils.to_categorical(y_test)

2. 建立模型

2.1 建立 Sequential 模型

In [7]:
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=1000, input_dim=784, kernel_initializer='normal', activation='relu'),  # 输入层-隐藏层(这里隐藏层为1000个神经元)
    tf.keras.layers.Dense(units=10, kernel_initializer='normal', activation='softmax')  # 输出层
])

2.2 查看模型的摘要

In [8]:
print(model.summary())
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 1000)              785000    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                10010     
=================================================================
Total params: 795,010
Trainable params: 795,010
Non-trainable params: 0
_________________________________________________________________
None

3. 训练模型

In [9]:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
In [10]:
train_history = model.fit(x=x_train_normalize, y=y_train_one_hot, validation_split=0.2,
                         epochs=10, batch_size=200, verbose=2)
Train on 48000 samples, validate on 12000 samples
Epoch 1/10
 - 7s - loss: 11.6040 - acc: 0.2754 - val_loss: 9.3206 - val_acc: 0.4169
Epoch 2/10
 - 6s - loss: 8.5123 - acc: 0.4669 - val_loss: 7.5692 - val_acc: 0.5271
Epoch 3/10
 - 7s - loss: 7.6291 - acc: 0.5234 - val_loss: 7.3625 - val_acc: 0.5409
Epoch 4/10
 - 6s - loss: 7.4583 - acc: 0.5345 - val_loss: 7.3288 - val_acc: 0.5420
Epoch 5/10
 - 7s - loss: 7.3170 - acc: 0.5430 - val_loss: 6.6177 - val_acc: 0.5848
Epoch 6/10
 - 6s - loss: 6.1799 - acc: 0.6134 - val_loss: 5.8796 - val_acc: 0.6327
Epoch 7/10
 - 6s - loss: 5.9269 - acc: 0.6296 - val_loss: 5.7337 - val_acc: 0.6414
Epoch 8/10
 - 6s - loss: 5.8553 - acc: 0.6340 - val_loss: 5.7188 - val_acc: 0.6424
Epoch 9/10
 - 7s - loss: 5.7866 - acc: 0.6385 - val_loss: 5.7039 - val_acc: 0.6433
Epoch 10/10
 - 5s - loss: 5.7334 - acc: 0.6419 - val_loss: 5.5996 - val_acc: 0.6503

4. 以图形显示训练过程

In [11]:
def show_train_history(train_history, train, validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train History')
    plt.xlabel('Epoch')
    plt.ylabel(train)
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()
In [12]:
show_train_history(train_history, 'acc', 'val_acc')
In [13]:
show_train_history(train_history, 'loss', 'val_loss')

5. 评估模型的准确率

In [14]:
scores = model.evaluate(x_test_normalize, y_test_one_hot)
print()
print('accuracy:', scores[1])
10000/10000 [==============================] - 1s 104us/step

accuracy: 0.6376

6. 进行预测

6.1 执行预测

In [15]:
predictions = model.predict_classes(x_test_normalize)

6.2 预测结果

In [16]:
predictions
Out[16]:
array([7, 6, 7, ..., 4, 5, 6])

6.3 定义函数以显示10项预测结果

In [17]:
def plot_images_labels_prediction(images, labels, predictions, idx, num=10):
    """
    images: 数字图像数组
    labels: 真实值数组
    predictions: 预测结果数据
    idx: 开始显示的数据index
    num: 要显示的数据项数, 默认为10, 不超过25
    """
    fig = plt.gcf()
    fig.set_size_inches(12, 14)
    if num > 25:
        num = 25
    for i in range(0, num):
        ax = plt.subplot(5, 5, i+1)
        ax.imshow(images[idx], cmap='binary')
        title = 'lable=' + str(labels[idx])
        if len(predictions) > 0:
            title += ',predict=' + str(predictions[idx])
        ax.set_title(title, fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
        idx += 1
    plt.show()
In [18]:
plot_images_labels_prediction(x_test, y_test, predictions, idx=0, num=10)

7. 显示混淆矩阵

7.1 建立混淆矩阵

In [19]:
pd.crosstab(y_test, predictions, rownames=['label'], colnames=['predict'])
Out[19]:
predict 0 2 3 4 5 6 7 8 9
label
0 0 0 73 3 632 204 12 50 6
1 25 0 218 15 26 20 157 593 81
2 0 0 513 60 16 123 71 230 19
3 0 0 939 2 26 2 11 22 8
4 0 0 0 937 0 12 1 4 28
5 0 0 31 6 818 11 5 12 9
6 0 0 5 11 22 910 3 6 1
7 0 1 15 12 2 1 960 9 28
8 0 0 27 11 21 10 7 888 10
9 0 0 15 37 13 3 11 6 924

7.2 建立真实值与预测 DataFrame

In [20]:
df = pd.DataFrame({'label': y_test, 'predict': predictions})
df[:2]
Out[20]:
label predict
0 7 7
1 2 6

7.3 查询真实值是 "5" 但预测值是 "2" 的数据

In [21]:
df[(df.label==5)&(df.predict==2)]
Out[21]:
label predict
In [22]:
plot_images_labels_prediction(x_test, y_test, predictions, idx=340, num=1)
In [23]:
plot_images_labels_prediction(x_test, y_test, predictions, idx=1289, num=1)