卷积神经网络迁移学习
簡單的講就是將一個在數據集上訓練好的卷積神經網絡模型通過簡單的調整快速移動到另外一個數據集上。
隨著模型的層數及模型的復雜度的增加,模型的錯誤率也隨著降低。但是要訓練一個復雜的卷積神經網絡需要非常多的標注信息,同時也需要幾天甚至幾周的時間,為了解決標注數據和訓練時間的問題,就可以使用遷移學習。
下面的代碼就是介紹如何利用ImageNet數據集訓練好的inception-v3模型來解決一個新的圖像分類問題。其中有論文依據表明可以保留訓練好的inception-v3模型中所有卷積層的參數,只替換最后一層全連接層。在最后這一層全連接層之前的網絡稱為瓶頸層。
原理:在訓練好的inception-v3模型中,因為將瓶頸層的輸出再通過一個單層的全連接層神經網絡可以很好的區分1000種類別的圖像,所以可以認為瓶頸層輸出的節點向量可以被作為任何圖像的一個更具有表達能力的特征向量。于是在新的數據集上可以直接利用這個訓練好的神經網絡對圖像進行特征提取,然后將提取得到的特征向量作為輸入來訓練一個全新的單層全連接神經網絡處理新的分類問題。
一般來說在數據量足夠的情況下,遷移學習的效果不如完全重新訓練。但是遷移學習所需要的訓練時間和訓練樣本要遠遠小于訓練完整的模型。
這其中說到inception-v3模型,其實它是和LeNet-5結構完全不同的卷積神經網絡。在LeNet-5模型中,不同卷積層通過串聯的方式連接在一起,而inception-v3模型中的inception結構是將不同的卷積層通過并聯的方式結合在一起。
具體細節請參考別處。
下面是一個完整的Tensorflow程序來實現遷移學習:
# coding: utf-8# In[1]:import glob import os.path import random import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile# #### 1. 模型和樣本路徑的設置# In[ ]:# inception-v3模型瓶頸層的節點個數 BOTTLENECK_TENSOR_SIZE = 2048 # inception-v3模型中代表瓶頸層結果的張量名稱。在谷歌提供的inception-v3模型中,這個張量名稱就是:'pool_3/_reshape:0' # 在訓練模型時可以通過tensor.name來獲取張量的名稱。 BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' # 圖像輸入張量所對應的名稱 JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'# 下載訓練好的inception-v3模型文件目錄 MODEL_DIR = r'datasets\inception_dec_2015' # 下載訓練好的inception-v3模型文件名 MODEL_FILE= 'tensorflow_inception_graph.pb' # 因為一個訓練數據會被使用多次,所以可以將原始圖像通過inception-v3模型計算得到的特征向量保存在文件種,免去重復的 # 計算。下面的變量定義了這些文件保存的路徑 CACHE_DIR = r'datasets\bottleneck' # 圖片文件夾,每個子文件夾中存放了對應類別的圖片 INPUT_DATA = r'datasets\flower_photos'#驗證數據的百分比 VALIDATION_PERCENTAGE = 10 # 測試數據的百分比 TEST_PERCENTAGE = 10# #### 2. 神經網絡參數的設置# In[ ]:LEARNING_RATE = 0.01 STEPS = 4000 BATCH = 100# #### 3. 把樣本中所有的圖片列表并按訓練、驗證、測試數據分開# In[ ]:# 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)] # 獲取當前目錄下的所有子目錄# 得到的第一個目錄是當前目錄,不需要考慮is_root_dir = Truefor sub_dir in sub_dirs:if is_root_dir:is_root_dir = Falsecontinue# 獲取當前目錄下所有的有效圖片文件extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']file_list = []dir_name = os.path.basename(sub_dir)for extension in extensions:file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension)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# #### 4. 定義函數通過類別名稱、所屬數據集和圖片編號獲取一張圖片的地址。# In[ ]:# 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# #### 5. 定義函數獲取Inception-v3模型處理之后的特征向量的文件地址。# In[ ]:def get_bottleneck_path(image_lists, label_name, index, category):return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt'# #### 6. 定義函數使用加載的訓練好的Inception-v3模型處理一張圖片,得到這個圖片的特征向量。# In[ ]: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# #### 7. 定義函數會先試圖尋找已經計算且保存下來的特征向量,如果找不到則先計算這個特征向量,然后保存到文件。# In[ ]:# 該函數獲取一張圖片經過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)# 將計算得到的特征向量存入文件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# #### 8. 這個函數隨機獲取一個batch的圖片作為訓練數據。# In[ ]: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)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.0bottlenecks.append(bottleneck)ground_truths.append(ground_truth)return bottlenecks, ground_truths# #### 9. 這個函數獲取全部的測試數據,并計算正確率。# In[ ]: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.0bottlenecks.append(bottleneck)ground_truths.append(ground_truth)return bottlenecks, ground_truths# #### 10. 定義主函數。# In[ ]:def main():# 讀取所有的圖片image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)n_classes = len(image_lists.keys())# 讀取已經訓練好的Inception-v3模型。谷歌訓練好的模型保存在了GraphDef Protocol Buffer中。里面保存了每一個節點取值# 的計算方法以及變量的取值。with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:graph_def = tf.GraphDef()graph_def.ParseFromString(f.read())# 加載讀取的inception-v3模型,并返回數據輸入對應的張量以及計算瓶頸層對應的張量。 bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])# 定義新的神經網絡輸入。# 這個輸入就是新的圖片通過inception-v3模型前向傳播到達瓶頸層時的節點取值。也是一種特征提取bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE],name='BottleneckInputPlaceholder')# 定義新的標準答案輸入ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')# 定義一層全鏈接層來解決新的圖片分類問題。因為訓練好的inception-v3模型已經將原始的圖片抽象成了更加容易# 分類的特征向量了。所以不需要再訓練那么復雜的神經網絡來完成這個新的分類任務了。with tf.name_scope('final_training_ops'):weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))biases = tf.Variable(tf.zeros([n_classes]))logits = tf.matmul(bottleneck_input, weights) + biasesfinal_tensor = tf.nn.softmax(logits)# 定義交叉熵損失函數。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))evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))with tf.Session() as sess:init = tf.global_variables_initializer()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__':main()運行過程有點慢,大概需要30分鐘左右。過程中會生成一個bottleneck的文件夾,里面存放的是原始圖像通過inception-v3模型計算得到的特征向量。
運行結果:
Step 0: Validation accuracy on random sampled 100 examples = 59.0% Step 100: Validation accuracy on random sampled 100 examples = 84.0% Step 200: Validation accuracy on random sampled 100 examples = 80.0% Step 300: Validation accuracy on random sampled 100 examples = 91.0% Step 400: Validation accuracy on random sampled 100 examples = 86.0% Step 500: Validation accuracy on random sampled 100 examples = 88.0% Step 600: Validation accuracy on random sampled 100 examples = 92.0% Step 700: Validation accuracy on random sampled 100 examples = 89.0% Step 800: Validation accuracy on random sampled 100 examples = 92.0% Step 900: Validation accuracy on random sampled 100 examples = 85.0% Step 1000: Validation accuracy on random sampled 100 examples = 90.0% Step 1100: Validation accuracy on random sampled 100 examples = 92.0% Step 1200: Validation accuracy on random sampled 100 examples = 93.0% Step 1300: Validation accuracy on random sampled 100 examples = 92.0% Step 1400: Validation accuracy on random sampled 100 examples = 92.0% Step 1500: Validation accuracy on random sampled 100 examples = 91.0% Step 1600: Validation accuracy on random sampled 100 examples = 94.0% Step 1700: Validation accuracy on random sampled 100 examples = 91.0% Step 1800: Validation accuracy on random sampled 100 examples = 94.0% Step 1900: Validation accuracy on random sampled 100 examples = 91.0% Step 2000: Validation accuracy on random sampled 100 examples = 90.0% Step 2100: Validation accuracy on random sampled 100 examples = 94.0% Step 2200: Validation accuracy on random sampled 100 examples = 94.0% Step 2300: Validation accuracy on random sampled 100 examples = 95.0% Step 2400: Validation accuracy on random sampled 100 examples = 93.0% Step 2500: Validation accuracy on random sampled 100 examples = 93.0% Step 2600: Validation accuracy on random sampled 100 examples = 93.0% Step 2700: Validation accuracy on random sampled 100 examples = 95.0% Step 2800: Validation accuracy on random sampled 100 examples = 87.0% Step 2900: Validation accuracy on random sampled 100 examples = 96.0% Step 3000: Validation accuracy on random sampled 100 examples = 87.0% Step 3100: Validation accuracy on random sampled 100 examples = 93.0% Step 3200: Validation accuracy on random sampled 100 examples = 93.0% Step 3300: Validation accuracy on random sampled 100 examples = 92.0% Step 3400: Validation accuracy on random sampled 100 examples = 96.0% Step 3500: Validation accuracy on random sampled 100 examples = 97.0% Step 3600: Validation accuracy on random sampled 100 examples = 94.0% Step 3700: Validation accuracy on random sampled 100 examples = 94.0% Step 3800: Validation accuracy on random sampled 100 examples = 97.0% Step 3900: Validation accuracy on random sampled 100 examples = 93.0% Step 3999: Validation accuracy on random sampled 100 examples = 95.0% Final test accuracy = 94.6%模型在新的數據集上能達到不錯的分數效果。
初次接觸遷移學習,感覺功能很強大,以后再深入學習。
參考:《Tensorflow實戰Google深度學習框架》
總結
以上是生活随笔為你收集整理的卷积神经网络迁移学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tas(说一说tas的简介)
- 下一篇: 聚焦和增强卷积神经网络