zoukankan      html  css  js  c++  java
  • 实现迁徙学习-《Tensorflow 实战Google深度学习框架》代码详解

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

    #利用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()
  • 相关阅读:
    C#制作windows屏保实战
    创建一个可以修改不可以删除的文件夹或文件,windows目录和文件权限实测总结
    分享一下我用C#写的贪吃蛇和迷宫
    用C#做的汉诺塔游戏以及对汉诺塔递归的简单理解
    纪念一下即将逝去的flash,曾今的flash入门学习示例《别盯着我》C#版
    C#中关于变量的作用域不易理解的特例
    列出文件夹和遍历文件夹的区别
    怎样创建无法直接删除的文件夹--关于windows权限的迷思
    用C#写的后台整点报时工具
    用C#写差异文件备份工具
  • 原文地址:https://www.cnblogs.com/Cucucudeblog/p/10159025.html
Copyright © 2011-2022 走看看