TensorFlow遷移學習-使用谷歌訓練好的Inception-v3網絡進行分類

本文代碼可在https://github.com/TimeIvyace/TensorFlow_Migration-learning_Inception-v3.git中下載,需要同時下載數據集Inception-v3模型
注:代碼中文件夾放置位置需要自行修改。

遷移學習是將一個數據集上訓練好的網絡模型快速轉移到另外一個數據集上,可以保留訓練好的模型中倒數第一層之前的所有參數,替換最後一層即可,在最後層之前的網絡層稱之爲瓶頸層。
下面代碼是使用TensorFlow將ImageNet上訓練好的Inception-v3模型轉移到另外一個圖像分類數據集上。
數據集Inception-v3模型可在此點擊下載。數據集文件夾包含5個子文件,每一個子文件夾的名稱爲一種花的名稱,代表了不同的類別。平均每一種花有734張圖片,每一張圖片都是RGB色彩模式,大小也不相同,程序將直接處理沒有整理過的圖像數據。

注意:計算交叉熵損失函數時,sparse_softmax_cross_entropy_with_logits直接用標籤就可以計算交叉熵,而softmax_cross_entropy_with_logits是需要標籤的one hot向量來參與計算,並且需要argmax得到標籤最大值位置,如此代碼中第58行所示。

# -*- coding: utf-8 -*-

import glob  # 返回一個包含有匹配文件/目錄的數組
import os.path
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile

# inception-v3瓶頸層的節點個數
BOTTLENECT_TENSOR_SIZE = 2048

# 在谷歌提供的inception-v3模型中,瓶頸層結果的張量名稱爲'pool_3/_reshape:0'
# 可以使用tensor.name來獲取張量名稱
BOTTLENECT_TENSOR_NAME = 'pool_3/_reshape:0'

# 圖像輸入張量所對應的名稱
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'

# 下載的谷歌inception-v3模型文件目錄
MODEL_DIR = '/tensorflow_google/inception_model'

# 下載的訓練好的模型文件名
MODEL_FILE = 'tensorflow_inception_graph.pb'

# 將原始圖像通過inception-v3模型計算得到的特徵向量保存在文件中,下面定義文件存放地址
CACHE_DIR = '/tensorflow_google/bottleneck'

# 圖片數據文件夾,子文件爲類別
INPUT_DATA = '/tensorflow_google/flower_photos'

# 驗證的數據百分比
VALIDATION_PRECENTAGE = 10
# 測試的數據百分比
TEST_PRECENTAGE = 10

# 定義神經網絡的參數
LEARNING_RATE = 0.01
STEPS = 4000
BATCH = 100


# 從數據文件夾中讀取所有的圖片列表並按訓練、驗證、測試數據分開
# testing_percentage和validation_percentage指定測試和驗證數據集的大小
def create_image_lists(testing_percentage, validation_percentage):
    # 得到的圖片放到result字典中,key爲類別名稱,value爲類別下的各個圖片(也是字典)
    result = {}
    # 獲取當前目錄下所有的子目錄
    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
    # sub_dirs中第一個目錄是當前目錄,即flower_photos,不用考慮
    is_root_dir = True
    for sub_dir in sub_dirs:
        if is_root_dir:
            is_root_dir = False
            continue

        # 獲取當前目錄下所有的有效圖片文件
        extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
        file_list = []
        # 獲取當前文件名
        dir_name = os.path.basename(sub_dir)
        for extension in extensions:
            # 將分離的各部分組成一個路徑名,如/flower_photos/roses/*.JPEG
            file_glob = os.path.join(INPUT_DATA, dir_name, '*.'+extension)
            # glob.glob()返回的是所有路徑下的符合條件的文件名的列表
            file_list.extend(glob.glob(file_glob))
        if not file_list: continue

        # 通過目錄名獲取類別的名稱(全部小寫)
        label_name = dir_name.lower()
        # 初始化當前類別的訓練數據集、測試數據集和驗證數據集
        training_images = []
        testing_images = []
        validation_images = []
        for file_name in file_list:
            base_name = os.path.basename(file_name) #獲取當前文件名
            # 隨機將數據分到訓練數據集、測試數據集以及驗證數據集
            chance = np.random.randint(100) #隨機返回一個整數
            if chance < validation_percentage:
                validation_images.append(base_name)
            elif chance < (testing_percentage + validation_percentage):
                testing_images.append(base_name)
            else:
                training_images.append(base_name)

        # 將當前類別的數據放入結果字典
        result[label_name] = {'dir': dir_name, 'training': training_images,
                              'testing': testing_images, 'validation': validation_images}
    return result


