深度学习手记(九)之Inception-v3实现迁移学习

  在训练神经网络模型时,往往需要很多的标注数据以支持模型的准确性。但是,在真实的应用中,很难收集到如此多的标注数据,即使可以收集到,也需要花费大量的人力物力。而且即使有海量的数据用于训练,也需要很多的时间。因此为了解决标注数据和训练时间的问题,可以考虑使用迁移学习。
  所谓的迁移学习,就是将一个问题上训练好的模型通过简单的调整使其适用于一个新的问题,即只改变训练好的模型最后一层全连接层,而保留之前卷积层的所有参数,并使用它们训练一个新的单层全连接神经网络处理新的分类问题。本篇文章将介绍如何使用Inception-v3模型来解决一个新的图像分类问题。
下面将具体实现Inception-v3模型的迁移学习,本次案例使用的是TensorFlow上面的鲜花数据集解压之后,文件夹包含5个文件即5种不同的花,一个文件夹中大约六八百张图像,每一张图像都是RGB色彩模式的,大小也不相同。因此,首先要对此数据集预处理,保证能正确的被模型读入。

**

1. 数据预处理

**

import glob
import os.path
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.python.platform import gfile

# 原始输入数据的目录
INPUT_DATA = 'E:/database/flower_photos'
# 输出文件地址,将整理后的图片数据使用numpy的格式保存
OUTPUT_PATH = 'flower_processed_data.csv'

# 测试数据与验证数据的比例
VALIDATION_PERCENTAGE = 10
TEST_PERCENTAGE = 10

# 读取数据并将数据分割成训练数据、验证数据和测试数据。
def create_image_lists(sess, testing_percentage, validation_percentage):
    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
    is_root_dir = True

    # 初始化各个数据集。
    training_images = []
    training_labels = []
    testing_images = []
    testing_labels = []
    validation_images = []
    validation_labels = []
    current_label = 0

    # 读取所有的子目录。
    for sub_dir in sub_dirs:
        if is_root_dir:
            is_root_dir = False
            continue

        # 获取一个子目录中所有的图片文件。
        file_list = []
        dir_name = os.path.basename(sub_dir)
        file_glob = os.path.join(INPUT_DATA, dir_name, '*.jpg')
        file_list.extend(glob.glob(file_glob))
        if not file_list: continue
        print("processing:", dir_name)

        i = 0
        # 处理图片数据。
        for file_name in file_list:
            i += 1
            # 读取并解析图片,将每张图片转化为299*299以方便inception-v3模型来处理。
            image_raw_data = gfile.FastGFile(file_name, 'rb').read()
            image = tf.image.decode_jpeg(image_raw_data)
            if image.dtype != tf.float32:
                image = tf.image.convert_image_dtype(image, dtype=tf.float32)
            image = tf.image.resize_images(image, [299, 299])
            image_value = sess.run(image)

            # 随机划分数据聚。
            chance = np.random.randint(100)
            if chance < validation_percentage:
                validation_images.append(image_value)
                validation_labels.append(current_label)
            elif chance < (testing_percentage + validation_percentage):
                testing_images.append(image_value)
                testing_labels.append(current_label)
            else:
                training_images.append(image_value)
                training_labels.append(current_label)
            if i % 200 == 0:
                print(i, "images processed.")
        current_label += 1

    # 将训练数据随机打乱以获得更好的训练效果。
    state = np.random.get_state()
    np.random.shuffle(training_images)
    np.random.set_state(state)
    np.random.shuffle(training_labels)
    process_data = np.asarray([training_images, training_labels,
                               validation_images, validation_labels,
                               testing_images, testing_labels])
    # np.save(OUTPUT_FILE, process_data)
    return process_data

得到npy格式的预处理文件之后,就可以构建模型了。Inception-v3模型可以直接在TensorFlow上面下载(http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz)。

**

2. 训练、测试过程

**

import glob
import os.path
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.platform import gfile
# 加载通过TensorFlow-slim定义好的inception-v3模型
import tensorflow.contrib.slim.python.slim.nets.inception_v3 as inception_v3
# 保存训练好的模型的路径。
# TRAIN_FILE = 'train_dir/model'
# 谷歌提供的训练好的。
CKPT_FILE = 'inception_v3.ckpt'
# 必要的参数
LEARNING_RATE = 0.0001
STEPS = 300
BATCH = 32
N_CLASSES = 5
# 不需要从谷歌训练好的模型中加载的参数。
CHECKPOINT_EXCLUDE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogits'
# 需要训练的网络层参数明层,在fine-tuning的过程中就是最后的全联接层。
TRAINABLE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogit'

