《TensorFlow实战Google深度学习框架第2版》教材中的样例代码,由于tensorflow版本、运行过程的修改、敲码过程中的失误、教材样例自带的错误等原因,可能会导致代码与教材不一致或者不能运行成功,仅供参考。
第7章 图像数据处理
- 7.1 将MNIST输入数据转化为TFRecord 的格式
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
# 生成整数型的属性
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# 生成字符串型的属性
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
# 读取mnist训练数据
mnist = input_data.read_data_sets("/path/to/MNIST_data", dtype=tf.uint8, one_hot=True)
images = mnist.train.images
# 训练数据所对应的正确答案,可以作为一个属性保存在TFRecord中
labels = mnist.train.labels
# 训练数据的图像分辨率,这可以作为Example中的一个属性
pixels = images.shape[1]
num_examples = mnist.train.num_examples
# 输出TFRecord文件的地址
filename = "/path/to/output.tfrecords"
# 创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
# 将图像矩阵转化成一个字符串
image_raw = images[index].tostring()
# 将一个样例转化为Example Protocol Buffer,并将所有的信息写入这个数据结构
example = tf.train.Example(features=tf.train.Features(feature={
'pixels': _int64_feature(pixels),
'label': _int64_feature(np.argmax(labels[index])),
'image_raw': _bytes_feature(image_raw)}))
# 将一个Example写入TFRecord文件
writer.write(example.SerializeToString())
writer.close()
- 7.1 读取TFRecord文件中的数据
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
# 创建一个reader来读取TFRecord文件中的样例
reader = tf.TFRecordReader()
# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer(["output.tfrecords"])
_, serialized_example = reader.read(filename_queue)
# 解析读入的一个样例,如果需要解析多个样例,可以用parse_example函数
features = tf.parse_single_example(
serialized_example,
features={
# TensorFlow提供两种不同的属性解析方法
# 一种是方法是tf.FixedLenFeature,这种方法解析的结果为一个Tensor
# 另一种方法是tf.VarLenFeature,这种方法得到的解析结果为SparseTensor,用于处理稀疏数据
# 这里解析数据的格式需要和上面程序写入数据的格式一致
'image_raw': tf.FixedLenFeature([], tf.string),
'pixels': tf.FixedLenFeature([], tf.int64),
'label': tf.FixedLenFeature([],