基於TensorFlow的Cats vs. Dogs(貓狗大戰)

轉載自   https://blog.csdn.net/qq_16137569/article/details/72802387  https://blog.csdn.net/xinyu3307/article/details/74643019 

自己整理的,剛學,自學,歡迎批評!


目錄

貓狗大戰數據集準備

訓練數據的讀取——input_data.py

導入模塊

生成圖片路徑和標籤的List

生成Batch 

測試

卷積神經網絡模型的構造——model.py 

  簡單的卷積神經網絡

loss計算 

loss損失值優化 

評價/準確率計算 

 

         模型訓練-train.py

  導入文件

 變量聲明

獲取批次batch

操作定義

進行batch的訓練

測試代碼-test.py

 導入模塊

獲取一張圖片

測試圖片



 

貓狗大戰數據集準備

  Cats vs. Dogs(貓狗大戰)是Kaggle大數據競賽某一年的一道賽題,利用給定的數據集,用算法實現貓和狗的識別。 
  數據集可以從Kaggle官網上下載:

  • 12500張cat
  • 12500張dog

https://www.kaggle.com/c/dogs-vs-cats

或者在這裏下載 https://blog.csdn.net/qq_20073741/article/details/81233326

Kaggle官網

  數據集由訓練數據和測試數據組成,訓練數據包含貓和狗各12500張圖片,測試數據包含12500張貓和狗的圖片。 
   
訓練數據

 
 首先在Pycharm上新建Cats_vs_Dogs工程,工程目錄結構爲: 

  •  
  • data文件夾下包含testtrain兩個子文件夾,分別用於存放測試數據和訓練數據,從官網上下載的數據直接解壓到相應的文件夾下即可
  • logs文件夾用於存放我們訓練時的模型結構以及訓練參數
  • input_data.py負責實現讀取數據,生成批次(batch)
  • model.py負責實現我們的神經網絡模型
  • training.py負責實現模型的訓練以及評估
  • test.py 負責我們想測試的圖片

接下來分成數據讀取、模型構造、模型訓練、測試模型四個部分來講。源碼從文章末尾的鏈接下載。

訓練數據的讀取——input_data.py

導入模塊

  tensorflow和numpy不用多說,其中os模塊包含操作系統相關的功能,可以處理文件和目錄這些我們日常手動需要做的操作。因爲我們需要獲取test目錄下的文件,所以要導入os模塊。

import tensorflow as tf
import numpy as np
import os

  

生成圖片路徑和標籤的List

# 獲取文件路徑和標籤
def get_files(file_dir):
    # file_dir: 文件夾路徑
    # return: 亂序後的圖片和標籤

    cats = []
    label_cats = []
    dogs = []
    label_dogs = []
    # 載入數據路徑並寫入標籤值
    for file in os.listdir(file_dir):
        name = file.split(sep='.')
        if name[0] == 'cat':
            cats.append(file_dir + file)
            label_cats.append(0)
        else:
            dogs.append(file_dir + file)
            label_dogs.append(1)
    print("There are %d cats\nThere are %d dogs" % (len(cats), len(dogs)))

    # 打亂文件順序
    image_list = np.hstack((cats, dogs))   #a=[1,2,3] b=[4,5,6] print(np.hstack((a,b)))
                                           #輸出:[1 2 3 4 5 6 ]
    label_list = np.hstack((label_cats, label_dogs))
    temp = np.array([image_list, label_list])
    temp = temp.transpose()     # 轉置
    np.random.shuffle(temp)     ##利用shuffle打亂順序
  
    ##從打亂的temp中再取出list(img和lab)
    image_list = list(temp[:, 0])  
    label_list = list(temp[:, 1])
    label_list = [int(i) for i in label_list]  #字符串類型轉換爲int類型

    return image_list, label_list

  函數get_files(file_dir)的功能是獲取給定路徑file_dir下的所有的訓練數據(包括圖片和標籤),以list的形式返回。 
  由於訓練數據前12500張是貓,後12500張是狗,如果直接按這個順序訓練,訓練效果可能會受影響(我自己猜的),所以需要將順序打亂,至於是讀取數據的時候亂序還是訓練的時候亂序可以自己選擇(視頻裏說在這裏亂序速度比較快)。因爲圖片和標籤是一一對應的,所以要整合到一起亂序。 
  這裏先用np.hstack()方法將貓和狗圖片和標籤整合到一起,得到image_listlabel_listhstack((a,b))的功能是將a和b以水平的方式連接,比如原來catsdogs是長度爲12500的向量,執行了hstack(cats, dogs)後,image_list的長度爲25000,同理label_list的長度也爲25000。接着將一一對應的image_listlabel_list再合併一次。temp的大小是2×25000,經過轉置(變成25000×2),然後使用np.random.shuffle()方法進行亂序。 
  最後從temp中分別取出亂序後的image_listlabel_list列向量,作爲函數的返回值。這裏要注意,因爲label_list裏面的數據類型是字符串類型,所以加上label_list = [int(i) for i in label_list]這麼一行將其轉爲int類型。 
 

