参考书

《TensorFlow:实战Google深度学习框架》(第2版)

一个使用数据集进行训练和测试的完整例子。

  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. # coding=utf-8
  4.  
  5. """
  6. @author: Li Tian
  7. @contact: 694317828@qq.com
  8. @software: pycharm
  9. @file: dataset_test5.py
  10. @time: 2019/2/12 13:45
  11. @desc: 使用数据集实现数据输入流程
  12. """
  13.  
  14. import tensorflow as tf
  15. from figuredata_deal.figure_deal_test2 import preprocess_for_train
  16.  
  17. # 列举输入文件。训练和测试使用不同的数据
  18. train_files = tf.train.match_filenames_once('./train_file-*')
  19. test_files = tf.train.match_filenames_once('./test_files-*')
  20.  
  21. # 定义parser方法从TFRecord中解析数据。这里假设image中存储的是图像的原始数据,
  22. # label为该样例所对应的标签。height、width和channels给出了图片的维度。
  23. def parser(record):
  24. features = tf.parse_single_example(
  25. record,
  26. features={
  27. 'image': tf.FixedLenFeature([], tf.string),
  28. 'label': tf.FixedLenFeature([], tf.int64),
  29. 'height': tf.FixedLenFeature([], tf.int64),
  30. 'width': tf.FixedLenFeature([], tf.int64),
  31. 'channels': tf.FixedLenFeature([], tf.int64),
  32. }
  33. )
  34.  
  35. # 从原始图像数据解析出像素矩阵,并根据图像尺寸还原图像。
  36. decoded_image = tf.decode_raw(features['image'], tf.uint8)
  37. decoded_image.set_shape([features['height'], features['width'], features['channels']])
  38. label = features['label']
  39. return decoded_image, label
  40.  
  41. # 定义神经网络输入层图片的大小
  42. image_size = 299
  43. # 定义组合数据batch的大小
  44. batch_size = 100
  45. # 定义随机打乱数据时buffer的大小
  46. shuffle_buffer = 10000
  47.  
  48. # 定义读取训练数据的数据集
  49. dataset = tf.data.TFRecordDataset(train_files)
  50. dataset = dataset.map(parser)
  51.  
  52. # 对数据依次进行预处理、shuffle和batching操作。preprocess_for_train为前面介绍的
  53. # 图像预处理程序。因为上一个map得到的数据集中提供了decoded_image和label两个结果,所以这个
  54. # map需要提供一个有2个参数的函数来处理数据。在下面的代码中,lambda中的image代表的就是第一个map返回的
  55. # decoded_image,label代表的就是第一个map返回的label。在这个lambda表达式中我们首先将decoded_image
  56. # 在传入preprocess_for_train来进一步对图像数据进行预处理。然后再将处理好的图像和label组成最终的输出。
  57. dataset = dataset.map(
  58. lambda image, label: (
  59. preprocess_for_train(image, image_size, image_size, None), label
  60. )
  61. )
  62. dataset = dataset.shuffle(shuffle_buffer).batch(batch_size)
  63.  
  64. # 重复NUM_EPOCHS个epoch。在前面TRAINING_ROUNDS指定了训练的轮数,
  65. # 而这里指定了整个数据集重复的次数,它也间接地确定了训练的论述。
  66. NUM_EPOCHS = 10
  67. dataset = dataset.repeat(NUM_EPOCHS)
  68.  
  69. # 定义数据集迭代器。虽然定义数据集的时候没直接使用placeholder来提供文件地址,但是
  70. # tf.train.match_filenames_once方法得到的结果和与placeholder的机制类似,也需要初始化。
  71. # 所以这里使用的是initializable_iterator
  72. iterator = dataset.make_initializable_iterator()
  73. image_batch, label_batch = iterator.get_next()
  74.  
  75. # 定义神经网络的结果以及优化过程。这里与前面的相同。
  76. learning_rate = 0.01
  77. logit = inference(image_batch)
  78. loss = calc_loss(logit, label_batch)
  79. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
  80.  
  81. # 定义测试用的Dataset。与训练时不同,测试数据的Dataset不需要经过随机翻转等预处理操作,
  82. # 也不需要打乱顺序和重复多个epoch。这里使用于训练数据相同的parser进行解析,调整分辨率
  83. # 到网络输入层大小,然后直接进行batching操作。
  84. test_dataset = tf.data.TFRecordDataset(test_files)
  85. test_dataset = test_dataset.map(parser).map(
  86. lambda image, label: (
  87. tf.image.resize_images(image, [image_size, image_size]), label
  88. )
  89. )
  90. test_dataset = test_dataset.batch(batch_size)
  91.  
  92. # 定义测试数据上的迭代器
  93. test_iterator = test_dataset.make_initializable_iterator()
  94. test_image_batch, test_label_batch = test_iterator.get_next()
  95.  
  96. # 定义预测结果为logit值最大的分类
  97. test_logit = inference(test_image_batch)
  98. predictions = tf.argmax(test_logit, axis=-1, output_type=tf.int32)
  99.  
  100. # 声明会话并运行神经网络的优化过程
  101. with tf.Session() as sess:
  102. # 初始化变量
  103. sess.run((
  104. tf.global_variables_initializer(),
  105. tf.local_variables_initializer()
  106. ))
  107.  
  108. # 初始化训练数据的迭代器。
  109. sess.run(iterator.initializer)
  110.  
  111. # 循环进行训练,知道数据集完成输入,抛出OutOfRangeError错误
  112. while True:
  113. try:
  114. sess.run(train_step)
  115. except tf.errors.OutOfRangeError:
  116. break
  117.  
  118. # 初始化测试数据的迭代器
  119. sess.run(test_iterator.initializer)
  120.  
  121. # 获取预测结果
  122. test_results = []
  123. test_labels = []
  124. while True:
  125. try:
  126. pred, label = sess.run([predictions, test_label_batch])
  127. test_results.extend(pred)
  128. test_labels.extend(label)
  129. except tf.errors.OutOfRangeError:
  130. break
  131.  
  132. # 计算准确率
  133. correct = [float(y == y_) for (y, y_) in zip(test_results, test_labels)]
  134. accuracy = sum(correct) / len(correct)
  135. print("Test accuracy is: ", accuracy)

