时间:2021-05-22
本文实例为大家分享了Tensorflow之MNIST CNN实现并保存、加载模型的具体代码,供大家参考,具体内容如下
废话不说,直接上代码
# TensorFlow and tf.kerasimport tensorflow as tffrom tensorflow import keras # Helper librariesimport numpy as npimport matplotlib.pyplot as pltimport os #download the datamnist = 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.0test_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 dimensionstrain_images = np.reshape(train_images,[-1,28,28,1])test_images = np.reshape(test_images,[-1,28,28,1]) #trainmodel = create_model() model.fit(train_images, train_labels, epochs=4) #save the modelmodel.save('my_model.h5') #Evaluatetest_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()测试结果
自己手写的图片截的时候要注意,空白部分尽量不要太大,否则测试结果就呵呵了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例为大家分享了基于TensorFlow的CNN实现Mnist手写数字识别的具体代码,供大家参考,具体内容如下一、CNN模型结构输入层:Mnist数据集(2
这里,我们将采用TensorFlow内建函数实现简单的CNN,并用MNIST数据集进行测试第1步:加载相应的库并创建计算图会话importnumpyasnpim
今天,我结合代码来详细介绍如何使用SciSharpSTACK的TensorFlow.NET来训练CNN模型,该模型主要实现图像的分类,可以直接移植该代码在CPU
一、TensorFlow模型保存和提取方法1.TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提取。tf.train.Saver对
TensorFlow模型保存/载入我们在上线使用一个算法模型的时候,首先必须将已经训练好的模型保存下来。tensorflow保存模型的方式与sklearn不太一