生成Batch 

將上面生成的List傳入get_batch() ,轉換類型,產生一個輸入隊列queue,因爲img和lab是分開的,所以使用tf.train.slice_input_producer(),然後用tf.read_file()從隊列中讀取圖像

# 生成相同大小的批次
def get_batch(image, label, image_W, image_H, batch_size, capacity):
    # image, label: 要生成batch的圖像和標籤list
    # image_W, image_H: 圖片的寬高
    # batch_size: 每個batch有多少張圖片
    # capacity: 隊列容量,一個隊列最大多少
    # return: 圖像和標籤的batch

    # 將python.list類型轉換成tf能夠識別的格式
    image = tf.cast(image, tf.string)
    label = tf.cast(label, tf.int32)

    # 生成隊列 ,將image 和 label 放倒隊列裏
    input_queue = tf.train.slice_input_producer([image, label])

    image_contents = tf.read_file(input_queue[0])  ## 讀取圖片的全部信息
    label = input_queue[1]
    #將圖像解碼,不同類型的圖像不能混在一起,要麼只用jpeg,要麼只用png等
    ## 把圖片解碼,channels =3 爲彩色圖片, r,g ,b  黑白圖片爲 1 ,也可以理解爲圖片的厚度
    image = tf.image.decode_jpeg(image_contents, channels=3)

    # 統一圖片大小
    # 將圖片以圖片中心進行裁剪或者擴充爲 指定的image_W,image_H
    # image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
    # 我的方法
    
    image = tf.image.resize_images(image, [image_H, image_W], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)     #最近鄰插值方法
    image = tf.cast(image, tf.float32)          #string類型轉換爲float
    # image = tf.image.per_image_standardization(image)   # 對數據進行標準化,標準化,就是減
                                                           #去它的均值,除以他的方差

    # 生成批次  num_threads 有多少個線程根據電腦配置設置  capacity 隊列中 最多容納圖片的個數 
     #tf.train.shuffle_batch 打亂順序,
    image_batch, label_batch = tf.train.batch([image, label],
                                              batch_size=batch_size,
                                              num_threads=64,   # 線程
                                              capacity=capacity)

    # 這兩行多餘? 重新排列label,行數爲[batch_size],有興趣可以試試看
    # label_batch = tf.reshape(label_batch, [batch_size])
   

    return image_batch, label_batch

  函數get_batch()用於將圖片分批次,因爲一次性將所有25000張圖片載入內存不現實也不必要,所以將圖片分成不同批次進行訓練。這裏傳入的imagelabel參數就是函數get_files()返回的image_listlabel_list,是python中的list類型,所以需要將其轉爲TensorFlow可以識別的tensor格式。 
  這裏使用隊列來獲取數據,因爲隊列操作牽扯到線程,我自己對這塊也不懂,,所以只從大體上理解了一下,想要系統學習可以去官方文檔看看,這裏引用了一張圖解釋。 
   
