1. 程式人生 > >TensorFlow遷移學習-使用谷歌訓練好的Inception-v3網路進行分類

TensorFlow遷移學習-使用谷歌訓練好的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%