tensorflow预测单张mnist数据集图片 — 数字识别(Predict single image for MNIST dataset by tensorflow - digital recognition)

MNIST数据集可以说是深度学习的入门,但是使用模型预测单张MNIST图片得到数字识别结果的文章不多,所以本人查找资料,把代码写下,希望可以帮到大家~

 1 # Buding your first image classification model with MNIST dataset
 2 import tensorflow as tf
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 from tensorflow.keras.models import Sequential, load_model
 6 from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
 7 
 8 # download the data
 9 mnist = tf.keras.datasets.mnist
10 (x_train, y_train), (x_test, y_test) = mnist.load_data()
11 
12 # reshape and normalize the data
13 # reshaping the array to 4-dim so that it can work with the Keras API
14 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
15 x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
16 input_shape = (28, 28, 1)
17 
18 # making sure that the values are float so that we can get decimal point after division
19 # astype()用于改变所有数据元素的数据类型
20 x_train = x_train.astype('float32')
21 x_test = x_test.astype('float32')
22 
23 # normalizing the RGB codes by dividing it to the max RGB value
24 x_train /= 255
25 x_test /= 255
26 
27 # create the model
28 model = Sequential()
29 model.add(Conv2D(28, kernel_size=(3, 3), input_shape=input_shape))
30 model.add(MaxPooling2D(pool_size=(2, 2)))
31 model.add(Flatten())
32 model.add(Dense(200, activation=tf.nn.relu))
33 model.add(Dropout(0.3))
34 model.add(Dense(10, activation=tf.nn.softmax))
35 # compile and fit our model
36 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
37 model.fit(x=x_train, y=y_train, epochs=10)
38 model.save('model_mnist_model.h5')
39 
40 # load model
41 model = load_model('model_mnist_model.h5', compile=True)
42 model.evaluate(x_test, y_test)
43 
44 # 查看前16张图片预测结果
45 images = x_test[:16]
46 labels = y_test[:16]
47 fig = plt.figure()
48 for count, (image, label) in enumerate(zip(images, labels)):
49     image_reshape = np.reshape(image, (1, 28, 28, 1))
50     # predict result
51     proba = model.predict(image_reshape)
52     # 得到概率最大的结果就是预测的结果
53     result = np.argmax(proba, axis=1)
54     print('proba : ', proba)
55     print('class_result: ', result)
56     print("label : ", label)
57     ax = fig.add_subplot(4, 4, count+1)
58     ax.imshow(image, "gray")
59     # 把预测结果设置为标题
60     ax.set_title("[ " + str(label) + " , " + str(result[0]) + " ]")
61     # 关闭坐标轴
62     ax.axis("off")
63 plt.show()
64 pass

代码运行结果:

可以看到仅仅使用一次的卷积神经网络,就可以达到不错的检测效果~

 

参考资料:

https://github.com/christianversloot/machine-learning-articles/blob/main/how-to-predict-new-samples-with-your-keras-model.md

https://medium.com/subex-ai-labs/build-your-1st-deep-learning-classification-model-with-mnist-dataset-1eb27227746b

posted @ 2022-07-01 09:51  ttweixiao9999  阅读(266)  评论(0编辑  收藏  举报