1·构建并训练模型
import tensorflow as tf
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
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, y_train, epochs=10,validation_data=(x_test,y_test))
2·对模型进行评估
model.evaluate(x_test, y_test, verbose=2)
history.history.keys()
plt.plot(history.epoch,history.history.get('loss'),label='loss')
plt.plot(history.epoch,history.history.get('val_loss'),label='val_loss')
plt.legend()
plt.show()
plt.plot(history.epoch,history.history.get('accuracy'),label='accuracy')
plt.plot(history.epoch,history.history.get('val_accuracy'),label='val_accuracy')
plt.legend()
plt.show()
3·保存并调用模型进行手写数字图片的识别
model.save('tf_model.h5')
new_model = tf.keras.models.load_model('tf_model.h5')
im = Image.open(r"D:\个人文件\Desktop\6.png")
im = im.resize((28,28))
im = np.array(im)
p3 = im.min(axis = -1)
plt.imshow(p3,cmap = 'gray')
for i in range(28):
for j in range(28):
p3[i][j] = 255-p3[i][j]
ret = new_model.predict((p3/255).reshape((1,28,28)))
number = np.argmax(ret)