TFRecord读写简介+Demo 基于Ubuntu18.04+Tensorflow1.12 无WARNING
简介
- TFRecord是TensorFlow官方推荐使用的数据格式化存储工具。
- 它规范了数据的读写方式。
- 只要生成一次TFRecord,之后的数据读取和加工处理的效率都会得到提高。
将图片转换成TFRecord
本例,将fashion-MNIST数据转换成TFRecord,需要先下载fashion数据集到当前目录下,参考:https://github.com/zalandoresearch/fashion-mnist/tree/master/data/fashion
import numpy as np
import tensorflow as tf
import gzip
import os fashion_mnist_directory = './data/fashion/' def load_mnist(path, kind='train'):
labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind)
images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath:
labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8) with gzip.open(images_path, 'rb') as imgpath:
images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(-1, 784) print(labels_path, "shape =", labels.shape)
print(images_path, "shape =", images.shape) return images, labels def make_example(image, label):
return tf.train.Example(features=tf.train.Features(feature={
'image_raw' : tf.train.Feature(bytes_list=tf.train.BytesList(value=[image.tobytes()])),
'label' : tf.train.Feature(int64_list=tf.train.Int64List(value=[int(label) ])) })) def write_tfrecord(images, labels, filename):
writer = tf.python_io.TFRecordWriter(filename)
for image, label, k in zip(images, labels, range(labels.shape[0])):
exam = make_example(image, label)
writer.write(exam.SerializeToString())
if (k%100 == 0):
print("\rwriting", filename, "%6.2f%% complited." %(100.0*(k+1)/labels.shape[0]), end='') print("\rwriting", filename, "%6.2f%% complited." %(100.0))
writer.close() def main():
train_images, train_labels = load_mnist(fashion_mnist_directory, 'train')
test_images, test_labels = load_mnist(fashion_mnist_directory, 't10k') write_tfrecord(train_images, train_labels, 'fashion_mnist_train.tfrecords')
write_tfrecord(test_images, test_labels, 'fashion_mnist_test.tfrecords') if __name__ == '__main__':
main()
读取TFRecord数据来训练
以下代码读取TFRecord数据用于训练,改代码改编自官方例程:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/how_tos/reading_data
原始代码运行时报错,已修复。
注意:在这个例子中,_, loss_value = sess.run([train_op, loss]),只执行一次Batch Input,无论[]中是什么,有多少个操作。
import argparse
import os.path
import sys
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import mnist FLAGS = None TRAIN_FILE = 'fashion_mnist_train.tfrecords'
VALIDATION_FILE = 'fashion_mnist_test.tfrecords' def decode(serialized_example):
features = tf.parse_single_example(serialized_example,
features={'image_raw': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)})
image = tf.decode_raw(features['image_raw'], tf.uint8)
image.set_shape((mnist.IMAGE_PIXELS))
label = tf.cast(features['label'], tf.int32)
return image, label def augment(image, label):
"""Placeholder for data augmentation."""
# OPTIONAL: Could reshape into a 28x28 image and apply distortions here.
return image, label def normalize(image, label):
"""Convert `image` from [0, 255] -> [-0.5, 0.5] floats."""
image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
return image, label def inputs(train, batch_size, num_epochs):
"""Reads input data"""
if not num_epochs:
num_epochs = None
filename = os.path.join(FLAGS.train_dir, TRAIN_FILE if train else VALIDATION_FILE) with tf.name_scope('input'):
dataset = tf.data.TFRecordDataset(filename)
dataset = dataset.map(decode)
dataset = dataset.map(augment)
dataset = dataset.map(normalize)
dataset = dataset.shuffle(1000 + 3 * batch_size)
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
iterator = dataset.make_one_shot_iterator()
return iterator.get_next() def run_training():
with tf.Graph().as_default():
image_batch, label_batch = inputs(train=True,
batch_size=FLAGS.batch_size,
num_epochs=FLAGS.num_epochs)
logits = mnist.inference(image_batch, FLAGS.hidden1, FLAGS.hidden2)
loss = mnist.loss(logits, label_batch)
train_op = mnist.training(loss, FLAGS.learning_rate) init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer()) with tf.Session() as sess:
sess.run(init_op)
try:
step = 0
while True: # Train until OutOfRangeError
start_time = time.time()
_, loss_value = sess.run([train_op, loss])
duration = time.time() - start_time
if step % 100 == 0:
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))
step += 1
except tf.errors.OutOfRangeError:
print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step)) def main(_):
run_training() if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--learning_rate', type=float, default=0.01, help='Initial learning rate.')
parser.add_argument('--num_epochs', type=int, default=2, help='Number of epochs to run trainer.')
parser.add_argument('--hidden1', type=int, default=128, help='Number of units in hidden layer 1.')
parser.add_argument('--hidden2', type=int, default=32, help='Number of units in hidden layer 2.')
parser.add_argument('--batch_size', type=int, default=100, help='Batch size.')
parser.add_argument('--train_dir', type=str, default='./', help='Directory with the training data.')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
参考了:
- https://blog.csdn.net/gg_18826075157/article/details/78449104
- https://github.com/zalandoresearch/fashion-mnist/blob/master/utils/mnist_reader.py
TFRecord读写简介+Demo 基于Ubuntu18.04+Tensorflow1.12 无WARNING的更多相关文章
- kubeadm部署1.17.3[基于Ubuntu18.04]
基于 Ubuntu18.04 使用 kubeadm 部署Kubernetes 1.17.3 高可用集群 环境 所有节点初始化 # cat <<EOF>> /etc/hosts ...
- 基于Ubuntu18.04一站式部署(python-mysql-redis-nginx)
基于Ubuntu18.04一站式部署 Python3.6.8的安装 1. 安装依赖 ~$ sudo apt install openssl* zlib* 2. 安装python3.6.8(个人建议从官 ...
- ubuntu18.04系统下无外部显示问题解决
记录一下自己作死过程. 由于学习的需要,在windows10下装了ubuntu18.04系统,第一次装这个系统时,也出现了无外部显示,那时候是老师帮忙搞好的,当时没太在意,只是走马关花的看了老师操作了 ...
- Kubernetes 基于 ubuntu18.04 手工部署 (k8s)
由于工作的需要, 手工部署一个 Kubernetes 环境(k8s).(以前都是云上搞定,拿来用) 习惯把这种工作记录下来,自己备查也和别人分享 网上相关文章很多, 我也参考了很多,这里推荐一个 链接 ...
- TensorFlow从入门到理解(一):搭建开发环境【基于Ubuntu18.04】
*注:教程及本文章皆使用Python3+语言,执行.py文件都是用终端(如果使用Python2+和IDE都会和本文描述有点不符) 一.安装,测试,卸载 TensorFlow官网介绍得很全面,很完美了, ...
- 腾讯云服务器ubuntu18.04部署禅道系统
踩了不少坑,记录一下. 基于ubuntu18.04 一开始按照网上的攻略下载安装包 ZenTaoPMS.9.8.3.zbox_64.tar.gz,通过FileZilla传到linux的/opt下面,解 ...
- 【Tool】---ubuntu18.04配置oh-my-zsh工具
作为Linux忠实用户,应该没有人不知道bash shell工具了吧,其实除了bash还有许多其他的工具,zsh就是一款很好得选择,基于zsh shell得基础之上,oh-my-zsh工具更是超级利器 ...
- ubuntu18.04下搭建深度学习环境anaconda2+ cuda9.0+cudnn7.0.5+tensorflow1.7【原创】【学习笔记】
PC:ubuntu18.04.i5.七彩虹GTX1060显卡.固态硬盘.机械硬盘 作者:庄泽彬(欢迎转载,请注明作者) 说明:记录在ubuntu18.04环境下搭建深度学习的环境,之前安装了cuda9 ...
- tensorflow/pytorch/mxnet的pip安装,非源代码编译,基于cuda10/cudnn7.4.1/ubuntu18.04.md
os安装 目前对tensorflow和cuda支持最好的是ubuntu的18.04 ,16.04这种lts,推荐使用18.04版本.非lts的版本一般不推荐. Windows倒是也能用来装深度GPU环 ...
随机推荐
- vue3 自学(一)基础知识学习和搭建一个脚手架
两年前曾自学过几天vue,那时候版本还是vue2,但后来项目中一直没用到,当时也觉得学习成本太高,便没有继续学习下去.初学者可以看下链接文章以前的吐槽~~ 学习 Vue ,从入门到放弃 最近部门决定升 ...
- Python基础之tabview
以前写过界面,但是没有记录下来,以至于现在得从头学习一次,论做好笔记的重要性. 现在学习的是怎么写一个tabview出来,也就是用tkinter做一个界面切换的效果.参考链接:https://blog ...
- python 管理工具
pip 包管理工具 virtualenv 虚拟环境管理工具 切换目录 virtualenvwrapper 虚拟环境管理工具加强版 pyenv python版本管理工具 修改环境变量 pyenv-vir ...
- Django orm 常用查询筛选总结
本文主要列举一下django orm中的常用查询的筛选方法: 大于.大于等于 小于.小于等于 in like is null / is not null 不等于/不包含于 其他模糊查询 model: ...
- 🔥 LeetCode 热题 HOT 100(41-50)
102. 二叉树的层序遍历 思路:使用队列. /** * Definition for a binary tree node. * public class TreeNode { * int val; ...
- 2020国防科大综述:3D点云深度学习—综述(点云形状识别部分)
目录 摘要 1.引言: 2.背景 2.1 数据集 2.2评价指标 3.3D形状分类 3.1基于多视图的方法 3.2基于体素的方法 3.3基于点的方法 3.3.1 点对多层感知机方法 3.3.2基于卷积 ...
- 【爬虫系列】1. 无事,Python验证码识别入门
最近在导入某站数据(正经需求),看到他们的登录需要验证码, 本来并不想折腾的,然而Cookie有效期只有一天. 已经收到了几次夜间报警推送之后,实在忍不住. 得嘞,还是得研究下模拟登录. 于是,秃头了 ...
- SpringBoot系列——动态定时任务
前言 定时器是我们项目中经常会用到的,SpringBoot使用@Scheduled注解可以快速启用一个简单的定时器(详情请看我们之前的博客<SpringBoot系列--定时器>),然而这种 ...
- C++小知识——显示VS大括号/花括号折叠按钮
这个功能默认是关闭的,打开路径如下: 将大纲语句块改为"True" 这个功能其实很有必要真不知道为啥默认要关闭这个功能. 站在巨人的肩膀上的思想,其实已经在互联网程序员之间深入人心 ...
- LinuxDHCP配置
目录 一.DHCP服务 1.1.了解DHCP服务 1.2.使用DHCP的好处 1.3.DHCP的分配方式 1.4.DHCP的租约过程 客户机请求IP地址 重新登录 更新租约 1.5.使用DHCP动态配 ...