隊列

  我認爲大體上可以這麼理解:每次訓練時,從隊列中取一個batch送到網絡進行訓練,然後又有新的圖片從訓練庫中注入隊列,這樣循環往復。隊列相當於起到了訓練庫到網絡模型間數據管道的作用,訓練數據通過隊列送入網絡。(我也不確定這麼理解對不對,歡迎指正)

  繼續看程序,我們使用slice_input_producer()來建立一個隊列,將imagelabel放入一個list中當做參數傳給該函數。然後從隊列中取得imagelabel,要注意,用read_file()讀取圖片之後,要按照圖片格式進行解碼。本例程中訓練數據是jpg格式的,所以使用decode_jpeg()解碼器,如果是其他格式,就要用其他解碼器,具體可以從官方API中查詢。注意decode出來的數據類型是uint8,之後模型卷積層裏面conv2d()要求輸入數據爲float32類型,所以如果刪掉標準化步驟之後需要進行類型轉換。

  因爲訓練庫中圖片大小是不一樣的,所以還需要將圖片裁剪成相同大小(img_Wimg_H)。視頻中是用resize_image_with_crop_or_pad()方法來裁剪圖片,這種方法是從圖像中心向四周裁剪,如果圖片超過規定尺寸,最後只會剩中間區域的一部分,可能一隻狗只剩下軀幹,頭都不見了,用這樣的圖片訓練結果肯定會受到影響。所以這裏我稍微改動了一下,使用resize_images()對圖像進行縮放,而不是裁剪,採用NEAREST_NEIGHBOR插值方法(其他幾種插值方法出來的結果圖像是花的,具體原因不知道)。

  縮放之後視頻中還進行了per_image_standardization (標準化)步驟,但加了這步之後,得到的圖片是花的,雖然各個通道單獨提出來是正常的,三通道一起就不對了,刪了標準化這步結果正常,所以這裏把標準化步驟註釋掉了。

  然後用tf.train.batch()方法獲取batch,還有一種方法是tf.train.shuffle_batch(),因爲之前我們已經亂序過了,這裏用普通的batch()就好。視頻中獲取batch後還對label進行了一下reshape()操作,在我看來這步是多餘的,從batch()方法中獲取的大小已經符合我們的要求了,註釋掉也沒什麼影響,能正常獲取圖片。

  最後將得到的image_batchlabel_batch返回。image_batch是一個4D的tensor,[batch, width, height, channels],label_batch是一個1D的tensor,[batch]。

  可以用下面的代碼測試獲取圖片是否成功,因爲之前將圖片轉爲float32了,因此這裏imshow()出來的圖片色彩會有點奇怪,因爲本來imshow()是顯示uint8類型的數據(灰度值在uint8類型下是0~255,轉爲float32後會超出這個範圍,所以色彩有點奇怪),不過這不影響後面模型的訓練。

測試

 變量初始化,每批2張圖,尺寸208x208,設置好自己的圖像路徑

# TEST
import matplotlib.pyplot as plt

BATCH_SIZE = 2
CAPACITY = 256
IMG_W = 208
IMG_H = 208

train_dir = "data\\train\\"
 #調用前面的兩個函數,生成batch
image_list, label_list = get_files(train_dir)
image_batch, label_batch = get_batch(image_list, label_list, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)

#開啓會話session,利用tf.train.Coordinator()和tf.train.start_queue_runners(coord=coord)來監控隊列(這裏有個問題:官網的start_queue_runners()是有兩個參數的,sess和coord,但是在這裏加上sess的話會報錯)。 
利用try——except——finally結構來執行隊列操作(官網推薦的方法),避免程序卡死什麼的。i<2執行兩次隊列操作,每一次取出2張圖放進batch裏面,然後imshow出來看看效果

with tf.Session() as sess:
    i = 0
    ##  Coordinator  和 start_queue_runners 監控 queue 的狀態,不停的入隊出隊1
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    try:
        while not coord.should_stop() and i < 1:
            img, label = sess.run([image_batch, label_batch])

            for j in np.arange(BATCH_SIZE):
                print("label: %d" % label[j])
                plt.imshow(img[j, :, :, :])
                plt.show()
            i += 1
   #隊列中沒有數據
    except tf.errors.OutOfRangeError:
        print("done!")
    finally:
        coord.request_stop()
    coord.join(threads)