# 获取所有需要从谷歌训练好的模型
def get_tuned_variables():
    exclusions = [scope.strip() for scope in CHECKPOINT_EXCLUDE_SCOPES.split(',')]

    variables_to_restore = []
    # 枚举inception-v3模型中所有的参数,然后判断是否需要从加载列表中移除。
    for var in slim.get_model_variables():
        excluded = False
        for exclusion in exclusions:
            if var.op.name.startswith(exclusion):
                excluded = True
                break
        if not excluded:
            variables_to_restore.append(var)
    return variables_to_restore
 # 获取所有需要训练的变量列表
 def get_trainable_variables():
    scopes = [scope.strip() for scope in TRAINABLE_SCOPES.split(',')]
    variables_to_train = []

    # 枚举所有需要训练的参数前缀,并通过这些前缀找到所有需要训练的参数。
    for scope in scopes:
        variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
        variables_to_train.extend(variables)
    return variables_to_train

# 训练及测试过程
def main():
    # 定义inception-v3的输入,images为输入图片,labels为每一张图片对应的标签。
    images = tf.placeholder(tf.float32, [None, 299, 299, 3], name='input_images')
    labels = tf.placeholder(tf.int64, [None], name='labels')

    # 定义inception-v3模型。
    with slim.arg_scope(inception_v3.inception_v3_arg_scope()):
        logits, _ = inception_v3.inception_v3(
            images, num_classes=N_CLASSES, is_training=True)

    # trainable_variables = get_trainable_variables()
    # 定义损失函数和训练过程。
    tf.losses.softmax_cross_entropy(
        tf.one_hot(labels, N_CLASSES), logits, weights=1.0)
    total_loss = tf.losses.get_total_loss()
    train_step = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(total_loss)

    # 计算正确率。
    with tf.name_scope('evaluation'):
        correct_prediction = tf.equal(tf.argmax(logits, 1), labels)
        evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # 定义加载Google训练好的Inception-v3模型的Saver。
    load_fn = slim.assign_from_checkpoint_fn(
        CKPT_FILE,
        get_tuned_variables(),
        ignore_missing_vars=True)

    # 定义保存新模型的Saver。
    # saver = tf.train.Saver()
    with tf.Session() as sess:
        # 加载预处理好的数据。
        processed_data = create_image_lists(sess, TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
        training_images = processed_data[0]
        n_training_example = len(training_images)
        training_labels = processed_data[1]

        validation_images = processed_data[2]
        validation_labels = processed_data[3]

        testing_images = processed_data[4]
        testing_labels = processed_data[5]
        print("%d training examples, %d validation examples and %d testing examples." % (
            n_training_example, len(validation_labels), len(testing_labels)))
        # 初始化没有加载进来的变量。
        init = tf.global_variables_initializer()
        sess.run(init)

        # 加载谷歌已经训练好的模型。
        print('Loading tuned variables from %s' % CKPT_FILE)
        load_fn(sess)
        for i in range(STEPS):
            for batch_index in range(int(n_training_example / BATCH)):
                _, loss = sess.run([train_step, total_loss], feed_dict={
                    images: training_images[batch_index * BATCH : (batch_index + 1) * BATCH],
                    labels: training_labels[batch_index * BATCH : (batch_index + 1) * BATCH]})

                if i % 30 == 0 or i + 1 == STEPS:
                    # saver.save(sess, TRAIN_FILE, global_step=i)
                    validation_accuracy = sess.run(evaluation_step, feed_dict={
                        images: validation_images, labels: validation_labels})
                    print('Step %d: Training loss is %.1f Validation accuracy = %.1f%%' % (
                        i, loss, validation_accuracy * 100.0))

        # 在最后的测试数据上测试正确率。
        test_accuracy = sess.run(evaluation_step, feed_dict={
            images: testing_images, labels: testing_labels})
        print('Final test accuracy = %.1f%%' % (test_accuracy * 100))


if __name__ == '__main__':
    main()

  最终在测试集上的准确性为91.9%,可以看出模型在新的数据集上也很快能够收敛,并达到还不错的分类效果。具体源代码请参照《TensorFlow实战Google深度学习框架》第六章。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值