为了实现迁徙学习,首先是数据集的下载

#利用curl下载数据集
curl -o flower_photos.tgz http://download.tensorflow.org/example_images/flower_photos.tgz
#在当前路径下对下载的数据集进行解压
tar xzf flower_photos.tgz
  • 下载谷歌提供的训练好的Inception-v3模型
wget -P /Volumes/Cu/QianXi_Learning --no-check-certificate https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip

wget -P是将模型下载到指定的数据集中

加入--no-check-certificate是因为wget在使用HTTPS协议时,默认会去验证网站的证书,而这个证书验证经常会失败,为了解决这个问题而添加的

  • 解压所训练好的模型

和书上提供的解压不一样,因为我的终端已经是在根目录下,因此直接

unzip /Volumes/Cu/QianXi_Learning/inception_dec_2015.zip

下面开始正式的利用下列代码实现迁徙学习

迁徙学习的代码如下

 # -*- coding: utf-8 -*-
import glob
import os.path
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile

1. 进行模型和样本参数和路径的设置

 #Inception_v3模型瓶颈层的节点个数
BOTTLENECK_TENSOR_SIZE = 2048
BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' MODEL_DIR = '/Volumes/Cu/QianXi_Learning/inception_dec_2015'
MODEL_FILE= 'tensorflow_inception_graph.pb' # 因为一个训练数据会被使用多次,所以可以将原始图像通过Inception-v3模型计算得到的特征向量保存在文件中,免去重复的计算。
CACHE_DIR = '/Volumes/Cu/QianXi_Learning/bottleneck'
INPUT_DATA = '/Volumes/Cu/QianXi_Learning/flower_photos' # 验证的数据百分比
VALIDATION_PERCENTAGE = 10
# 测试的数据百分比
TEST_PERCENTAGE = 10 #神经网络参数的设置
LEARNING_RATE = 0.01
STEPS = 4000
BATCH = 100

在Inception_v3模型中代表瓶颈层结果的张量名称,在谷歌提供的Inception+v3模型中,这个张量的名称就是'pool_3/_reshape:0',并且在模型准备的时候,我们就已经将训练好的Inception_v3模型存放到已有的文件夹中,因此只需要指定其路径与模型名称即可,对于训练网络的其它参数,也不再进行赘述

2. 最基本的模型参数与路径设置完之后,我们就会开始对模型进行定义一系列的函数,首先是把样本中的所有图片列表化并且将其按照训练、验证、测试数据分开

 #这个函数从数据文件夹中读取所有的图片列表并把样本中所有的图片列表并按训练、验证、测试数据分开
#在函数中testing_percentage, validation_percentage这两个参数指定了测试数据集和验证数据集的大小
def create_image_lists(testing_percentage, validation_percentage):
result = {}
# 获取当前目录下所有的子目录
sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
# 得到的第一个目录是当前目录,不需要考虑
is_root_dir = True
for sub_dir in sub_dirs:
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:
file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension)
file_list.extend(glob.glob(file_glob))
if not file_list: continue #通过目录名获取类别的名称
label_name = dir_name.lower() # 初始化当前类别的训练数据集,测试数据集和验证数据集
training_images = []
testing_images = []
validation_images = []
for file_name in file_list:
base_name = os.path.basename(file_name) # 随机将数据分到训练数据集,测试数据集和验证数据集
chance = np.random.randint(100)
if chance < validation_percentage:
validation_images.append(base_name)
elif chance < (testing_percentage + validation_percentage):
testing_images.append(base_name)
else:
training_images.append(base_name) #将当前类别的数据放入结果字典
result[label_name] = {
'dir': dir_name,
'training': training_images,
'testing': testing_images,
'validation': validation_images,
}
#返回整理好的所有数据
return result

对于这个函数,其形参就是testing_percentage和validation_percentage,我们将结果存放在一个字典中

3. 定义函数通过类别名称、所属数据集和图片编号获取一张图片的地址

 #这个函数通过类别名称、所属数据集和图片编号获取一张图片的地址
#image_lists参数给出了所有图片的信息
#image_dir参数给出了根目录
#label_name参数定义了类别的名称
#index参数给定了需要获取的图片的编号
#category参数指定了需要获取的图片实在训练数据集,测试数据集还是验证数据集
def get_image_path(image_lists, image_dir, label_name, index, category):
#获取给定类别中所有图片的信息
label_lists = image_lists[label_name]
#根据所属数据集的名称获取集合中的全部图片信息
category_list = label_lists[category]
mod_index = index % len(category_list)
# 获取图片的文件名
base_name = category_list[mod_index]
sub_dir = label_lists['dir']
#最终的地址为数据根目录的地址加上类别的文件夹加上图片的名称
full_path = os.path.join(image_dir, sub_dir, base_name)
return full_path

4. 定义函数获取Inception_v3模型处理后的特征向量的文件地址

 #定义函数获取Inception-v3模型处理之后的特征向量的文件地址
