欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Tensorflow之MNIST CNN實現(xiàn)并保存、加載模型

 更新時間:2020年06月17日 10:25:55   作者:uflswe  
這篇文章主要為大家詳細介紹了Tensorflow之MNIST CNN實現(xiàn)并保存、加載模型,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Tensorflow之MNIST CNN實現(xiàn)并保存、加載模型的具體代碼,供大家參考,具體內(nèi)容如下

廢話不說,直接上代碼

# 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()

測試結(jié)果

自己手寫的圖片截的時候要注意,空白部分盡量不要太大,否則測試結(jié)果就呵呵了

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 詳解python tkinter包獲取本地絕對路徑(以獲取圖片并展示)

    詳解python tkinter包獲取本地絕對路徑(以獲取圖片并展示)

    這篇文章主要給大家介紹了關于python tkinter包獲取本地絕對路徑(以獲取圖片并展示)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • Python中網(wǎng)絡請求中Retry策略實現(xiàn)方式

    Python中網(wǎng)絡請求中Retry策略實現(xiàn)方式

    這篇文章主要介紹了Python中網(wǎng)絡請求中Retry策略實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • Python處理mat文件的三種方式小結(jié)

    Python處理mat文件的三種方式小結(jié)

    這篇文章主要介紹了Python處理mat文件的三種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • python安裝pandas庫不成功原因分析及解決辦法

    python安裝pandas庫不成功原因分析及解決辦法

    Pandas是python中非常常用的數(shù)據(jù)分析庫,在數(shù)據(jù)分析、機器學習、深度學習等領域經(jīng)常被使用,下面這篇文章主要給大家介紹了關于python安裝pandas庫不成功原因分析及解決辦法的相關資料
    2023-11-11
  • Pandas中DataFrame對象轉(zhuǎn)置(交換行列)

    Pandas中DataFrame對象轉(zhuǎn)置(交換行列)

    本文主要介紹了Pandas中DataFrame對象轉(zhuǎn)置(交換行列),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • python使用bs4爬取boss直聘靜態(tài)頁面

    python使用bs4爬取boss直聘靜態(tài)頁面

    這篇文章主要介紹了python如何使用bs4爬取boss直聘靜態(tài)頁面,幫助大家更好的理解和學習爬蟲,感興趣的朋友可以了解下
    2020-10-10
  • python實現(xiàn)簡單點對點(p2p)聊天

    python實現(xiàn)簡單點對點(p2p)聊天

    這篇文章主要為大家詳細介紹了python實現(xiàn)簡單點對點p2p聊天,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • Python使用FFMPEG壓縮視頻的方法

    Python使用FFMPEG壓縮視頻的方法

    FFMPEG是一個完整的,跨平臺的解決方案,記錄,轉(zhuǎn)換和流音頻和視頻,,這篇文章主要介紹了FFMPEG視頻壓縮與Python使用方法,需要的朋友可以參考下
    2023-09-09
  • python字符串拼接.join()和拆分.split()詳解

    python字符串拼接.join()和拆分.split()詳解

    這篇文章主要為大家介紹了python字符串拼接.join()和拆分.split(),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • python使用技巧-查找文件?

    python使用技巧-查找文件?

    這篇文章主要分享的是python使用技巧查找文件,下面我們就來介紹針對python查找文件的相關內(nèi)容,需要的小伙伴可以參考一下
    2022-02-02

最新評論