# 通過類別名稱、所屬數據集和圖片編號獲取一張圖片的地址
# image_lists爲所有圖片信息,image_dir給出根目錄,label_name爲類別名稱,index爲圖片編號,category指定圖片是在哪個訓練集
def get_image_path(image_lists, image_dir, label_name, index, category):
    # 獲取給定類別中所有圖片的信息
    label_lists = image_lists[label_name]
    # 根據所屬數據集的名稱獲取集合中的全部圖片信息
    category_list = label_lists[category]
    mod_index = index % len(category_list)
    # 獲取圖片的文件名
    base_name = category_list[mod_index]
    sub_dir = label_lists['dir']
    # 最終的地址爲數據根目錄的地址加上類別的文件夾加上圖片的名稱
    full_path = os.path.join(image_dir, sub_dir, base_name)
    return full_path


# 通過類別名稱、所屬數據集和圖片編號經過inception-v3處理之後的特徵向量文件地址
def get_bottleneck_path(image_lists, label_name, index, category):
    return get_image_path(image_lists, CACHE_DIR, label_name, index, category)+'.txt'


# 使用加載的訓練好的網絡處理一張圖片,得到這個圖片的特徵向量
def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):
    # 將當前圖片作爲輸入,計算瓶頸張量的值
    # 這個張量的值就是這張圖片的新的特徵向量
    bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})
    # 經過卷積神經網絡處理的結果是一個四維數組,需要將這個結果壓縮成一個一維數組
    bottleneck_values = np.squeeze(bottleneck_values) #從數組的形狀中刪除單維條目
    return  bottleneck_values


# 獲取一張圖片經過inception-v3模型處理之後的特徵向量
# 先尋找已經計算並且保存的向量,若找不到則計算然後保存到文件
def get_or_create_bottleneck(sess, image_lists, label_name, index, category,
                             jpeg_data_tensor, bottleneck_tensor):
    # 獲取一張圖片對應的特徵向量文件路徑
    label_lists = image_lists[label_name]
    sub_dir = label_lists['dir']
    sub_dir_path = os.path.join(CACHE_DIR, sub_dir)
    if not os.path.exists(sub_dir_path):
        os.makedirs(sub_dir_path) #若不存在則創建
    bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)

    # 如果這個特徵向量文件不存在,則通過inception-v3計算,並存入文件
    if not os.path.exists(bottleneck_path):
        # 獲取原始的圖片路徑
        image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)
        # 獲取圖片內容,對圖片的讀取
        image_data = gfile.FastGFile(image_path, 'rb').read()
        # 通過inception-v3計算特徵向量
        bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)
        # 將計算得到的特徵向量存入文件,join()連接字符串
        bottleneck_string = ','.join(str(x) for x in bottleneck_values)
        with open(bottleneck_path, 'w') as bottleneck_file:  #打開文件並寫入
            bottleneck_file.write(bottleneck_string)
    else:
        # 直接從文件中獲取圖片相應的特徵向量
        with open(bottleneck_path, 'r') as bottleneck_file:
            bottleneck_string = bottleneck_file.read()
        bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
    # 返回特徵向量
    return bottleneck_values


# 隨機選取一個batch的圖片作爲訓練數據
def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category,
                                  jpeg_data_tensor, bottleneck_tensor):
    bottlenecks = []
    ground_truths = []
    for _ in range(how_many):
        # 隨機一個類別和圖片的編號加入當前的訓練數據
        label_index = random.randrange(n_classes)  # 返回指定遞增基數集合中的一個隨機數,基數缺省值爲1,隨機類別號
        label_name = list(image_lists.keys())[label_index]
        image_index = random.randrange(65536)
        bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, image_index,
                                              category, jpeg_data_tensor, bottleneck_tensor)
        ground_truth = np.zeros(n_classes, dtype=np.float32)
        ground_truth[label_index] = 1.0
        bottlenecks.append(bottleneck)
        ground_truths.append(ground_truth)

    return bottlenecks, ground_truths