def get_bottleneck_path(image_lists, label_name, index, category):
return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt'

5. 定义函数使用加载好的Inception_v3模型处理每一张图片,得到这个图片的特征向量

 #定义函数使用加载的训练好的Inception-v3模型处理一张图片,得到这个图片的特征向量
#这个过程实际上就是将当前图片作为输入计算瓶颈张量的值,这个瓶颈张量的值就是这张图片的新的特征向量
def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor): bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})
#经过卷积神经网络处理的结果是一个四维数组,需要将这个结果压缩成一个特征向量(一维数组)
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values

6. 函数获取一张图片经过Inception_v3模型处理之后的特征向量,这个函数会先试图寻找已经计算且保存下来的特征向量,如果找不到则先计算这个特征向量,然后保存到文件

 #这个函数获取一张图片经过Inception_v3模型处理之后的特征向量,这个函数会先试图寻找已经计算且保存下来的特征向量,如果找不到则先计算这个特征向量,然后保存到文件
def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):
label_lists = image_lists[label_name]
sub_dir = label_lists['dir']
sub_dir_path = os.path.join(CACHE_DIR, sub_dir)
if not os.path.exists(sub_dir_path): os.makedirs(sub_dir_path)
bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)
if not os.path.exists(bottleneck_path): image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category) image_data = gfile.FastGFile(image_path, 'rb').read() bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor) bottleneck_string = ','.join(str(x) for x in bottleneck_values)
with open(bottleneck_path, 'w') as bottleneck_file:
bottleneck_file.write(bottleneck_string)
else: with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
bottleneck_values = [float(x) for x in bottleneck_string.split(',')] return bottleneck_values

7. 定义一个函数随机获取一个batch的图片作为训练数据

 #这个函数随机获取一个batch的图片作为训练数据
def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, jpeg_data_tensor, bottleneck_tensor):
bottlenecks = []
ground_truths = []
for _ in range(how_many):
label_index = random.randrange(n_classes)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(65536)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, category, jpeg_data_tensor, bottleneck_tensor)
ground_truth = np.zeros(n_classes, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth) return bottlenecks, ground_truths

8. 定义一个函数获取全部的测试数据,并计算正确率

 #这个函数获取全部的测试数据,并计算正确率
def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):
bottlenecks = []
ground_truths = []
label_name_list = list(image_lists.keys())
for label_index, label_name in enumerate(label_name_list):
category = 'testing'
for index, unused_base_name in enumerate(image_lists[label_name][category]):
bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,jpeg_data_tensor, bottleneck_tensor)
ground_truth = np.zeros(n_classes, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
return bottlenecks, ground_truths

9. 定义主函数

 #定义主函数
def main(_):
image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
n_classes = len(image_lists.keys()) # 读取已经训练好的Inception-v3模型。
with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(
graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME]) # 定义新的神经网络输入
bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE], name='BottleneckInputPlaceholder')
ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput') # 定义一层全链接层
with tf.name_scope('final_training_ops'):
weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))
biases = tf.Variable(tf.zeros([n_classes]))
logits = tf.matmul(bottleneck_input, weights) + biases
final_tensor = tf.nn.softmax(logits) # 定义交叉熵损失函数。
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, ground_truth_input)
cross_entropy_mean = tf.reduce_mean(cross_entropy)
train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean) # 计算正确率。
with tf.name_scope('evaluation'):
correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
# 训练过程。
for i in range(STEPS): train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(
sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)
sess.run(train_step,
feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth}) if i % 100 == 0 or i + 1 == STEPS:
validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(
sess, n_classes, image_lists, BATCH, 'validation', jpeg_data_tensor, bottleneck_tensor)
validation_accuracy = sess.run(evaluation_step, feed_dict={
bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth})
print('Step %d: Validation accuracy on random sampled %d examples = %.1f%%' %
(i, BATCH, validation_accuracy * 100)) # 在最后的测试数据上测试正确率。
test_bottlenecks, test_ground_truth = get_test_bottlenecks(
sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor)
test_accuracy = sess.run(evaluation_step, feed_dict={
bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth})
print('Final test accuracy = %.1f%%' % (test_accuracy * 100)) if __name__ == '__main__':
tf.app.run()

