实现迁徙学习-《tensorflow实战google深度学习框架》代码详解(代码片段)

cucucudeblog cucucudeblog     2023-02-20     135

关键词:

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

#利用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

技术分享图片

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

迁徙学习的代码如下

1 # -*- coding: utf-8 -*-
2 import glob
3 import os.path
4 import random
5 import numpy as np
6 import tensorflow as tf
7 from tensorflow.python.platform import gfile

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

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

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

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

 1 #这个函数从数据文件夹中读取所有的图片列表并把样本中所有的图片列表并按训练、验证、测试数据分开
 2 #在函数中testing_percentage, validation_percentage这两个参数指定了测试数据集和验证数据集的大小
 3 def create_image_lists(testing_percentage, validation_percentage):
 4     result = 
 5     # 获取当前目录下所有的子目录
 6     sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
 7     # 得到的第一个目录是当前目录,不需要考虑
 8     is_root_dir = True
 9     for sub_dir in sub_dirs:
10         if is_root_dir:
11             is_root_dir = False
12             continue
13 
14         #获取当前目录下所有有效图片文件
15         extensions = [jpg, jpeg, JPG, JPEG]
16 
17         file_list = []
18         dir_name = os.path.basename(sub_dir)
19         for extension in extensions:
20             file_glob = os.path.join(INPUT_DATA, dir_name, *. + extension)
21             file_list.extend(glob.glob(file_glob))
22         if not file_list: continue
23 
24         #通过目录名获取类别的名称
25         label_name = dir_name.lower()
26 
27         # 初始化当前类别的训练数据集,测试数据集和验证数据集
28         training_images = []
29         testing_images = []
30         validation_images = []
31         for file_name in file_list:
32             base_name = os.path.basename(file_name)
33 
34             # 随机将数据分到训练数据集,测试数据集和验证数据集
35             chance = np.random.randint(100)
36             if chance < validation_percentage:
37                 validation_images.append(base_name)
38             elif chance < (testing_percentage + validation_percentage):
39                 testing_images.append(base_name)
40             else:
41                 training_images.append(base_name)
42 
43         #将当前类别的数据放入结果字典
44         result[label_name] = 
45             dir: dir_name,
46             training: training_images,
47             testing: testing_images,
48             validation: validation_images,
49         
50     #返回整理好的所有数据
51     return result

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

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

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

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

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

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

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

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

 1 #这个函数获取一张图片经过Inception_v3模型处理之后的特征向量,这个函数会先试图寻找已经计算且保存下来的特征向量,如果找不到则先计算这个特征向量,然后保存到文件
 2 def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):
 3     label_lists = image_lists[label_name]
 4     sub_dir = label_lists[dir]
 5     sub_dir_path = os.path.join(CACHE_DIR, sub_dir)
 6     if not os.path.exists(sub_dir_path): os.makedirs(sub_dir_path)
 7     bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)
 8     if not os.path.exists(bottleneck_path):
 9 
10         image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)
11 
12         image_data = gfile.FastGFile(image_path, rb).read()
13 
14         bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)
15 
16         bottleneck_string = ,.join(str(x) for x in bottleneck_values)
17         with open(bottleneck_path, w) as bottleneck_file:
18             bottleneck_file.write(bottleneck_string)
19     else:
20 
21         with open(bottleneck_path, r) as bottleneck_file:
22             bottleneck_string = bottleneck_file.read()
23         bottleneck_values = [float(x) for x in bottleneck_string.split(,)]
24 
25     return bottleneck_values

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

 1 #这个函数随机获取一个batch的图片作为训练数据
 2 def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, jpeg_data_tensor, bottleneck_tensor):
 3     bottlenecks = []
 4     ground_truths = []
 5     for _ in range(how_many):
 6         label_index = random.randrange(n_classes)
 7         label_name = list(image_lists.keys())[label_index]
 8         image_index = random.randrange(65536)
 9         bottleneck = get_or_create_bottleneck(
10             sess, image_lists, label_name, image_index, category, jpeg_data_tensor, bottleneck_tensor)
11         ground_truth = np.zeros(n_classes, dtype=np.float32)
12         ground_truth[label_index] = 1.0
13         bottlenecks.append(bottleneck)
14         ground_truths.append(ground_truth)
15 
16     return bottlenecks, ground_truths

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

 1 #这个函数获取全部的测试数据,并计算正确率
 2 def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):
 3     bottlenecks = []
 4     ground_truths = []
 5     label_name_list = list(image_lists.keys())
 6     for label_index, label_name in enumerate(label_name_list):
 7         category = testing
 8         for index, unused_base_name in enumerate(image_lists[label_name][category]):
 9             bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,jpeg_data_tensor, bottleneck_tensor)