TensorFlow数据集(二)——数据集的高层操作的更多相关文章

  1. 一个简单的TensorFlow可视化MNIST数据集识别程序

    下面是TensorFlow可视化MNIST数据集识别程序,可视化内容是,TensorFlow计算图,表(loss, 直方图, 标准差(stddev)) # -*- coding: utf-8 -*- ...

  2. 深入浅出TensorFlow(二):TensorFlow解决MNIST问题入门

    2017年2月16日,Google正式对外发布Google TensorFlow 1.0版本,并保证本次的发布版本API接口完全满足生产环境稳定性要求.这是TensorFlow的一个重要里程碑,标志着 ...

  3. 深度学习之 TensorFlow(二):TensorFlow 基础知识

    1.TensorFlow 系统架构: 分为设备层和网络层.数据操作层.图计算层.API 层.应用层.其中设备层和网络层.数据操作层.图计算层是 TensorFlow 的核心层. 2.TensorFlo ...

  4. MySQL 系列(二) 你不知道的数据库操作

    第一篇:MySQL 系列(一) 生产标准线上环境安装配置案例及棘手问题解决 第二篇:MySQL 系列(二) 你不知道的数据库操作 本章内容: 查看\创建\使用\删除 数据库 用户管理及授权实战 局域网 ...

  5. C++使用VARIANT实现二维数组的操作

    C++使用VARIANT实现二维数组的操作 VARIANT变量是COM组件之间互相通信的重要的参数变量之一,它可以容纳多种不同的类型,如short.long.double等,包括各类指针和数组.组件之 ...

  6. SSH原理与运用(二):远程操作与端口转发

    SSH原理与运用(二):远程操作与端口转发 作者:阮一峰 (Image credit: Tony Narlock) 七.远程操作 SSH不仅可以用于远程主机登录,还可以直接在远程主机上执行操作. 上一 ...

  7. IDEA环境下GIT操作浅析之二-idea下分支操作相关命令

    上次写到<idea下仓库初始化与文件提交涉及到的基本命令>,今天我们继续写IDEA环境下GIT操作之二--idea下分支操作相关命令以及分支创建与合并. 1.idea 下分支操作相关命令 ...

  8. Java从零开始学二十九(大数操作(BigIntger、BigDecimal)

    一.BigInteger 如果在操作的时候一个整型数据已经超过了整数的最大类型长度long的话,则此数据就无法装入,所以,此时要使用BigInteger类进行操作. 不可变的任意精度的整数.所有操作中 ...

  9. 04-树7 二叉搜索树的操作集(30 point(s)) 【Tree】

    04-树7 二叉搜索树的操作集(30 point(s)) 本题要求实现给定二叉搜索树的5种常用操作. 函数接口定义: BinTree Insert( BinTree BST, ElementType ...

  10. 二、Docker基础操作

    原文:二.Docker基础操作 一.下载镜像 命令:docker pull xxxxxx(镜像名) docker pull training/weapp 二.运行镜像 docker run -d -P ...

随机推荐

  1. define tensorflow and run it

    import tensorflow as tf a, b, c, d, e = tf.constant(5, name='input_a'), tf.constant(6, name='input_b ...

  2. Hadoop实战-MapReduce之WordCount(五)

    环境介绍: 主服务器ip:192.168.80.128(master)  NameNode  SecondaryNameNode ResourceManager 从服务器ip:192.168.80.1 ...

  3. SQL JOIN--初级篇

    写在前面的话: 以下是最简单的join原理,为后面的大数据分布式join做概念复习和知识铺垫: 有时为了得到完整的结果,我们需要从两个或更多的表中获取结果.我们就需要执行 join. JOIN: 如果 ...

  4. appium(8)-locator strategies

    locator strategies Finding and interacting with elements Appium supports a subset of the WebDriver l ...

  5. Nginx+Tomcat搭建负载均衡集群

    Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器, 使用 Nginx 可以使得程序在高并发的情况下依旧可以保持良好的性能.使用 Nginx+Tomcat ...

  6. CORS 理解(不要那么多术语)

    摘要 谈到跨域,不论前端还是后端,多少有点谈虎色变,面试中也常会问到这些问题,浏览器和服务器端到底怎么做才能跨域,他们都做了什么? 同源 vs 跨域 同源,字面意义是相同的源头,即同一个web服务器( ...

  7. Codeforces Round #402 (Div. 2) D String Game —— 二分法

    D. String Game time limit per test 2 seconds memory limit per test 512 megabytes input standard inpu ...

  8. Codeforces Round #371 (Div. 2) C. Sonya and Queries —— 二进制压缩

    题目链接:http://codeforces.com/contest/714/problem/C C. Sonya and Queries time limit per test 1 second m ...

  9. 人生苦短之Python装饰器

    在Python中函数也是一个对象,我们可以获得函数对象,然后执行函数 def func(): print('I am very good') a = func a 如果我们要是想增强这个函数呢?比如给 ...

  10. UITabBar 设置选中、未选中状态下title的字体颜色

    一.如果只是设置选中状态的字体颜色,使用 tintColor  就可以达到效果 self.tabBar.tintColor = [UIColor redColor]; 二.但如果要将未选中状态和选中状 ...