# 獲取全部的測試數據,在最終測試的時候在所有測試數據上計算正確率
def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):
    bottlenecks = []
    ground_truths = []
    label_name_list = list(image_lists.keys())
    # 枚舉所有類別和每個類別中的測試圖片
    for label_index, label_name in enumerate(label_name_list):
        category = 'testing'
        for index, unused_base_name in enumerate(image_lists[label_name][category]):
            # 通過inception-v3計算圖片對應的特徵向量,並將其加入最終數據的列表
            bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,
                                                  jpeg_data_tensor, bottleneck_tensor)
            ground_truth = np.zeros(n_classes, dtype=np.float32)
            ground_truth[label_index] = 1.0
            bottlenecks.append(bottleneck)
            ground_truths.append(ground_truth)
    return bottlenecks, ground_truths


def main(_):
    # 讀取所有圖片
    image_lists = create_image_lists(TEST_PRECENTAGE, VALIDATION_PRECENTAGE)
    # image_lists.keys()爲dict_keys(['roses', 'sunflowers', 'daisy', 'dandelion', 'tulips'])
    n_classes = len(image_lists.keys()) # 類別數
    # 讀取已經訓練好的inception-v3模型,谷歌訓練好的模型保存在了GraphDef Protocol Buffer中
    # 裏面保存了每一個節點取值的計算方法以及變量的取值
    # 對模型的讀取,二進制
    with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:
        #  新建GraphDef文件,用於臨時載入模型中的圖
        graph_def = tf.GraphDef()
        # 加載模型中的圖
        graph_def.ParseFromString(f.read())
        # 加載讀取的inception模型,並返回數據輸出所對應的張量以及計算瓶頸層結果所對應的張量
        # 從圖上讀取張量,同時把圖設爲默認圖
        # Tensor("import/pool_3/_reshape:0", shape=(1, 2048), dtype=float32)
        # Tensor("import/DecodeJpeg/contents:0", shape=(), dtype=string)
        bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def, return_elements=[BOTTLENECT_TENSOR_NAME,
                                                                                              JPEG_DATA_TENSOR_NAME])

        # 定義新的神經網絡輸入,這個輸入就是新的圖片經過inception模型前向傳播達到瓶頸層的節點取值,None爲了batch服務
        bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECT_TENSOR_SIZE],
                                          name='BottleneckInputPlaceholder')
        # 定義新的標準答案
        ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')

        # 定義一層全連接層來解決新的圖片分類問題
        with tf.name_scope('final_training_ops'):
            weights = tf.Variable(tf.truncated_normal([BOTTLENECT_TENSOR_SIZE, n_classes], stddev=0.001))
            biases = tf.Variable(tf.zeros([n_classes]))
            logits = tf.matmul(bottleneck_input, weights) + biases
            final_tensor = tf.nn.softmax(logits)

        # 定義交叉熵損失函數
        # tf.nn.softmax中dim默認爲-1,即tf.nn.softmax會以最後一個維度作爲一維向量計算softmax
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input)
        cross_entropy_mean = tf.reduce_mean(cross_entropy)
        train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)

        # 計算正確率
        with tf.name_scope('evaluation'):
            correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))
            # 平均錯誤率,cast將bool值轉成float
            evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        with tf.Session() as sess:
            init = tf.initialize_all_variables()
            sess.run(init)

            # 訓練過程
            for i in range(STEPS):
                # 每次獲取一個batch的訓練數據
                train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks\
                    (sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)
                sess.run(train_step, feed_dict={bottleneck_input: train_bottlenecks,
                                                ground_truth_input: train_ground_truth})

                # 在驗證數據上測試正確率
                if i % 100 == 0 or i+1 == STEPS:
                    validation_bottlenecks, validation_ground_truth = \
                        get_random_cached_bottlenecks(sess, n_classes, image_lists, BATCH,
                                                      'validation', jpeg_data_tensor, bottleneck_tensor)
                    validation_accuracy = sess.run(evaluation_step,
                                                   feed_dict={bottleneck_input: validation_bottlenecks,
                                                              ground_truth_input: validation_ground_truth})
                    print('Step %d :Validation accuracy on random sampled %d examples = %.1f%%' %
                          (i, BATCH, validation_accuracy*100))

            # 在最後的測試數據上測試正確率
            test_bottlenecks, test_ground_truth = get_test_bottlenecks(sess, image_lists, n_classes,
                                                                       jpeg_data_tensor, bottleneck_tensor)
            test_accuracy = sess.run(evaluation_step, feed_dict={bottleneck_input: test_bottlenecks,
                                                                 ground_truth_input: test_ground_truth})
            print('Final test accuracy = %.1f%%' % (test_accuracy*100))