10             ground_truth = np.zeros(n_classes, dtype=np.float32)
11             ground_truth[label_index] = 1.0
12             bottlenecks.append(bottleneck)
13             ground_truths.append(ground_truth)
14     return bottlenecks, ground_truths

 

9. 定义主函数

 1 #定义主函数
 2 def main(_):
 3     image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
 4     n_classes = len(image_lists.keys())
 5 
 6     # 读取已经训练好的Inception-v3模型。
 7     with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), rb) as f:
 8         graph_def = tf.GraphDef()
 9         graph_def.ParseFromString(f.read())
10     bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(
11         graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])
12 
13     # 定义新的神经网络输入
14     bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE], name=BottleneckInputPlaceholder)
15     ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name=GroundTruthInput)
16 
17     # 定义一层全链接层
18     with tf.name_scope(final_training_ops):
19         weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))
20         biases = tf.Variable(tf.zeros([n_classes]))
21         logits = tf.matmul(bottleneck_input, weights) + biases
22         final_tensor = tf.nn.softmax(logits)
23 
24     # 定义交叉熵损失函数。
25     cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, ground_truth_input)
26     cross_entropy_mean = tf.reduce_mean(cross_entropy)
27     train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)
28 
29     # 计算正确率。
30     with tf.name_scope(evaluation):
31         correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))
32         evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
33 
34     with tf.Session() as sess:
35         init = tf.global_variables_initializer()
36         sess.run(init)
37         # 训练过程。
38         for i in range(STEPS):
39 
40             train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(
41                 sess, n_classes, image_lists, BATCH, training, jpeg_data_tensor, bottleneck_tensor)
42             sess.run(train_step,
43                      feed_dict=bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth)
44 
45             if i % 100 == 0 or i + 1 == STEPS:
46                 validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(
47                     sess, n_classes, image_lists, BATCH, validation, jpeg_data_tensor, bottleneck_tensor)
48                 validation_accuracy = sess.run(evaluation_step, feed_dict=
49                     bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth)
50                 print(Step %d: Validation accuracy on random sampled %d examples = %.1f%% %
51                       (i, BATCH, validation_accuracy * 100))
52 
53         # 在最后的测试数据上测试正确率。
54         test_bottlenecks, test_ground_truth = get_test_bottlenecks(
55             sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor)
56         test_accuracy = sess.run(evaluation_step, feed_dict=
57             bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth)
58         print(Final test accuracy = %.1f%% % (test_accuracy * 100))
59 
60 
61 if __name__ == __main__:
62     tf.app.run()

 

《tensorflow实战google深度学习框架(第二版)》学习笔记及书评(代码片段)

《TensorFlow实战Google深度学习框架(第二版)》学习笔记文章目录《TensorFlow实战Google深度学习框架(第二版)》学习笔记写在前面1.TensorFlow图像处理函数学习总结2.TensorFlow图像预处理完整样例3.TensorFlow多线程输入... 查看详情

《tensorflow实战google深度学习框架(第2版)》+《tensorflow实战_黄文坚》

资源链接:https://pan.baidu.com/s/1n-ydbsnvKag4jWgpHRGIUA《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码带目录标签,文字可以复制,363页。配套源代码;《TensorFlow实战_黄文坚》中文版PDF和源代码带目录标签,文字可以复制... 查看详情

tensorflow实战google深度学习框架

...就要入职。接下来准备在接下来的半个月时间内重温一下TensorFlow的用法。道友么,有感兴趣的,大家一起一起交流学习呀!争取每天更新~本书有十章,所以将分成十个部分介绍该系列来源于书籍《TensorFLow实战Google深度学习框... 查看详情

学习《tensorflow实战google深度学习框架(第2版)》中文pdf和代码

TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用。《TensorFlow:实战Google深度学习框架(第2版)》为TensorFlow入门参考书,帮助快速、有效的方式上手TensorFlow和深度学习。书中省略了烦琐的数学模型推导,从实... 查看详情

求《tensorflow:实战google深度学习框架》全文免费下载百度网盘资源,谢谢~

