import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #可解决Matplotlib中文乱码问题
plt.rcParams['axes.unicode_minus'] = False #可解决坐标轴负号'-'显示为方块的问题
# 模型建立
mnist = tf.keras.datasets.mnist
# 导入MNIST手写阿拉伯数字数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 训练/测试数据的X/y维度
print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
# 数据维度为:
# 训练:(60000, 28, 28) (60000,)
# 测试:(10000, 28, 28) (10000,)
# 进行特征值变为 0, 1
x_train[x_train > 0] = 1
x_test[x_test > 0] = 1
x_train_norm, x_test_norm = x_train, x_test
# # 把标签转成独热编码
# y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
# y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
# 建立模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# 设定优化器,损失函数,效果衡量指标的类别
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 模型训练
history = model.fit(x_train_norm, y_train, epochs=7, validation_split=0.2)
# 对模型训练过程的准确率绘图
plt.figure(figsize=(8, 6))
plt.plot(history.history['accuracy'], 'r', label='训练准确率')
plt.plot(history.history['val_accuracy'], 'g', label='验证准确率')
plt.legend()
plt.show()
# 对训练过程的损失绘图
plt.figure(figsize=(8, 6))
plt.plot(history.history['loss'], 'r', label="训练损失")
plt.plot(history.history['val_loss'], 'g', label="验证损失")
plt.legend()
plt.show()
# 模型存档
model.save('model.h5')
# 模型人工测试
# 模型载入
model = tf.keras.models.load_model('model.h5')
from skimage import io
from skimage.transform import resize
# 读取影相并转换为灰度图
uploaded_file = 'www.png'
imagel = io.imread(uploaded_file, as_gray=True) / 255
# 缩为(28, 28)大小的影相
image_resized = resize(imagel, (28, 28), anti_aliasing=True)
# 进行特征值变为 0, 1
image_resized[image_resized>8.1e-01] = 1
image_resized[image_resized != 1] = 0
X1 = image_resized.reshape(1, 28, 28)
# 反转颜色
X1 = np.abs(1-X1)
# 预测
predictions = model.predict(X1)
max_index = np.argmax(predictions)
y_predict = int(max_index)
print(predictions)
print(y_predict)