ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-07-01 10:03:13  阅读:180  来源: 互联网

标签:Predict image 28 add train test tensorflow model 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

标签:Predict,image,28,add,train,test,tensorflow,model,recognition
来源: https://www.cnblogs.com/ttweixiao-IT-program/p/16418616.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有