TensorFlow卷積神經網絡之使用訓練好的模型識別貓狗圖片
本文是Python通過TensorFlow卷積神經網絡實現(xiàn)貓狗識別的姊妹篇,是加載上一篇訓練好的模型,進行貓狗識別
本文邏輯:
- 我從網上下載了十幾張貓和狗的圖片,用于檢驗我們訓練好的模型。
- 處理我們下載的圖片
- 加載模型
- 將圖片輸入模型進行檢驗
代碼如下:
#coding=utf-8
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import input_data
import numpy as np
import model
import os
#從指定目錄中選取一張圖片
def get_one_image(train):
files = os.listdir(train)
n = len(files)
ind = np.random.randint(0,n)
img_dir = os.path.join(train,files[ind])
image = Image.open(img_dir)
plt.imshow(image)
plt.show()
image = image.resize([208, 208])
image = np.array(image)
return image
def evaluate_one_image():
#存放的是我從百度下載的貓狗圖片路徑
train = '/Users/yangyibo/GitWork/pythonLean/AI/貓狗識別/testImg/'
image_array = get_one_image(train)
with tf.Graph().as_default():
BATCH_SIZE = 1 # 因為只讀取一副圖片 所以batch 設置為1
N_CLASSES = 2 # 2個輸出神經元,[1,0] 或者 [0,1]貓和狗的概率
# 轉化圖片格式
image = tf.cast(image_array, tf.float32)
# 圖片標準化
image = tf.image.per_image_standardization(image)
# 圖片原來是三維的 [208, 208, 3] 重新定義圖片形狀 改為一個4D 四維的 tensor
image = tf.reshape(image, [1, 208, 208, 3])
logit = model.inference(image, BATCH_SIZE, N_CLASSES)
# 因為 inference 的返回沒有用激活函數(shù),所以在這里對結果用softmax 激活
logit = tf.nn.softmax(logit)
# 用最原始的輸入數(shù)據的方式向模型輸入數(shù)據 placeholder
x = tf.placeholder(tf.float32, shape=[208, 208, 3])
# 我門存放模型的路徑
logs_train_dir = '/Users/yangyibo/GitWork/pythonLean/AI/貓狗識別/saveNet/'
# 定義saver
saver = tf.train.Saver()
with tf.Session() as sess:
print("從指定的路徑中加載模型。。。。")
# 將模型加載到sess 中
ckpt = tf.train.get_checkpoint_state(logs_train_dir)
if ckpt and ckpt.model_checkpoint_path:
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
saver.restore(sess, ckpt.model_checkpoint_path)
print('模型加載成功, 訓練的步數(shù)為 %s' % global_step)
else:
print('模型加載失敗,,,文件沒有找到')
# 將圖片輸入到模型計算
prediction = sess.run(logit, feed_dict={x: image_array})
# 獲取輸出結果中最大概率的索引
max_index = np.argmax(prediction)
if max_index==0:
print('貓的概率 %.6f' %prediction[:, 0])
else:
print('狗的概率 %.6f' %prediction[:, 1])
# 測試
evaluate_one_image()
/Users/yangyibo/GitWork/pythonLean/AI/貓狗識別/testImg/ 存放的是我從百度下載的貓狗圖片

執(zhí)行結果:
因為從testimg 中選取圖片是隨機的,所以每次執(zhí)行的結果不同
從指定的路徑中加載模型。。。。
模型加載成功, 訓練的步數(shù)為 11999
狗的概率 0.964047
[Finished in 6.8s]
代碼地址:https://github.com/527515025/My-TensorFlow-tutorials/blob/master/貓狗識別/evaluateCatOrDog.py
歡迎star。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
詳解如何使用Python的Plotly庫進行交互式圖形可視化
Python中有許多強大的工具和庫可用于創(chuàng)建交互式圖形,其中之一就是Plotly庫,Plotly庫提供了豐富的功能和靈活的接口,使得創(chuàng)建各種類型的交互式圖形變得簡單而直觀,本文將介紹如何使用Plotly庫來創(chuàng)建交互式圖形,需要的朋友可以參考下2024-05-05
python爬蟲開發(fā)之使用Python爬蟲庫requests多線程抓取貓眼電影TOP100實例
這篇文章主要介紹了python爬蟲開發(fā)之使用Python爬蟲庫requests多線程抓取貓眼電影TOP100實例,需要的朋友可以參考下2020-03-03
詳解Python中Sync與Async執(zhí)行速度快慢對比
Python新的版本中支持了async/await語法, 很多文章都在說這種語法的實現(xiàn)代碼會變得很快, 但是這種快是有場景限制的。這篇文章將嘗試簡單的解釋為何Async的代碼在某些場景比Sync的代碼快2023-03-03

