# -*- coding: utf-8 -*-

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 import tensorflow.contrib.slim.python.slim.nets.inception_v3 as inception_v3 # 处理好之后的数据文件。
INPUT_DATA = 'E:\\flower_processed_data\\flower_processed_data.npy'
# 保存训练好的模型的路径。这里我们可以将使用新数据训练得到的完整模型保存
# 下来,如果计算资源充足,我们还可以在训练完最后的全联接层之后再训练所有
# 网络层,这样可以使得新模型更加贴近新数据。
TRAIN_FILE = 'E:\\train_dir7\\model'
# 谷歌提供的训练好的模型文件地址。
CKPT_FILE = 'E:\\inception_v3\\inception_v3.ckpt' # 定义训练中使用的参数。
LEARNING_RATE = 0.002
STEPS = 3000
BATCH = 32
N_CLASSES = 5 # 不需要从谷歌训练好的模型中加载的参数。这里就是最后的全联接层,因为在
# 新的问题中我们要重新训练这一层中的参数。这里给出的是参数的前缀。
CHECKPOINT_EXCLUDE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogits'
# 需要训练的网络层参数明层,在fine-tuning的过程中就是最后的全联接层。
# 这里给出的是参数的前缀。
TRAINABLE_SCOPES='InceptionV3/Logits,InceptionV3/AuxLogits' # 获取所有需要从谷歌训练好的模型中加载的参数。
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的模型结构。因为模型
# 中使用到了dropout,所以需要定一个训练时使用的模型,一个测试时
# 使用的模型。
with slim.arg_scope(inception_v3.inception_v3_arg_scope()):
logits, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES)
logits1, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES, is_training=False, reuse=True)
logits2, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES, reuse=True)
trainable_variables = get_trainable_variables()
tf.losses.softmax_cross_entropy(tf.one_hot(labels, N_CLASSES), logits, weights=1.0)
train_step = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(tf.losses.get_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)) correct_prediction1 = tf.equal(tf.argmax(logits1, 1), labels)
evaluation_step1 = tf.reduce_mean(tf.cast(correct_prediction1, tf.float32)) correct_prediction2 = tf.equal(tf.argmax(logits2, 1), labels)
evaluation_step2 = tf.reduce_mean(tf.cast(correct_prediction2, tf.float32)) load_fn = slim.assign_from_checkpoint_fn(CKPT_FILE,get_tuned_variables(),ignore_missing_vars=True) 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):
sess.run(train_step, 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,evaluation_step1,evaluation_step2], feed_dict={
images: validation_images, labels: validation_labels})
print('Step %d: Validation accuracy = %.1f%%' % (
i, validation_accuracy[0] * 100.0))
print(validation_accuracy)
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()

吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(4)的更多相关文章

  1. 吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(3)

    import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platfor ...

  2. 吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(2)

    import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platfor ...

  3. 吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(1)

    import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platfor ...

  4. 吴裕雄 python 神经网络——TensorFlow 花瓣识别2

    import glob import os.path import numpy as np import tensorflow as tf from tensorflow.python.platfor ...

  5. 吴裕雄 python 神经网络——TensorFlow训练神经网络:花瓣识别

    import os import glob import os.path import numpy as np import tensorflow as tf from tensorflow.pyth ...

  6. 吴裕雄 python 神经网络——TensorFlow 循环神经网络处理MNIST手写数字数据集

    #加载TF并导入数据集 import tensorflow as tf from tensorflow.contrib import rnn from tensorflow.examples.tuto ...

  7. 吴裕雄 python 神经网络TensorFlow实现LeNet模型处理手写数字识别MNIST数据集

    import tensorflow as tf tf.reset_default_graph() # 配置神经网络的参数 INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE ...

  8. 吴裕雄 PYTHON 神经网络——TENSORFLOW 无监督学习处理MNIST手写数字数据集

    # 导入模块 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 加载数据 from tensor ...

  9. 吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

    import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_dat ...

随机推荐

  1. 杭电ACM 1713 相遇周期

    相遇周期 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  2. JS实现点击table中任意元素选中

    上项目开发,忙的焦头烂额,博客也没咋更新了. 昨天老师提了个需求,简单的小例子,选择tr中任一行选中tr,觉得很有意思,记录一下: 上代码 <!DOCTYPE html> <html ...

  3. 云原生学习笔记(3)——Kubernetes基本概念

    学习地址:https://developer.aliyun.com/lesson_1651_13078?spm=5176.270689.1397405.6.716ef5f8Q9z1z3#_13078 ...

  4. 【音乐欣赏】《Abnormalize》 - 凛として時雨

    曲名:Abnormalize 作者:凛として時雨 [00:00.96]誰にも見せられないもの [00:06.44]頭の中溢れて [00:11.96]間違いさえも無い世界へ [00:17.16]迷い込ん ...

  5. 使用VS2015调试Qt5.9.5源码

    调试的前提 1.Qt5.9.5源码. 2.Qt5.9.5对应VS2015版本的pdb文件. 前提1在安装Qt时勾选源代码选项即可,这样安装后的Qt目录会多出一个“Src”的目录,里面就是Qt的源码. ...

  6. Java compareTo的用法

    compareTo() 方法用于将 Number 对象与方法的参数进行比较.可用于比较 Byte, Long, Integer等. 该方法用于两个相同数据类型的比较,两个不同类型的数据不能用此方法来比 ...

  7. js 实现文字转音频播放

    var msg = new SpeechSynthesisUtterance("hello World"); console.log(msg); window.speechSynt ...

  8. concat merge

    # concat import numpy as np import pandas as pd from pandas import Series,DataFrame df1 = DataFrame( ...

  9. [洛谷P4463] calc (生成函数)

    首先注意到题目中 \(a\) 数组是有序的,那我们只用算有序的方案乘上 \(n!\) 即可. 而此时的答案显然 \[Ans=[x^n](1+x)(1+2x)\dots (1+Ax)=\prod_{i= ...

  10. MySQL存储引擎优化

    如何在两种存储引擎中进行选择? ① 是否有事务操作?有,InnoDB. ②是否存储并发修改?有,InnoDB. ③是否追求快速查询,且数据修改较少?是,MyISAM. ④是否使用全文索引?如果不引用第 ...