迁移学习
迁移学习就是将一个问题上训练好的模型通过简单的调整使其适用于一个新的问题。
由于大型网络很复杂,训练一个复杂的卷积神经网络需要非常多的标注数据,而且需要比较长的时间。迁移学习就是为了解决大量标注数据和训练时间问题的一种变通处理方式。
在数据量足够的情况下,迁移学习的效果不如完全重新训练。但是迁移学习所需要的训练时间和训练样本数要远远小于训练完整的模型。而且可以得到不错的准确率。
下面利用ImageNet 数据集上训练好的Inception-v3 模型来解决一个新的图像分类问题。
完整代码
数据处理代码
import glob
import os.path
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
# 原始输入数据的目录,这个目录下有5个子目录,每个子目录底下保存这属于该
# 类别的所有图片。
#下载链接:http://download.tensorflow.org/example_images/flower_photos.tgz
INPUT_DATA = '../../datasets/flower_photos'
# 输出文件地址。我们将整理后的图片数据通过numpy的格式保存。
OUTPUT_FILE = '../../datasets/flower_processed_data.npy'
# 测试数据和验证数据比例。
VALIDATION_PERCENTAGE = 10
TEST_PERCENTAGE = 10
# 读取数据并将数据分割成训练数据、验证数据和测试数据。
def create_image_lists(sess, testing_percentage, validation_percentage):
'''
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
在Unix,Windows中有效。
'''
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:
print ("sub_dir:", sub_dir)
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:
#os.path.join就是获取INPUT_DATA目录,并组合成新目录
file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension)
#使用glob.glob获得文件路径
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
# 将训练数据随机打乱以获得更好的训练效果。
'''
get_state():可理解为设定状态,记录下数组被打乱的操作
set_state():接收get_state()返回的值,并进行同样的操作
一般结合random.shuffle()函数使用
将实例与标签两个数组同时打乱,但打乱后,实例与标签任然是一一对应的关系
'''
state = np.random.get_state()
np.random.shuffle(training_images)
np.random.set_state(state)
np.random.shuffle(training_labels)
return np.asarray([training_images, training_labels,
validation_images, validation_labels,
testing_images, testing_labels])
with tf.Session() as sess:
processed_data = create_image_lists(sess, TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
# 通过numpy格式保存处理后的数据。
np.save(OUTPUT_FILE, processed_data)
训练代码
import glob
import os.path
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
import tensorflow.contrib.slim as slim
# 加载通过TensorFlow-Slim定义好的inception_v3模型。
import tensorflow.contrib.slim.python.slim.nets.inception_v3 as inception_v3
# 处理好之后的数据文件。
INPUT_DATA = '../../datasets/flower_processed_data.npy'
# 保存训练好的模型的路径。
TRAIN_FILE = 'train_dir/model'
# 在运行时需要先自行从Google下载inception_v3.ckpt文件。
# 下载地址:http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz
CKPT_FILE = '../../datasets/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():
# 加载预处理好的数据。
processed_data = np.load(INPUT_DATA)
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)))
# 定义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模型。因为谷歌给出的只有模型参数取值,所以这里
# 需要在这个代码中定义inception-v3的模型结构。虽然理论上需要区分训练和
# 测试中使用到的模型,也就是说在测试时应该使用is_training=False,但是
# 因为预先训练好的inception-v3模型中使用的batch normalization参数与
# 新的数据会有出入,所以这里直接使用同一个模型来做测试。
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
1.主要用于进行不同样本的loss计算
2.默认weights=1,等价于tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits)
3.weights为标量w时,等价于w*tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits))
4.weights为向量时,算出的每个loss需要乘以对应样本权重,再求均值
logits = np.array([[1, 2, 7],
[3, 5, 2],
[6, 1, 3],
[8, 2, 0],
[3, 6, 1]], dtype=np.float32)
#labels是[2,1,0,0,1]的ont-hot编码形式
labels = np.array([[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[1, 0, 0],
[0, 1, 0]], dtype=np.float32)
cross1 = tf.nn.softmax_cross_entropy_with_logits(labels=labels,logits=logits)
cross2 = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)
cross3 = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits,weights=0.2)
print sess.run(cross1) #[ 0.00917445 0.16984604 0.05498521 0.00281022 0.05498521]
print sess.run(cross2) #0.0583602
print sess.run(tf.reduce_mean(cross1)) #0.0583602
print sess.run(cross3) #0.011672
print sess.run(0.2*tf.reduce_mean(cross1)) #0.011672
'''
# 定义损失函数和训练过程。注意在模型定义的时候己经将正则化损失加入损失集合了。
tf.losses.softmax_cross_entropy(
tf.one_hot(labels, N_CLASSES), logits, weights=1.0)
'''
one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
Returns a one-hot tensor.
indices表示输入的多个数值,通常是矩阵形式;depth表示输出的尺寸。
indices = 0 对应的输出是[1, 0 … 0, 0], indices = 1 对应的输出是[0, 1 … 0, 0], 依次类推,最大可能值的输出是[0, 0 … 0, 1]。
'''
#定义训练过程。这里minimize 的过程中指定了需要优化的变量集合。
total_loss = tf.losses.get_total_loss()
train_step = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(total_loss)
'''
tf.argmax就是返回最大的那个数值所在的下标
第一个参数是矩阵,第二个参数是0或者1。0表示的是按列比较返回最大值的索引,1表示按行比较返回最大值的索引
'''
# 计算正确率。
with tf.name_scope('evaluation'):
correct_prediction = tf.equal(tf.argmax(logits, 1), labels)
print('correct_prediction: %s' % correct_prediction)
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:
# 初始化没有加载进来的变量。注意这个过程一定要在模型加载之前,否则初始化过程会将已经加就好的变量新赋值。
init = tf.global_variables_initializer()
sess.run(init)
# 加载谷歌已经训练好的模型。
print('Loading tuned variables from %s' % CKPT_FILE)
load_fn(sess)
start = 0
end = BATCH
for i in range(STEPS):
#运行训练过程,这里不会更新全部的参数,只会更新指定的部分参数。
_, loss = sess.run([train_step, total_loss], feed_dict={
images: training_images[start:end],
labels: training_labels[start:end]})
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))
start = end
if start == n_training_example:
start = 0
end = start + BATCH
if end > n_training_example:
end = n_training_example
# 在最后的测试数据上测试正确率。
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()