1. 程式人生 > >tensorflow-Inception-v3模型訓練自己的資料程式碼示例

tensorflow-Inception-v3模型訓練自己的資料程式碼示例

一、宣告

  本程式碼非原創,源網址不詳,僅做學習參考。

二、程式碼  

  1 # -*- coding: utf-8 -*-
  2 
  3 import glob  # 返回一個包含有匹配檔案/目錄的陣列
  4 import os.path
  5 import random
  6 import numpy as np
  7 import tensorflow as tf
  8 from tensorflow.python.platform import gfile
  9 
 10 # inception-v3瓶頸層的節點個數
 11 BOTTLENECT_TENSOR_SIZE = 2048
 12
13 # 在谷歌提供的inception-v3模型中,瓶頸層結果的張量名稱為'pool_3/_reshape:0' 14 # 可以使用tensor.name來獲取張量名稱 15 BOTTLENECT_TENSOR_NAME = 'pool_3/_reshape:0' 16 17 # 影象輸入張量所對應的名稱 18 JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' 19 20 # 下載的谷歌inception-v3模型檔案目錄 21 MODEL_DIR = '/tensorflow_google/inception_model' 22 23
# 下載的訓練好的模型檔名 24 MODEL_FILE = 'tensorflow_inception_graph.pb' 25 26 # 將原始影象通過inception-v3模型計算得到的特徵向量儲存在檔案中,下面定義檔案存放地址 27 CACHE_DIR = '/tensorflow_google/bottleneck' 28 29 # 圖片資料資料夾,子檔案為類別 30 INPUT_DATA = '/tensorflow_google/flower_photos' 31 32 # 驗證的資料百分比 33 VALIDATION_PRECENTAGE = 10 34 # 測試的資料百分比
35 TEST_PRECENTAGE = 10 36 37 # 定義神經網路的引數 38 LEARNING_RATE = 0.01 39 STEPS = 4000 40 BATCH = 100 41 42 43 # 從資料資料夾中讀取所有的圖片列表並按訓練、驗證、測試資料分開 44 # testing_percentage和validation_percentage指定測試和驗證資料集的大小 45 def create_image_lists(testing_percentage, validation_percentage): 46 # 得到的圖片放到result字典中,key為類別名稱,value為類別下的各個圖片(也是字典) 47 result = {} 48 # 獲取當前目錄下所有的子目錄 49 sub_dirs = [x[0] for x in os.walk(INPUT_DATA)] 50 # sub_dirs中第一個目錄是當前目錄,即flower_photos,不用考慮 51 is_root_dir = True 52 for sub_dir in sub_dirs: 53 if is_root_dir: 54 is_root_dir = False 55 continue 56 57 # 獲取當前目錄下所有的有效圖片檔案 58 extensions = ['jpg', 'jpeg', 'JPG', 'JPEG'] 59 file_list = [] 60 # 獲取當前檔名 61 dir_name = os.path.basename(sub_dir) 62 for extension in extensions: 63 # 將分離的各部分組成一個路徑名,如/flower_photos/roses/*.JPEG 64 file_glob = os.path.join(INPUT_DATA, dir_name, '*.'+extension) 65 # glob.glob()返回的是所有路徑下的符合條件的檔名的列表 66 file_list.extend(glob.glob(file_glob)) 67 if not file_list: continue 68 69 # 通過目錄名獲取類別的名稱(全部小寫) 70 label_name = dir_name.lower() 71 # 初始化當前類別的訓練資料集、測試資料集和驗證資料集 72 training_images = [] 73 testing_images = [] 74 validation_images = [] 75 for file_name in file_list: 76 base_name = os.path.basename(file_name) #獲取當前檔名 77 # 隨機將資料分到訓練資料集、測試資料集以及驗證資料集 78 chance = np.random.randint(100) #隨機返回一個整數 79 if chance < validation_percentage: 80 validation_images.append(base_name) 81 elif chance < (testing_percentage + validation_percentage): 82 testing_images.append(base_name) 83 else: 84 training_images.append(base_name) 85 86 # 將當前類別的資料放入結果字典 87 result[label_name] = {'dir': dir_name, 'training': training_images, 88 'testing': testing_images, 'validation': validation_images} 89 return result 90 91 92 # 通過類別名稱、所屬資料集和圖片編號獲取一張圖片的地址 93 # image_lists為所有圖片資訊,image_dir給出根目錄,label_name為類別名稱,index為圖片編號,category指定圖片是在哪個訓練集 94 def get_image_path(image_lists, image_dir, label_name, index, category): 95 # 獲取給定類別中所有圖片的資訊 96 label_lists = image_lists[label_name] 97 # 根據所屬資料集的名稱獲取集合中的全部圖片資訊 98 category_list = label_lists[category] 99 mod_index = index % len(category_list) 100 # 獲取圖片的檔名 101 base_name = category_list[mod_index] 102 sub_dir = label_lists['dir'] 103 # 最終的地址為資料根目錄的地址加上類別的資料夾加上圖片的名稱 104 full_path = os.path.join(image_dir, sub_dir, base_name) 105 return full_path 106 107 108 # 通過類別名稱、所屬資料集和圖片編號經過inception-v3處理之後的特徵向量檔案地址 109 def get_bottleneck_path(image_lists, label_name, index, category): 110 return get_image_path(image_lists, CACHE_DIR, label_name, index, category)+'.txt' 111 112 113 # 使用載入的訓練好的網路處理一張圖片,得到這個圖片的特徵向量 114 def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor): 115 # 將當前圖片作為輸入,計算瓶頸張量的值 116 # 這個張量的值就是這張圖片的新的特徵向量 117 bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data}) 118 # 經過卷積神經網路處理的結果是一個四維陣列,需要將這個結果壓縮成一個一維陣列 119 bottleneck_values = np.squeeze(bottleneck_values) #從陣列的形狀中刪除單維條目 120 return bottleneck_values 121 122 123 # 獲取一張圖片經過inception-v3模型處理之後的特徵向量 124 # 先尋找已經計算並且儲存的向量,若找不到則計算然後儲存到檔案 125 def get_or_create_bottleneck(sess, image_lists, label_name, index, category, 126 jpeg_data_tensor, bottleneck_tensor): 127 # 獲取一張圖片對應的特徵向量檔案路徑 128 label_lists = image_lists[label_name] 129 sub_dir = label_lists['dir'] 130 sub_dir_path = os.path.join(CACHE_DIR, sub_dir) 131 if not os.path.exists(sub_dir_path): 132 os.makedirs(sub_dir_path) #若不存在則建立 133 bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category) 134 135 # 如果這個特徵向量檔案不存在,則通過inception-v3計算,並存入檔案 136 if not os.path.exists(bottleneck_path): 137 # 獲取原始的圖片路徑 138 image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category) 139 # 獲取圖片內容,對圖片的讀取 140 image_data = gfile.FastGFile(image_path, 'rb').read() 141 # 通過inception-v3計算特徵向量 142 bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor) 143 # 將計算得到的特徵向量存入檔案,join()連線字串 144 bottleneck_string = ','.join(str(x) for x in bottleneck_values) 145 with open(bottleneck_path, 'w') as bottleneck_file: #開啟檔案並寫入 146 bottleneck_file.write(bottleneck_string) 147 else: 148 # 直接從檔案中獲取圖片相應的特徵向量 149 with open(bottleneck_path, 'r') as bottleneck_file: 150 bottleneck_string = bottleneck_file.read() 151 bottleneck_values = [float(x) for x in bottleneck_string.split(',')] 152 # 返回特徵向量 153 return bottleneck_values 154 155 156 # 隨機選取一個batch的圖片作為訓練資料 157 def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, 158 jpeg_data_tensor, bottleneck_tensor): 159 bottlenecks = [] 160 ground_truths = [] 161 for _ in range(how_many): 162 # 隨機一個類別和圖片的編號加入當前的訓練資料 163 label_index = random.randrange(n_classes) # 返回指定遞增基數集合中的一個隨機數,基數預設值為1,隨機類別號 164 label_name = list(image_lists.keys())[label_index] 165 image_index = random.randrange(65536) 166 bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, image_index, 167 category, jpeg_data_tensor, bottleneck_tensor) 168 ground_truth = np.zeros(n_classes, dtype=np.float32) 169 ground_truth[label_index] = 1.0 170 bottlenecks.append(bottleneck) 171 ground_truths.append(ground_truth) 172 173 return bottlenecks, ground_truths 174 175 176 # 獲取全部的測試資料,在最終測試的時候在所有測試資料上計算正確率 177 def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor): 178 bottlenecks = [] 179 ground_truths = [] 180 label_name_list = list(image_lists.keys()) 181 # 列舉所有類別和每個類別中的測試圖片 182 for label_index, label_name in enumerate(label_name_list): 183 category = 'testing' 184 for index, unused_base_name in enumerate(image_lists[label_name][category]): 185 # 通過inception-v3計算圖片對應的特徵向量,並將其加入最終資料的列表 186 bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category, 187 jpeg_data_tensor, bottleneck_tensor) 188 ground_truth = np.zeros(n_classes, dtype=np.float32) 189 ground_truth[label_index] = 1.0 190 bottlenecks.append(bottleneck) 191 ground_truths.append(ground_truth) 192 return bottlenecks, ground_truths 193 194 195 def main(_): 196 # 讀取所有圖片 197 image_lists = create_image_lists(TEST_PRECENTAGE, VALIDATION_PRECENTAGE) 198 # image_lists.keys()為dict_keys(['roses', 'sunflowers', 'daisy', 'dandelion', 'tulips']) 199 n_classes = len(image_lists.keys()) # 類別數 200 # 讀取已經訓練好的inception-v3模型,谷歌訓練好的模型儲存在了GraphDef Protocol Buffer中 201 # 裡面儲存了每一個節點取值的計算方法以及變數的取值 202 # 對模型的讀取,二進位制 203 with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f: 204 # 新建GraphDef檔案,用於臨時載入模型中的圖 205 graph_def = tf.GraphDef() 206 # 載入模型中的圖 207 graph_def.ParseFromString(f.read()) 208 # 載入讀取的inception模型,並返回資料輸出所對應的張量以及計算瓶頸層結果所對應的張量 209 # 從圖上讀取張量,同時把圖設為預設圖 210 # Tensor("import/pool_3/_reshape:0", shape=(1, 2048), dtype=float32) 211 # Tensor("import/DecodeJpeg/contents:0", shape=(), dtype=string) 212 bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def, return_elements=[BOTTLENECT_TENSOR_NAME, 213 JPEG_DATA_TENSOR_NAME]) 214 215 # 定義新的神經網路輸入,這個輸入就是新的圖片經過inception模型前向傳播達到瓶頸層的節點取值,None為了batch服務 216 bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECT_TENSOR_SIZE], 217 name='BottleneckInputPlaceholder') 218 # 定義新的標準答案 219 ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput') 220 221 # 定義一層全連線層來解決新的圖片分類問題 222 with tf.name_scope('final_training_ops'): 223 weights = tf.Variable(tf.truncated_normal([BOTTLENECT_TENSOR_SIZE, n_classes], stddev=0.001)) 224 biases = tf.Variable(tf.zeros([n_classes])) 225 logits = tf.matmul(bottleneck_input, weights) + biases 226 final_tensor = tf.nn.softmax(logits) 227 228 # 定義交叉熵損失函式 229 # tf.nn.softmax中dim預設為-1,即tf.nn.softmax會以最後一個維度作為一維向量計算softmax 230 cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input) 231 cross_entropy_mean = tf.reduce_mean(cross_entropy) 232 train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean) 233 234 # 計算正確率 235 with tf.name_scope('evaluation'): 236 correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1)) 237 # 平均錯誤率,cast將bool值轉成float 238 evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 239 240 with tf.Session() as sess: 241 init = tf.initialize_all_variables() 242 sess.run(init) 243 244 # 訓練過程 245 for i in range(STEPS): 246 # 每次獲取一個batch的訓練資料 247 train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks\ 248 (sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor) 249 sess.run(train_step, feed_dict={bottleneck_input: train_bottlenecks, 250 ground_truth_input: train_ground_truth}) 251 252 # 在驗證資料上測試正確率 253 if i % 100 == 0 or i+1 == STEPS: 254 validation_bottlenecks, validation_ground_truth = \ 255 get_random_cached_bottlenecks(sess, n_classes, image_lists, BATCH, 256 'validation', jpeg_data_tensor, bottleneck_tensor) 257 validation_accuracy = sess.run(evaluation_step, 258 feed_dict={bottleneck_input: validation_bottlenecks, 259 ground_truth_input: validation_ground_truth}) 260 print('Step %d :Validation accuracy on random sampled %d examples = %.1f%%' % 261 (i, BATCH, validation_accuracy*100)) 262 263 # 在最後的測試資料上測試正確率 264 test_bottlenecks, test_ground_truth = get_test_bottlenecks(sess, image_lists, n_classes, 265 jpeg_data_tensor, bottleneck_tensor) 266 test_accuracy = sess.run(evaluation_step, feed_dict={bottleneck_input: test_bottlenecks, 267 ground_truth_input: test_ground_truth}) 268 print('Final test accuracy = %.1f%%' % (test_accuracy*100)) 269 270 271 if __name__ == '__main__': 272 tf.app.run()
View Code