if __name__ == '__main__':
    tf.app.run()

輸出結果:

Step 0 :Validation accuracy on random sampled 100 examples = 45.0%
Step 100 :Validation accuracy on random sampled 100 examples = 78.0%
Step 200 :Validation accuracy on random sampled 100 examples = 85.0%
Step 300 :Validation accuracy on random sampled 100 examples = 82.0%
Step 400 :Validation accuracy on random sampled 100 examples = 84.0%
Step 500 :Validation accuracy on random sampled 100 examples = 84.0%
Step 600 :Validation accuracy on random sampled 100 examples = 84.0%
Step 700 :Validation accuracy on random sampled 100 examples = 87.0%
Step 800 :Validation accuracy on random sampled 100 examples = 90.0%
Step 900 :Validation accuracy on random sampled 100 examples = 85.0%
Step 1000 :Validation accuracy on random sampled 100 examples = 84.0%
Step 1100 :Validation accuracy on random sampled 100 examples = 88.0%
Step 1200 :Validation accuracy on random sampled 100 examples = 81.0%
Step 1300 :Validation accuracy on random sampled 100 examples = 85.0%
Step 1400 :Validation accuracy on random sampled 100 examples = 82.0%
Step 1500 :Validation accuracy on random sampled 100 examples = 82.0%
Step 1600 :Validation accuracy on random sampled 100 examples = 90.0%
Step 1700 :Validation accuracy on random sampled 100 examples = 90.0%
Step 1800 :Validation accuracy on random sampled 100 examples = 84.0%
Step 1900 :Validation accuracy on random sampled 100 examples = 88.0%
Step 2000 :Validation accuracy on random sampled 100 examples = 84.0%
Step 2100 :Validation accuracy on random sampled 100 examples = 88.0%
Step 2200 :Validation accuracy on random sampled 100 examples = 81.0%
Step 2300 :Validation accuracy on random sampled 100 examples = 92.0%
Step 2400 :Validation accuracy on random sampled 100 examples = 87.0%
Step 2500 :Validation accuracy on random sampled 100 examples = 80.0%
Step 2600 :Validation accuracy on random sampled 100 examples = 89.0%
Step 2700 :Validation accuracy on random sampled 100 examples = 87.0%
Step 2800 :Validation accuracy on random sampled 100 examples = 91.0%
Step 2900 :Validation accuracy on random sampled 100 examples = 90.0%
Step 3000 :Validation accuracy on random sampled 100 examples = 93.0%
Step 3100 :Validation accuracy on random sampled 100 examples = 88.0%
Step 3200 :Validation accuracy on random sampled 100 examples = 85.0%
Step 3300 :Validation accuracy on random sampled 100 examples = 91.0%
Step 3400 :Validation accuracy on random sampled 100 examples = 85.0%
Step 3500 :Validation accuracy on random sampled 100 examples = 87.0%
Step 3600 :Validation accuracy on random sampled 100 examples = 89.0%
Step 3700 :Validation accuracy on random sampled 100 examples = 88.0%
Step 3800 :Validation accuracy on random sampled 100 examples = 88.0%
Step 3900 :Validation accuracy on random sampled 100 examples = 85.0%
Step 3999 :Validation accuracy on random sampled 100 examples = 89.0%
Final test accuracy = 90.8%
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章