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'
# 谷歌提供的训练好的模型文件地址。因为GitHub无法保存大于100M的文件,所以
# 在运行时需要先自行从Google下载inception_v3.ckpt文件。
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(
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:
# 初始化没有加载进来的变量。
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))

吴裕雄--天生自然python Google深度学习框架:Tensorflow实现迁移学习的更多相关文章

  1. 吴裕雄--天生自然python Google深度学习框架:经典卷积神经网络模型

    import tensorflow as tf INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE_SIZE = 28 NUM_CHANNELS = 1 NUM_LABEL ...

  2. 吴裕雄--天生自然python Google深度学习框架:图像识别与卷积神经网络

  3. 吴裕雄--天生自然python Google深度学习框架:MNIST数字识别问题

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  4. 吴裕雄--天生自然python Google深度学习框架:深度学习与深层神经网络

  5. 吴裕雄--天生自然python Google深度学习框架:TensorFlow实现神经网络

    http://playground.tensorflow.org/

  6. 吴裕雄--天生自然python Google深度学习框架:Tensorflow基础应用

    import tensorflow as tf a = tf.constant([1.0, 2.0], name="a") b = tf.constant([2.0, 3.0], ...

  7. 吴裕雄--天生自然python Google深度学习框架:人工智能、深度学习与机器学习相互关系介绍

  8. 吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:Bellman函数、贪心算法与增强性学习网络开发实践

    !pip install gym import random import numpy as np import matplotlib.pyplot as plt from keras.layers ...

  9. 吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:使用TensorFlow和Keras开发高级自然语言处理系统——LSTM网络原理以及使用LSTM实现人机问答系统

    !mkdir '/content/gdrive/My Drive/conversation' ''' 将文本句子分解成单词,并构建词库 ''' path = '/content/gdrive/My D ...

随机推荐

  1. Kmeans应用

    1.思路 应用Kmeans聚类时,需要首先确定k值,如果k是未知的,需要先确定簇的数量.其方法可以使用拐点法.轮廓系数法(k>=2).间隔统计量法.若k是已知的,可以直接调用sklearn子模块 ...

  2. Day1-T3

    原题目 Describe:两个限制条件,求第三属性的最大和 code: #pragma GCC optimize(2) #include<bits/stdc++.h> using name ...

  3. exit(0)与exit(1)

    exit(0):正常运行程序并退出程序: exit(1):非正常运行导致退出程序: return():返回函数,若在主函数中,则会退出函数并返回一值. 详细说: 1. return返回函数值,是关键字 ...

  4. echars的使用

    1.首先引入echars的js文件 该文件可从echars官网下载 在某些图表中可能会引用ecStat.js文件 如线性回归散点图 我们直接下载引用即可 <head> <title& ...

  5. Condition接口及其主要实现类ConditionObject源码浅析

    1.引子 任意一个Java对象,都拥有一组监视器方法(定义在java.lang.Object上),主要包括wait().wait(long timeout).notify()以及notifyAll() ...

  6. soupui--替换整个case的url

    添加新的URL 随便进入一个case的[REST]step,添加新的url 更换URL 添加完之后双击想要更换url的case,在弹出的窗口中点击URL按钮 在弹出的set endpoint窗口中选择 ...

  7. 百度网盘下载神器 PanDownload v2.0.9(破解版、不限速)

    一直用这个软件来下载百度网盘的东西,不限速,贼爽.  链接:https://pan.baidu.com/s/1UjF47YWd2v9x52c5sjhutQ 提取码:v9pe 也可以直接到官网下载:ht ...

  8. MySQL硬核干货:从磁盘读取数据页到缓冲池时,免费链表有什么用?

    1.数据库启动的时候,是如何初始化Buffer Pool的? 现在我们已经搞明白一件事儿了,那就是数据库的Buffer Pool到底长成个什么样,大家想必都是理解了 其实说白了,里面就是会包含很多个缓 ...

  9. CocoaPods为多个target添加依赖库/Podfile的配置

    Podfile的相关配置,请看官方文档http://guides.cocoapods.org/syntax/podfile.html 1)多个target公用相同库,还可以添加额外的不同第三方库 编辑 ...

  10. INNER JOIN & OUTER JOIN

    INNER JOIN & OUTER JOIN 参考:sql