《TensorFlow:实战Google深度学习框架》百度网盘pdf最新全集下载:链接:https://pan.baidu.com/s/1pSqb0GyJnrtt-CVG1DI2_g?pwd=zm65提取码:zm65简介:TensorFlow:实战Google深度学习框架pdf电子书,TensorFlow是一门新型技术学习框架,本书作者作为TensorFlo... 查看详情

tensorflow:实战google深度学习框架第三章

tensorflow的计算模型:计算图–tf.Graph tensorflow的数据模型:张量–tf.Tensor tensorflow的运行模型:会话–tf.Session tensorflow可视化工具:TensorBoard 通过集合管理资源:tf.add_to_collection、tf.get_collection Tensor主要三个属 查看详情

tensorflow实战google深度学习框架(代码片段)

第3章TensorFlow入门3.1TensorFlow计算模型-计算图3.1.1计算图的概念Tensorflow中所有计算都会被转化成计算图的一个节点,计算图上的边表示了他们之间的相互依赖关系。3.1.2计算图的使用Tensorflow的程序可以分成两个阶段:定义计算、... 查看详情

tensorflow实战google深度学习框架笔记codepart(代码片段)

深层神经网络线性模型的局限性激活函数实现去线性化a=tf.nn.relu(tf.matmul(x,w1)+biases1)y=tf.nn.relu(tf.matmul(a,w2)+biases2)经典损失函数#计算交叉熵cross_entropy=-tf.reduce_mean(y_*tf.log(tf.clip_by_value(y,le-10,1.0)))#tf.clip_by_value样例 查看详情

tensorflow实现迁移学习

此例程出自《TensorFlow实战Google深度学习框架》6.5.2小节卷积神经网络迁移学习。 数据集来自http://download.tensorflow.org/example_images/flower_photos.tgz ,及谷歌提供的Inception-v3模型https://storage.googleapis.com/download.tensorflow 查看详情

tensorflow实战google深度学习框架笔记摘要pone

《Tensorflow实战Google深度学习框架》前三章的摘要(没有简介和环境搭建的部分)摘要的内容是与tensorflow语句相关的知识如有违规之类的请通知我啊这个pdf一般bd有需要的可以私聊我或者留下扣扣邮箱欢迎指点注:本来是要直接... 查看详情

tensorflow实现迁移学习

此例程出自《TensorFlow实战Google深度学习框架》6.5.2小节卷积神经网络迁移学习。数据集来自http://download.tensorflow.org/example_images/flower_photos.tgz,及谷歌提供的Inception-v3模型https://storage.googleapis.com/download.tensorflow.org/ 查看详情

tensorflow实战google深度学习框架笔记摘要pfour

6.4经典卷积网络模型LeNet-5模型     Inception-v3模型     6.5卷积神经网络迁移学习              查看详情

分享《tensorflow实战google深度学习框架(第2版)》+pdf+源码+郑泽宇

...3-QPyHn5oCcVhcKjtTYFw更多分享资料:http://blog.51cto.com/14087171《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页。配套源代码;经典书籍,讲解详细;如图: 查看详情

书籍推荐:《tensorflow实战google深度学习框架第2版》(高清pdf中文版)

内容简介:TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用。《TensorFlow:实战Google深度学习框架(第2版)》为TensorFlow入门参考书,旨在帮助读者以快速、有效的方式上手TensorFlow和深度学习。书中省略了烦琐... 查看详情

《tensorflow实战google深度学习框架(第2版)》中文版pdf和源代码

下载:https://pan.baidu.com/s/1hltIZdjkET3CNxKWSixtZA《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页。配套源代码;经典书籍,讲解详细;如图: 查看详情

《tensorflow实战google深度学习框架(第2版)》中文版pdf和源代码

下载:https://pan.baidu.com/s/1aD1Y2erdtppgAbk8c63xEw《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页。配套源代码;经典书籍,讲解详细;如图 查看详情

分享《tensorflow实战google深度学习框架(第2版)》中文版pdf和源代码

下载:https://pan.baidu.com/s/1hltIZdjkET3CNxKWSixtZA《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页。配套源代码;经典书籍,讲解详细;如图: 查看详情

分享《tensorflow实战google深度学习框架(第2版)》中文版pdf和源代码

下载:(https://pan.baidu.com/s/1mrEiGC2B3h6p1iOZuOkGlw)《TensorFlow实战Google深度学习框架(第2版)》中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页。配套源代码;经典书籍,讲解详细;如图: 查看详情