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# 因为slim.nets包在 tensorflow 1.3 中有一些问题,所以这里为了方便
# 我们将slim.nets.inception_v3中的代码拷贝到了同一个文件夹下。
# import inception_v3# 加载通过TensorFlow-Slim定义好的inception_v3模型。
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_dir\\model'
# 谷歌提供的训练好的模型文件地址。
CKPT_FILE = 'E:\\inception_v3\\inception_v3.ckpt'# 定义训练中使用的参数。
LEARNING_RATE = 0.01
STEPS = 5000
BATCH = 128
N_CLASSES = 5# 不需要从谷歌训练好的模型中加载的参数。这里就是最后的全联接层,因为在
# 新的问题中我们要重新训练这一层中的参数。这里给出的是参数的前缀。
CHECKPOINT_EXCLUDE_SCOPES = 'InceptionV3/Logits,InceptionV3/AuxLogits'
# 需要训练的网络层参数明层,在fine-tuning的过程中就是最后的全联接层。
# 这里给出的是参数的前缀。
TRAINABLE_SCOPES='InceptionV3/Logits'# 获取所有需要从谷歌训练好的模型中加载的参数。
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():print var.op.nameexcluded = Falsefor exclusion in exclusions:if var.op.name.startswith(exclusion):excluded = Truebreakif 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_traindef 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]# 定义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()):train_logits, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES, is_training=True)# 定义测试使用的模型时需要将reuse设置为True。test_logits, _ = inception_v3.inception_v3(images, num_classes=N_CLASSES, is_training=False, reuse=True)trainable_variables = get_trainable_variables()print(trainable_variables)cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=train_logits, labels=tf.one_hot(labels, N_CLASSES))cross_entropy_mean = tf.reduce_mean(cross_entropy)train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean,var_list=trainable_variables)# 计算正确率。with tf.name_scope('evaluation'):correct_prediction = tf.equal(tf.argmax(test_logits, 1), labels)evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))loader = tf.train.Saver(get_tuned_variables())saver = tf.train.Saver()with tf.variable_scope("InceptionV3", reuse = True):check1 = tf.get_variable("Conv2d_1a_3x3/weights")check2 = tf.get_variable("Logits/Conv2d_1c_1x1/weights")with tf.Session() as sess:# 初始化没有加载进来的变量。init = tf.global_variables_initializer()sess.run(init)print sess.run(check1)print sess.run(check2)# 加载谷歌已经训练好的模型。print('Loading tuned variables from %s' % CKPT_FILE)loader.restore(sess, CKPT_FILE)start = 0end = BATCHfor i in range(STEPS):print sess.run(check1)print sess.run(check2)_, loss = sess.run([train_step, cross_entropy_mean], feed_dict={images: training_images[start:end], labels: training_labels[start:end]})if i % 100 == 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 * 100.0, validation_accuracy * 100.0))start = endif start == n_training_example:start = 0end = start + BATCHif end > n_training_example: end = n_training_example# 在最后的测试数据上测试正确率。test_accuracy = sess.run(evaluation_step, feed_dict={images: test_images, labels: test_labels})print('Final test accuracy = %.1f%%' % (test_accuracy * 100))if __name__ == '__main__':main()

转载于:https://www.cnblogs.com/tszr/p/10885106.html

吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(3)相关推荐

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

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

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

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

  3. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用隐藏层

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dataINPUT_NODE = 784 # ...

  4. 吴裕雄 python 神经网络——TensorFlow 图、张量及会话

    import tensorflow as tfg1 = tf.Graph() with g1.as_default():v = tf.get_variable("v", [1], ...

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

    import tensorflow as tf# 输入数据 from tensorflow.examples.tutorials.mnist import input_datamnist = inpu ...

  6. python识别花草_吴裕雄 python神经网络 花朵图片识别(9)

    import os import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageChops from ...

  7. python识别花草_吴裕雄 python神经网络 花朵图片识别(10)

    import os import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageChops from ...

  8. 绒毛动物探测器:通过TensorFlow.js中的迁移学习识别浏览器中的自定义对象

    目录 起点 MobileNet v1体系结构上的迁移学习 修改模型 训练新模式 运行物体识别 终点线 下一步是什么?我们可以检测到脸部吗? 下载TensorFlowJS-Examples-master ...

  9. 使用Flow forecast进行时间序列预测和分类的迁移学习介绍

    ImageNet首次发表于2009年,在接下来的四年里,它成为了大多数计算机视觉模型的基础.到目前为止,无论您是在训练一个模型来检测肺炎还是对汽车模型进行分类,您都可能从在ImageNet或其他大型( ...

  10. 宠物狗图片分类之迁移学习代码笔记

    五月两场 | NVIDIA DLI 深度学习入门课程 5月19日/5月26日一天密集式学习  快速带你入门阅读全文> 正文共3152个字,预计阅读时间8分钟. 本文主要是总结之前零零散散抽出时间 ...

最新文章

  1. Oracle PLSQL 导出数据table xx contains one or more CLOB columns 解决方案
  2. 监控磁盘并发mail通知
  3. ios模拟器装ipa包_uni-app 打包ios上架app store流程
  4. python四分位数_分位函数(四分位数)概念与pandas中的quantile函数
  5. 【方案分享】2021美图美学营销方案.pdf(附下载链接)
  6. js课程 2-6 js如何进行类型转换及js运算符有哪些
  7. 战地一的服务器在哪个文件夹,战地1怎么加入服务器 战地1加入服务器方法
  8. 支付宝客户端java版_支付宝对接支付-JAVA版
  9. pyspark调用spark以及执行带in语句参数的hql示例
  10. jq 遍历map集合
  11. cgcs2000大地坐标系地图_MapGIS国土空间数据2000大地坐标系转换系统
  12. 天龙八部,小师妹,李沧海,齐御风
  13. poj java_POJ 3083 java实现
  14. linux rpm -qip命令,linux rpm命令
  15. C#支付宝当面付扫码支付开发,包括demo代码的修改和蚂蚁金服开发平台的配置
  16. 无线网密码修改好了无法连接服务器,无线路由器修改密码后电脑无法上网如何解决...
  17. 从0基础到车载测试工程师,薪资11K,肯拼搏的人,总会有所收获
  18. bway ESL电竞联赛十六季C组对战前瞻 三组战队情报分析
  19. UT-Exynos4412开发板三星ARM四核旗舰开发平台android4.0体验-7GPS功能调试支持
  20. 恢复我的文档中三个标准文件夹

热门文章

  1. Android模拟器SDL_app:emulator.exe 解决方法
  2. vCheck 5.0
  3. 苹果Mac开启root用户及切换到root用户的方法
  4. PHP的新手语法介绍
  5. 关于vue脚手架cli3.0版本的一篇有关配置的文章,可以借鉴
  6. ceph分布式存储简介
  7. 使用shell创建一个简单的菜单bash select用法
  8. 10次课( find命令、文件名后缀)
  9. 单例模式简单示例与优化
  10. Android WebView中那些不得不解决的坑~~