卷積神經網絡模型的構造——model.py 

        關於神經網絡模型不想說太多,視頻中使用的模型是仿照TensorFlow的官方例程cifar-10的網絡結構來寫的。就是兩個卷積層(每個卷積層後加一個池化層),兩個全連接層,最後一個softmax輸出分類結果。

  簡單的卷積神經網絡

 

 

  • 一個簡單的卷積神經網絡,卷積+池化層x2,全連接層x2,最後一個softmax層做分類。 
    推理函數:def inference(images, batch_size, n_classes):

  • 輸入參數: 
    images,image batch、4D tensor、tf.float32、[batch_size, width, height, channels]
  • 返回參數: 
    logits, float、 [batch_size, n_classes]
  • import tensorflow as tf
    
    # 結構
    # conv1   卷積層 1
    # pooling1_lrn  池化層 1
    # conv2  卷積層 2
    # pooling2_lrn 池化層 2
    # local3 全連接層 1
    # local4 全連接層 2
    # softmax 全連接層 3
    
    def inference(images, batch_size, n_classes):
        # conv1, shape = [kernel_size, kernel_size, channels, kernel_numbers]
        #卷積層1 16個3x3的卷積核(3通道),padding=’SAME’,表示padding後卷積的圖與原圖尺寸一致,激活函數relu()
        with tf.variable_scope("conv1") as scope:
            weights = tf.get_variable("weights",
                                      shape=[3, 3, 3, 16],
                                      dtype=tf.float32,
                                      initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
            biases = tf.get_variable("biases",
                                     shape=[16],
                                     dtype=tf.float32,
                                     initializer=tf.constant_initializer(0.1))
            conv = tf.nn.conv2d(images, weights, strides=[1, 1, 1, 1], padding="SAME")
            pre_activation = tf.nn.bias_add(conv, biases)
            conv1 = tf.nn.relu(pre_activation, name="conv1")
    
        # pool1 && norm1 
        # 池化層1 3x3最大池化,步長strides爲2,池化後執行lrn()操作,局部響應歸一化,對訓練有利。
        with tf.variable_scope("pooling1_lrn") as scope:
            pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],
                                   padding="SAME", name="pooling1")
            norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001/9.0,
                              beta=0.75, name='norm1')
    
        # conv2
        #卷積層2 16個3x3的卷積核(16通道),padding=’SAME’,表示padding後卷積的圖與原圖尺寸一致,激活函數relu()
        with tf.variable_scope("conv2") as scope:
            weights = tf.get_variable("weights",
                                      shape=[3, 3, 16, 16],
                                      dtype=tf.float32,
                                      initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
            biases = tf.get_variable("biases",
                                     shape=[16],
                                     dtype=tf.float32,
                                     initializer=tf.constant_initializer(0.1))
            conv = tf.nn.conv2d(norm1, weights, strides=[1, 1, 1, 1], padding="SAME")
            pre_activation = tf.nn.bias_add(conv, biases)
            conv2 = tf.nn.relu(pre_activation, name="conv2")
    
        # pool2 && norm2
        #池化層2 3x3最大池化,步長strides爲2,池化後執行lrn()操作,
        with tf.variable_scope("pooling2_lrn") as scope:
            pool2 = tf.nn.max_pool(conv2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],
                                   padding="SAME", name="pooling2")
            norm2 = tf.nn.lrn(pool2, depth_radius=4, bias=1.0, alpha=0.001/9.0,
                              beta=0.75, name='norm2')
    
        # full-connect1 
        #全連接層1 128個神經元,將之前pool層的輸出reshape成一行,激活函數relu()
        with tf.variable_scope("fc1") as scope:
            reshape = tf.reshape(norm2, shape=[batch_size, -1])
            dim = reshape.get_shape()[1].value
            weights = tf.get_variable("weights",
                                      shape=[dim, 128],
                                      dtype=tf.float32,
                                      initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
            biases = tf.get_variable("biases",
                                     shape=[128],
                                     dtype=tf.float32,
                                     initializer=tf.constant_initializer(0.1))
            fc1 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name="fc1")
    
        # full_connect2
        #全連接層2 128個神經元,激活函數relu()
        with tf.variable_scope("fc2") as scope:
            weights = tf.get_variable("weights",
                                      shape=[128, 128],
                                      dtype=tf.float32,
                                      initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
            biases = tf.get_variable("biases",
                                     shape=[128],
                                     dtype=tf.float32,
                                     initializer=tf.constant_initializer(0.1))
            fc2 = tf.nn.relu(tf.matmul(fc1, weights) + biases, name="fc2")
    
        # softmax 
        #Softmax迴歸層 將前面的FC層輸出,做一個線性迴歸,計算出每一類的得分,在這裏是2類,所以這個層輸出的是兩個得分
        with tf.variable_scope("softmax_linear") as scope:
           #weights = tf.get_variable("softmax_linear",有一個鏈接是寫成這樣子的,大家可以試試
            weights = tf.get_variable("weights",
                                      shape=[128, n_classes],
                                      dtype=tf.float32,
                                      initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
            biases = tf.get_variable("biases",
                                     shape=[n_classes],
                                     dtype=tf.float32,
                                     initializer=tf.constant_initializer(0.1))
            softmax_linear = tf.add(tf.matmul(fc2, weights), biases, name="softmax_linear")
            softmax_linear = tf.nn.softmax(softmax_linear)
        return softmax_linear

 

發現程序裏面有很多with tf.variable_scope("name")的語句,這其實是TensorFlow中的變量作用域機制,目的是有效便捷地管理需要的變量。 
  變量作用域機制在TensorFlow中主要由兩部分組成:

  • tf.get_variable(<name>, <shape>, <initializer>): 創建一個變量
  • tf.variable_scope(<scope_name>): 指定命名空間

如果需要共享變量,需要通過reuse_variables()方法來指定,詳細的例子去官方文檔中看就好了。(鏈接在博客參考部分)

loss計算 


    將網絡計算得出的每類得分與真實值進行比較,得出一個loss損失值,這個值代表了計算值與期望值的差距。這裏使用的loss函數是交叉熵。一批loss取平均數。最後調用了summary.scalar()記錄下這個標量數據,在TensorBoard中進行可視化。 
函數:def losses(logits, labels):

  • 傳入參數:logits,網絡計算輸出值。labels,真實值,在這裏是0或者1
  • 返回參數:loss,損失值
#loss計算
def losses(logits, labels):
    with tf.variable_scope("loss") as scope:
        cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
                                                                       labels=labels, name="xentropy_per_example")
        loss = tf.reduce_mean(cross_entropy, name="loss")
        tf.summary.scalar(scope.name + "loss", loss)
    return loss




loss損失值優化 


目的就是讓loss越小越好,使用的是AdamOptimizer優化器 
函數:def trainning(loss, learning_rate):

  • 輸入參數:loss。learning_rate,學習速率。
  • 返回參數:train_op,訓練op,這個參數要輸入sess.run中讓模型去訓練

 

#loss損失值優化 
def trainning(loss, learning_rate):
    with tf.name_scope("optimizer"):
        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
        global_step = tf.Variable(0, name="global_step", trainable=False)
        train_op = optimizer.minimize(loss, global_step=global_step)
    return train_op

評價/準確率計算 


計算出平均準確率來評價這個模型,在訓練過程中按批次計算(每隔N步計算一次),可以看到準確率的變換情況。 
函數:def evaluation(logits, labels):

  • 輸入參數:logits,網絡計算值。labels,標籤,也就是真實值,在這裏是0或者1。
  • 返回參數:accuracy,當前step的平均準確率,也就是在這些batch中多少張圖片被正確分類了

 

#評價/準確率計算
def evaluation(logits, labels):
    with tf.variable_scope("accuracy") as scope:
        correct = tf.nn.in_top_k(logits, labels, 1)
        correct = tf.cast(correct, tf.float16)
        accuracy = tf.reduce_mean(correct)
        tf.summary.scalar(scope.name + "accuracy", accuracy)
    return accuracy

 

 函數losses(logits, labels)用於計算訓練過程中的loss,這裏輸入參數logtis是函數inference()的輸出,代表圖片對貓和狗的預測概率,labels則是圖片對應的標籤。 
  通過在程序中設置斷點,查看logtis的值,結果如下圖所示,根據這個就很好理解了,一個數值代表屬於貓的概率,一個數值代表屬於狗的概率,兩者的和爲1。

logtis變量

  而函數tf.nn.sparse_sotfmax_cross_entropy_with_logtis從名字就很好理解,是將稀疏表示的label與輸出層計算出來結果做對比。然後因爲訓練的時候是16張圖片一個batch,所以再用tf.reduce_mean求一下平均值,就得到了這個batch的平均loss。 
  training(loss, learning_rate)就沒什麼好說的了,loss是訓練的loss,learning_rate是學習率,使用AdamOptimizer優化器來使loss朝着變小的方向優化。 
  evaluation(logits, labels)功能是在訓練過程中實時監測驗證數據的準確率,達到反映訓練效果的作用。

 

模型訓練-train.py

  導入文件

import os
import numpy as np
import tensorflow as tf
import input_data
import model

 變量聲明

N_CLASSES = 2 # 2個輸出神經元,[1,0] 或者 [0,1]貓和狗的概率
IMG_W = 208  # resize圖像,太大的話訓練時間久
IMG_H = 208
BATCH_SIZE = 16
CAPACITY = 2000
MAX_STEP = 10000 # 一般大於10K
learning_rate = 0.0001 # 一般小於0.0001

獲取批次batch

train_dir = './data/train/'
logs_train_dir = './logs/train/'    #這個目錄會自動生成
  
 # 獲取圖片和標籤集
train, train_label = input_data.get_files(train_dir)
 ## 生成批次
train_batch,train_label_batch=input_data.get_batch(train,
                                train_label,
                                IMG_W,
                                IMG_H,
                                BATCH_SIZE,
                                CAPACITY)

操作定義

#操作定義  進入模型
train_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)
#獲取loss
train_loss = model.losses(train_logits, train_label_batch)        
#訓練
train_op = model.trainning(train_loss, learning_rate)
#獲取準確率
train__acc = model.evaluation(train_logits, train_label_batch)
合併summary
summary_op = tf.summary.merge_all() #這個是log彙總記錄
#產生一個會話
sess = tf.Session()  
#產生一個writer來寫log文件
train_writer = tf.summary.FileWriter(logs_train_dir, sess.graph) 
 #產生一個saver來存儲訓練好的模型
