1. 程式人生 > >機器學習筆記(二十一):TensorFlow實戰十三(遷移學習)

機器學習筆記(二十一):TensorFlow實戰十三(遷移學習)

1 - 引言

越複雜的神經網路,需要的訓練集越大,ImageNet影象分類資料集有120萬標註圖片,所以才能將152層的ResNet的模型訓練到大約96.%的正確率。但是在真正的應用中,很難收集到如此多的標註資料。即使收集到也需要花費大量人力物力來標註。並且即使有了大量的資料集,要訓練一個複雜的卷積神經網路也需要幾天甚至幾周的時間,為了解決標註資料和訓練時間的問題,可以使用遷移學習

下面就讓我們來介紹遷移學習

2 - 使用TensorFlow實現遷移學習

一般來說,在數量量足夠的情況下,遷移學習的效果不如完全重新訓練,但是遷移學習所需要的訓練時間和訓練樣本數要遠遠小於訓練完整的模型。

資料集下載 :http://download.tensorflow.org/example_images/flower_photos.tgz
已訓練好的谷歌的Inception-v3模下載:https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip
解壓後放入相應的資料夾下

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import glob
import os.path
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile

# 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 = '/path/to/model'

# 下載的谷歌訓練好的Inception-v3模型檔名
MODEL_FILE = 'tensorflow_inception_graph.pb'

# 因為一個訓練資料會被使用多次,所以可以將原始影象通過Inception-v3模型計算得到的特徵向量儲存在檔案中,免去重複的計算。
# 下面的變數定義了這些檔案的存放地址。
CACHE_DIR = 'tmp/bottleneck/'

# 圖片資料資料夾。
# 在這個資料夾中每一個子資料夾代表一個需要區分的類別,每個子資料夾中存放了對應類別的圖片。
INPUT_DATA = '/path/to/flower_data'

# 驗證的資料百分比
VALIDATION_PERCENTAGE = 10
# 測試的資料百分比
TEST_PERCENTAGE = 10

# 定義神經網路的設定
LEARNING_RATE = 0.01
STEPS = 4000
BATCH = 100

# 這個函式從資料資料夾中讀取所有的圖片列表並按訓練、驗證、測試資料分開。
# testing_percentage和validation_percentage引數指定了測試資料集和驗證資料集的大小。
def create_image_lists(testing_percentage, validation_percentage):
    # 得到的所有圖片都存在result這個字典(dictionary)裡。
    # 這個字典的key為類別的名稱,value也是一個字典,字典裡儲存了所有的圖片名稱。
    result = {}
    # 獲取當前目錄下所有的子目錄
    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
    # 得到的第一個目錄是當前目錄,不需要考慮
    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:
            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


# 這個函式通過類別名稱、所屬資料集和圖片編號獲取一張圖片的地址。
# 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_bottlenect_path(image_lists, label_name, index, category):
    return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt';


# 這個函式使用載入的訓練好的Inception-v3模型處理一張圖片,得到這個圖片的特徵向量。
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_bottlenect_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()
        # print(len(image_data))
        # 由於輸入的圖片大小不一致,此處得到的image_data大小也不一致(已驗證),但卻都能通過載入的inception-v3模型生成一個2048的特徵向量。具體原理不詳。
        # 通過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


# 這個函式隨機獲取一個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)
        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_PERCENTAGE, VALIDATION_PERCENTAGE)
    n_classes = len(image_lists.keys())
    # 讀取已經訓練好的Inception-v3模型。
    # 谷歌訓練好的模型儲存在了GraphDef Protocol Buffer中,裡面儲存了每一個節點取值的計算方法以及變數的取值。
    # TensorFlow模型持久化的問題在第5章中有詳細的介紹。
    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) + biases
        final_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:
        tf.global_variables_initializer().run()
        startTime = time.time()
        # 訓練過程
        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))
        print("Time taken: %f" % (time.time() - startTime))

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

Step 0: Validation accuracy on random sampled 100 examples = 27.0%
Step 100: Validation accuracy on random sampled 100 examples = 78.0%
Step 200: Validation accuracy on random sampled 100 examples = 88.0%
·
·
·
Step 3800: Validation accuracy on random sampled 100 examples = 94.0%
Step 3900: Validation accuracy on random sampled 100 examples = 100.0%
Step 3999: Validation accuracy on random sampled 100 examples = 96.0%
Final test accuracy = 94.3%
Time taken: 713.256381

Inception-v3模型在單機上訓練到78%的正確率需要將近半年的時間
使用遷移學習我們只花十多分鐘就將新的資料在Inception-v3模型上訓練完畢,節省了我們很多時間。並且大大降低了cpu的利用率(平常的訓練cpu利用率高達90%以上)
在這裡插入圖片描述