TensorFlow数据集(二)——数据集的高层操作
参考书
《TensorFlow:实战Google深度学习框架》(第2版)
一个使用数据集进行训练和测试的完整例子。
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- # coding=utf-8
- """
- @author: Li Tian
- @contact: 694317828@qq.com
- @software: pycharm
- @file: dataset_test5.py
- @time: 2019/2/12 13:45
- @desc: 使用数据集实现数据输入流程
- """
- import tensorflow as tf
- from figuredata_deal.figure_deal_test2 import preprocess_for_train
- # 列举输入文件。训练和测试使用不同的数据
- train_files = tf.train.match_filenames_once('./train_file-*')
- test_files = tf.train.match_filenames_once('./test_files-*')
- # 定义parser方法从TFRecord中解析数据。这里假设image中存储的是图像的原始数据,
- # label为该样例所对应的标签。height、width和channels给出了图片的维度。
- def parser(record):
- features = tf.parse_single_example(
- record,
- features={
- 'image': tf.FixedLenFeature([], tf.string),
- 'label': tf.FixedLenFeature([], tf.int64),
- 'height': tf.FixedLenFeature([], tf.int64),
- 'width': tf.FixedLenFeature([], tf.int64),
- 'channels': tf.FixedLenFeature([], tf.int64),
- }
- )
- # 从原始图像数据解析出像素矩阵,并根据图像尺寸还原图像。
- decoded_image = tf.decode_raw(features['image'], tf.uint8)
- decoded_image.set_shape([features['height'], features['width'], features['channels']])
- label = features['label']
- return decoded_image, label
- # 定义神经网络输入层图片的大小
- image_size = 299
- # 定义组合数据batch的大小
- batch_size = 100
- # 定义随机打乱数据时buffer的大小
- shuffle_buffer = 10000
- # 定义读取训练数据的数据集
- dataset = tf.data.TFRecordDataset(train_files)
- dataset = dataset.map(parser)
- # 对数据依次进行预处理、shuffle和batching操作。preprocess_for_train为前面介绍的
- # 图像预处理程序。因为上一个map得到的数据集中提供了decoded_image和label两个结果,所以这个
- # map需要提供一个有2个参数的函数来处理数据。在下面的代码中,lambda中的image代表的就是第一个map返回的
- # decoded_image,label代表的就是第一个map返回的label。在这个lambda表达式中我们首先将decoded_image
- # 在传入preprocess_for_train来进一步对图像数据进行预处理。然后再将处理好的图像和label组成最终的输出。
- dataset = dataset.map(
- lambda image, label: (
- preprocess_for_train(image, image_size, image_size, None), label
- )
- )
- dataset = dataset.shuffle(shuffle_buffer).batch(batch_size)
- # 重复NUM_EPOCHS个epoch。在前面TRAINING_ROUNDS指定了训练的轮数,
- # 而这里指定了整个数据集重复的次数,它也间接地确定了训练的论述。
- NUM_EPOCHS = 10
- dataset = dataset.repeat(NUM_EPOCHS)
- # 定义数据集迭代器。虽然定义数据集的时候没直接使用placeholder来提供文件地址,但是
- # tf.train.match_filenames_once方法得到的结果和与placeholder的机制类似,也需要初始化。
- # 所以这里使用的是initializable_iterator
- iterator = dataset.make_initializable_iterator()
- image_batch, label_batch = iterator.get_next()
- # 定义神经网络的结果以及优化过程。这里与前面的相同。
- learning_rate = 0.01
- logit = inference(image_batch)
- loss = calc_loss(logit, label_batch)
- train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
- # 定义测试用的Dataset。与训练时不同,测试数据的Dataset不需要经过随机翻转等预处理操作,
- # 也不需要打乱顺序和重复多个epoch。这里使用于训练数据相同的parser进行解析,调整分辨率
- # 到网络输入层大小,然后直接进行batching操作。
- test_dataset = tf.data.TFRecordDataset(test_files)
- test_dataset = test_dataset.map(parser).map(
- lambda image, label: (
- tf.image.resize_images(image, [image_size, image_size]), label
- )
- )
- test_dataset = test_dataset.batch(batch_size)
- # 定义测试数据上的迭代器
- test_iterator = test_dataset.make_initializable_iterator()
- test_image_batch, test_label_batch = test_iterator.get_next()
- # 定义预测结果为logit值最大的分类
- test_logit = inference(test_image_batch)
- predictions = tf.argmax(test_logit, axis=-1, output_type=tf.int32)
- # 声明会话并运行神经网络的优化过程
- with tf.Session() as sess:
- # 初始化变量
- sess.run((
- tf.global_variables_initializer(),
- tf.local_variables_initializer()
- ))
- # 初始化训练数据的迭代器。
- sess.run(iterator.initializer)
- # 循环进行训练,知道数据集完成输入,抛出OutOfRangeError错误
- while True:
- try:
- sess.run(train_step)
- except tf.errors.OutOfRangeError:
- break
- # 初始化测试数据的迭代器
- sess.run(test_iterator.initializer)
- # 获取预测结果
- test_results = []
- test_labels = []
- while True:
- try:
- pred, label = sess.run([predictions, test_label_batch])
- test_results.extend(pred)
- test_labels.extend(label)
- except tf.errors.OutOfRangeError:
- break
- # 计算准确率
- correct = [float(y == y_) for (y, y_) in zip(test_results, test_labels)]
- accuracy = sum(correct) / len(correct)
- print("Test accuracy is: ", accuracy)
TensorFlow数据集(二)——数据集的高层操作的更多相关文章
- 一个简单的TensorFlow可视化MNIST数据集识别程序
下面是TensorFlow可视化MNIST数据集识别程序,可视化内容是,TensorFlow计算图,表(loss, 直方图, 标准差(stddev)) # -*- coding: utf-8 -*- ...
- 深入浅出TensorFlow(二):TensorFlow解决MNIST问题入门
2017年2月16日,Google正式对外发布Google TensorFlow 1.0版本,并保证本次的发布版本API接口完全满足生产环境稳定性要求.这是TensorFlow的一个重要里程碑,标志着 ...
- 深度学习之 TensorFlow(二):TensorFlow 基础知识
1.TensorFlow 系统架构: 分为设备层和网络层.数据操作层.图计算层.API 层.应用层.其中设备层和网络层.数据操作层.图计算层是 TensorFlow 的核心层. 2.TensorFlo ...
- MySQL 系列(二) 你不知道的数据库操作
第一篇:MySQL 系列(一) 生产标准线上环境安装配置案例及棘手问题解决 第二篇:MySQL 系列(二) 你不知道的数据库操作 本章内容: 查看\创建\使用\删除 数据库 用户管理及授权实战 局域网 ...
- C++使用VARIANT实现二维数组的操作
C++使用VARIANT实现二维数组的操作 VARIANT变量是COM组件之间互相通信的重要的参数变量之一,它可以容纳多种不同的类型,如short.long.double等,包括各类指针和数组.组件之 ...
- SSH原理与运用(二):远程操作与端口转发
SSH原理与运用(二):远程操作与端口转发 作者:阮一峰 (Image credit: Tony Narlock) 七.远程操作 SSH不仅可以用于远程主机登录,还可以直接在远程主机上执行操作. 上一 ...
- IDEA环境下GIT操作浅析之二-idea下分支操作相关命令
上次写到<idea下仓库初始化与文件提交涉及到的基本命令>,今天我们继续写IDEA环境下GIT操作之二--idea下分支操作相关命令以及分支创建与合并. 1.idea 下分支操作相关命令 ...
- Java从零开始学二十九(大数操作(BigIntger、BigDecimal)
一.BigInteger 如果在操作的时候一个整型数据已经超过了整数的最大类型长度long的话,则此数据就无法装入,所以,此时要使用BigInteger类进行操作. 不可变的任意精度的整数.所有操作中 ...
- 04-树7 二叉搜索树的操作集(30 point(s)) 【Tree】
04-树7 二叉搜索树的操作集(30 point(s)) 本题要求实现给定二叉搜索树的5种常用操作. 函数接口定义: BinTree Insert( BinTree BST, ElementType ...
- 二、Docker基础操作
原文:二.Docker基础操作 一.下载镜像 命令:docker pull xxxxxx(镜像名) docker pull training/weapp 二.运行镜像 docker run -d -P ...
随机推荐
- 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 ...
- Hadoop实战-MapReduce之WordCount(五)
环境介绍: 主服务器ip:192.168.80.128(master) NameNode SecondaryNameNode ResourceManager 从服务器ip:192.168.80.1 ...
- SQL JOIN--初级篇
写在前面的话: 以下是最简单的join原理,为后面的大数据分布式join做概念复习和知识铺垫: 有时为了得到完整的结果,我们需要从两个或更多的表中获取结果.我们就需要执行 join. JOIN: 如果 ...
- appium(8)-locator strategies
locator strategies Finding and interacting with elements Appium supports a subset of the WebDriver l ...
- Nginx+Tomcat搭建负载均衡集群
Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器, 使用 Nginx 可以使得程序在高并发的情况下依旧可以保持良好的性能.使用 Nginx+Tomcat ...
- CORS 理解(不要那么多术语)
摘要 谈到跨域,不论前端还是后端,多少有点谈虎色变,面试中也常会问到这些问题,浏览器和服务器端到底怎么做才能跨域,他们都做了什么? 同源 vs 跨域 同源,字面意义是相同的源头,即同一个web服务器( ...
- 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 ...
- 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 ...
- 人生苦短之Python装饰器
在Python中函数也是一个对象,我们可以获得函数对象,然后执行函数 def func(): print('I am very good') a = func a 如果我们要是想增强这个函数呢?比如给 ...
- UITabBar 设置选中、未选中状态下title的字体颜色
一.如果只是设置选中状态的字体颜色,使用 tintColor 就可以达到效果 self.tabBar.tintColor = [UIColor redColor]; 二.但如果要将未选中状态和选中状 ...