简介

  • 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的更多相关文章

  1. kubeadm部署1.17.3[基于Ubuntu18.04]

    基于 Ubuntu18.04 使用 kubeadm 部署Kubernetes 1.17.3 高可用集群 环境 所有节点初始化 # cat <<EOF>> /etc/hosts ...

  2. 基于Ubuntu18.04一站式部署(python-mysql-redis-nginx)

    基于Ubuntu18.04一站式部署 Python3.6.8的安装 1. 安装依赖 ~$ sudo apt install openssl* zlib* 2. 安装python3.6.8(个人建议从官 ...

  3. ubuntu18.04系统下无外部显示问题解决

    记录一下自己作死过程. 由于学习的需要,在windows10下装了ubuntu18.04系统,第一次装这个系统时,也出现了无外部显示,那时候是老师帮忙搞好的,当时没太在意,只是走马关花的看了老师操作了 ...

  4. Kubernetes 基于 ubuntu18.04 手工部署 (k8s)

    由于工作的需要, 手工部署一个 Kubernetes 环境(k8s).(以前都是云上搞定,拿来用) 习惯把这种工作记录下来,自己备查也和别人分享 网上相关文章很多, 我也参考了很多,这里推荐一个 链接 ...

  5. TensorFlow从入门到理解(一):搭建开发环境【基于Ubuntu18.04】

    *注:教程及本文章皆使用Python3+语言,执行.py文件都是用终端(如果使用Python2+和IDE都会和本文描述有点不符) 一.安装,测试,卸载 TensorFlow官网介绍得很全面,很完美了, ...

  6. 腾讯云服务器ubuntu18.04部署禅道系统

    踩了不少坑,记录一下. 基于ubuntu18.04 一开始按照网上的攻略下载安装包 ZenTaoPMS.9.8.3.zbox_64.tar.gz,通过FileZilla传到linux的/opt下面,解 ...

  7. 【Tool】---ubuntu18.04配置oh-my-zsh工具

    作为Linux忠实用户,应该没有人不知道bash shell工具了吧,其实除了bash还有许多其他的工具,zsh就是一款很好得选择,基于zsh shell得基础之上,oh-my-zsh工具更是超级利器 ...

  8. ubuntu18.04下搭建深度学习环境anaconda2+ cuda9.0+cudnn7.0.5+tensorflow1.7【原创】【学习笔记】

    PC:ubuntu18.04.i5.七彩虹GTX1060显卡.固态硬盘.机械硬盘 作者:庄泽彬(欢迎转载,请注明作者) 说明:记录在ubuntu18.04环境下搭建深度学习的环境,之前安装了cuda9 ...

  9. 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环 ...

随机推荐

  1. java开源项目学习

    http://jeecg-boot.mydoc.io/ 在线文档已切换至新地址: http://doc.jeecg.com Jeecg-Boot 是一款基于SpringBoot+代码生成器的快速开发平 ...

  2. odoo里面的read_group写法

    #计算数task_count = fields.Integer(compute='_compute_task_count', string="Task Count")def _co ...

  3. odoo12学习之javascript

    本文来源:https://www.jianshu.com/p/1a47fac01077 Odoo12 Javascript 参考指南   本文介绍了odoo javascript框架.从代码行的角度来 ...

  4. 使用adb如何批量给设备安装apk

    win系统 1.首先我们需要在本地建一个文件夹apks,然后把所要安装的apk放进去 2.打开dos窗口使用for循环进行安装即可(前提你的电脑已经连接上了设备,输入adb devices可查看) f ...

  5. 利用LRU策略实现Axios请求缓存

    业务场景 前一段时间刚做完一个项目,先说一下业务场景,有别于其他的前端项目,这次的项目是直接调用第三方服务的接口,而我们的服务端只做鉴权和透传,第三方为了灵活,把接口拆的很零散,所以这个项目就像扔给你 ...

  6. xss常见方式

    1.<script>alert(1)</script> 2.源码第一个,[<]被转义,因此在第二个里 "><script>alert(1)&l ...

  7. 自学linux——6.安全外壳协议(ssh服务)

    ssh服务 ssh(secure shell)安全外壳协议:远程连接协议,远程文件传输协议 1.协议使用端口号默认:22 若要修改,则修改ssh服务的配置文件/etc/ssh/ssh_config a ...

  8. 2020年度钻石C++C学习笔记(3)--《博学谷》

    1.Unix/Linux操作系统介绍 1.1 操作系统的作用 1.1.1 操作系统的目标 l 方便:使计算机系统易于使用 l 有效:以更有效的方式使用计算机系统资源 l 扩展:方便用户有效开发.测试和 ...

  9. Upload-labs 文件上传靶场通关攻略(上)

    Upload-labs 文件上传靶场通关攻略(上) 文件上传是Web网页中常见的功能之一,通常情况下恶意的文件上传,会形成漏洞. 逻辑是这样的:用户通过上传点上传了恶意文件,通过服务器的校验后保存到指 ...

  10. JCE加密和解密 bouncycastle

    https://blog.csdn.net/weixin_43935907/article/details/89155617 https://blog.csdn.net/qq_29583513/art ...