saver = tf.train.Saver()
#所有節點初始化
sess.run(tf.global_variables_initializer()) 

#隊列監控
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

進行batch的訓練

#進行batch的訓練
try:
    #執行MAX_STEP步的訓練,一步一個batch
    for step in np.arange(MAX_STEP):
        if coord.should_stop():
                break
        #啓動以下操作節點,有個疑問,爲什麼train_logits在這裏沒有開啓?
        _, tra_loss, tra_acc = sess.run([train_op, train_loss, train__acc])
        #每隔50步打印一次當前的loss以及acc,同時記錄log,寫入writer   
        if step % 50 == 0:
            print('Step %d, train loss = %.2f, train accuracy = %.2f%%' %(step, tra_loss, tra_acc*100.0))
            summary_str = sess.run(summary_op)
            train_writer.add_summary(summary_str, step)
        #每隔2000步,保存一次訓練好的模型
        if step % 2000 == 0 or (step + 1) == MAX_STEP:
            checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')
            saver.save(sess, checkpoint_path, global_step=step)

except tf.errors.OutOfRangeError:
    print('Done training -- epoch limit reached')
finally:
    coord.request_stop()

測試代碼-test.py

 導入模塊

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):

       輸入參數:train,訓練圖片的路徑

       返回參數:image,從訓練圖片中隨機抽取一張圖片   

  • #從指定目錄中選取一張圖片
    def get_one_image(train):
        files = os.listdir(train)
        n = len(files)
        n = len(train)
        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():

  • #測試圖片
    def evaluate_one_image():
        #存放我們想測試的圖片集
        train = './data/test/'
        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 的返回沒有用激活函數,所以在這裏對結果用softmax 激活
           logit = tf.nn.softmax(logit)
           # 用最原始的輸入數據的方式向模型輸入數據 placeholder
           x = tf.placeholder(tf.float32, shape=[208, 208, 3])
    
           # 我門存放模型的路徑
           logs_train_dir = './Logs/train'
    
            # 定義saver
           saver = tf.train.Saver()
    
           with tf.Session() as sess:
    
               print("Reading checkpoints...")
               # 將模型加載到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('Loading success, global_step is %s' % global_step)
               else:
                   print('No checkpoint file found')
    
               prediction = sess.run(logit, feed_dict={x: image_array})
               max_index = np.argmax(prediction)
               if max_index==0:
                   print('This is a cat with possibility %.6f' %prediction[:, 0])
               else:
                   print('This is a dog with possibility %.6f' %prediction[:, 1])

  •  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章