实现迁徙学习-《Tensorflow 实战Google深度学习框架》代码详解的更多相关文章

  1. 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)

    学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...

  2. 2 (自我拓展)部署花的识别模型(学习tensorflow实战google深度学习框架)

    kaggle竞赛的inception模型已经能够提取图像很好的特征,后续训练出一个针对当前图片数据的全连接层,进行花的识别和分类.这里见书即可,不再赘述. 书中使用google参加Kaggle竞赛的i ...

  3. [Tensorflow实战Google深度学习框架]笔记4

    本系列为Tensorflow实战Google深度学习框架知识笔记,仅为博主看书过程中觉得较为重要的知识点,简单摘要下来,内容较为零散,请见谅. 2017-11-06 [第五章] MNIST数字识别问题 ...

  4. TensorFlow+实战Google深度学习框架学习笔记(5)----神经网络训练步骤

    一.TensorFlow实战Google深度学习框架学习 1.步骤: 1.定义神经网络的结构和前向传播的输出结果. 2.定义损失函数以及选择反向传播优化的算法. 3.生成会话(session)并且在训 ...

  5. 学习《TensorFlow实战Google深度学习框架 (第2版) 》中文PDF和代码

    TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用.<TensorFlow:实战Google深度学习框架(第2版)>为TensorFlow入门参考书,帮助快速. ...

  6. TensorFlow实战Google深度学习框架10-12章学习笔记

    目录 第10章 TensorFlow高层封装 第11章 TensorBoard可视化 第12章 TensorFlow计算加速 第10章 TensorFlow高层封装 目前比较流行的TensorFlow ...

  7. TensorFlow实战Google深度学习框架5-7章学习笔记

    目录 第5章 MNIST数字识别问题 第6章 图像识别与卷积神经网络 第7章 图像数据处理 第5章 MNIST数字识别问题 MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会 ...

  8. TensorFlow实战Google深度学习框架1-4章学习笔记

    目录 第1章 深度学习简介 第2章 TensorFlow环境搭建 第3章 TensorFlow入门 第4章 深层神经网络   第1章 深度学习简介 对于许多机器学习问题来说,特征提取不是一件简单的事情 ...

  9. Tensorflow实战Google深度学习框架-总结-1

    第一章:深度学习简介   1⃣️应用有 1.计算机视觉 2.语音识别 3.自然语言处理 4.人机博弈   2⃣️深度学习,机器学习,AI 的关系

  10. TensorFlow实战Google深度学习框架-人工智能教程-自学人工智能的第二天-深度学习

    自学人工智能的第一天 "TensorFlow 是谷歌 2015 年开源的主流深度学习框架,目前已得到广泛应用.本书为 TensorFlow 入门参考书,旨在帮助读者以快速.有效的方式上手 T ...

随机推荐

  1. python 基础篇

    1.编程语言介绍. 1.机器语言:直接用二进制编程,直接对硬件的控制,需对硬件掌握比较深. 优点:执行效率快 缺点:开发效率低下 2.汇编语言:用英文标签代替二进制编写程序,直接对硬件的控制,需对硬件 ...

  2. css3实现背景渐变

    #grad { background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /* Safari 5.1 - 6 ...

  3. Windows Server2008、IIS7启用CA认证及证书制作完整过程

    1         添加活动目录证书服务 1.1          打开服务器管理器,右键点击角色,选择“添加角色”,在“添加角色向导”窗口左侧面板选择“服务器角色”,然后勾选“Active Dire ...

  4. Nginx 如何处理上游响应的数据

    陶辉93 一个非常重要的指令 proxy_buffer_size 指令限制头部响应header最大值 proxy_buffering 指令主要是指 上游服务器是否接受完完整包体在处理 默认是on 也就 ...

  5. BZOJ2142礼物——扩展卢卡斯

    题目描述 一年一度的圣诞节快要来到了.每年的圣诞节小E都会收到许多礼物,当然他也会送出许多礼物.不同的人物在小E 心目中的重要性不同,在小E心中分量越重的人,收到的礼物会越多.小E从商店中购买了n件礼 ...

  6. web scraper——简单的爬取数据【二】

    web scraper——安装[一] 在上文中我们已经安装好了web scraper现在我们来进行简单的爬取,就来爬取百度的实时热点吧. http://top.baidu.com/buzz?b=1&a ...

  7. HDU4341-Gold miner-分组DP

    模拟黄金矿工这个游戏,给出每一个金子的位置和所需时间,计算在给定时间内最大收益. 刚看这道题以为金子的位置没什么用,直接DP就行,WA了一发终于明白如果金子和人共线的话只能按顺序抓. 这就是需要考虑先 ...

  8. [USACO2008 Mar]土地购买

    传送门:>HERE< 题意:购买一组土地的费用是最长的长乘以最长的宽.现给出n块土地,求购买所有土地(可以将土地分为任意组,不需按顺序)的最小费用 解题思路 动态规划+斜率优化 斜率优化在 ...

  9. C# 成员默认访问权限(public、private、protected、internal)

    C# 成员默认访问权限(public.private.protected.internal) 来源 https://www.cnblogs.com/yezongjie/p/20181121Access ...

  10. windows 设置ipsec防火墙

    windows server 推荐使用ipsec修改防火墙设置,默认防火墙需要手动导入导出.wfw文件,需要手动添加单条规则,维护麻烦,推荐关闭,使用ipsec管理 以下是线上防火墙配置,可参照业务环 ...