Tensorflow之MNIST CNN实现并保存、加载模型

作者:uflswe 时间:2023-10-16 06:21:33 

本文实例为大家分享了Tensorflow之MNIST CNN实现并保存、加载模型的具体代码,供大家参考,具体内容如下

废话不说,直接上代码


# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import os

#download the data
mnist = keras.datasets.mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

train_images = train_images / 255.0
test_images = test_images / 255.0

def create_model():
# It's necessary to give the input_shape,or it will fail when you load the model
# The error will be like : You are trying to load the 4 layer models to the 0 layer
model = keras.Sequential([
  keras.layers.Conv2D(32,[5,5], activation=tf.nn.relu,input_shape = (28,28,1)),
  keras.layers.MaxPool2D(),
  keras.layers.Conv2D(64,[7,7], activation=tf.nn.relu),
  keras.layers.MaxPool2D(),
  keras.layers.Flatten(),
  keras.layers.Dense(576, activation=tf.nn.relu),
  keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=tf.train.AdamOptimizer(),
       loss='sparse_categorical_crossentropy',
       metrics=['accuracy'])

return model

#reshape the shape before using it, for that the input of cnn is 4 dimensions
train_images = np.reshape(train_images,[-1,28,28,1])
test_images = np.reshape(test_images,[-1,28,28,1])

#train
model = create_model()                        
model.fit(train_images, train_labels, epochs=4)

#save the model
model.save('my_model.h5')

#Evaluate
test_loss, test_acc = model.evaluate(test_images, test_labels,verbose = 0)
print('Test accuracy:', test_acc)

模型保存后,自己手写了几张图片,放在文件夹C:\pythonp\testdir2下,开始测试


#Load the model

new_model = keras.models.load_model('my_model.h5')
new_model.compile(optimizer=tf.train.AdamOptimizer(),
       loss='sparse_categorical_crossentropy',
       metrics=['accuracy'])
new_model.summary()

#Evaluate

# test_loss, test_acc = new_model.evaluate(test_images, test_labels)
# print('Test accuracy:', test_acc)

#Predicte

mypath = 'C:\\pythonp\\testdir2'

def getimg(mypath):
 listdir = os.listdir(mypath)
 imgs = []
 for p in listdir:
   img = plt.imread(mypath+'\\'+p)
   # I save the picture that I draw myself under Windows, but the saved picture's
   # encode style is just opposite with the experiment data, so I transfer it with
   # this line.
   img = np.abs(img/255-1)
   imgs.append(img[:,:,0])
 return np.array(imgs),len(imgs)

imgs = getimg(mypath)

test_images = np.reshape(imgs[0],[-1,28,28,1])

predictions = new_model.predict(test_images)

plt.figure()

for i in range(imgs[1]):
c = np.argmax(predictions[i])
plt.subplot(3,3,i+1)
plt.xticks([])
plt.yticks([])
plt.imshow(test_images[i,:,:,0])
plt.title(class_names[c])
plt.show()

测试结果

Tensorflow之MNIST CNN实现并保存、加载模型

自己手写的图片截的时候要注意,空白部分尽量不要太大,否则测试结果就呵呵了

标签:Tensorflow,MNIST,CNN,模型
0
投稿

猜你喜欢

  • 使用python3+xlrd解析Excel的实例

    2021-05-09 23:37:33
  • Oracle 数组的学习 小知识也要积累,养成好的学习态度

    2009-08-04 12:42:00
  • 使用JavaScript和CSS实现文本隔行换色的方法

    2024-04-19 09:46:52
  • 用javascript代替marquee的滚动字幕效果代码

    2024-05-22 10:36:09
  • MySQL timestamp自动更新时间分享

    2024-01-22 11:48:21
  • JS获取当前时间的年月日时分秒及时间的格式化的方法

    2024-04-17 10:23:00
  • Python 爬虫学习笔记之多线程爬虫

    2022-10-03 15:10:37
  • DTS构建组件及其如何完成数据转换服务

    2009-01-20 15:37:00
  • Python操作Jira库常用方法解析

    2022-02-06 01:56:11
  • mac安装mysql初始密码忘记怎么办

    2024-01-16 20:42:45
  • 一文教会你pandas plot各种绘图

    2021-04-29 19:41:11
  • 自学python求已知DNA模板的互补DNA序列

    2022-07-05 13:24:56
  • Vue实现无限加载瀑布流

    2024-05-09 15:23:16
  • Python构建XML树结构的方法示例

    2023-06-22 09:35:07
  • 如何用python 操作MongoDB数据库

    2024-01-27 16:53:10
  • python机器学习实现神经网络示例解析

    2022-10-24 03:45:09
  • 完美解决python遍历删除字典里值为空的元素报错问题

    2023-04-23 13:39:50
  • Python字典循环添加一键多值的用法实例

    2021-07-15 14:48:48
  • 基于JS实现的随机数字抽签实例

    2024-04-16 09:27:23
  • IntelliJ IDEA2020.3 新特性(小结)

    2023-12-24 13:33:13
  • asp之家 网络编程 m.aspxhome.com