TFRecord 统一数据格式

1.将输入数据保存为TFRecord格式

__author__ = 'ding'
'''
将数据保存为TFRecord格式
'''
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 = 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

# 输出文件的路径
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()

在工程的/path/to目录下生成一个output.tfrecord文件,这个文件就是输入数据的TFRecord格式文件
此处注意 不要遗漏tf.train.Features后的s,为了不必要的错误,需要仔细核对(掉过坑,所以提醒。。)

2.读取TFRecord文件中的数据

__author__ = 'ding'
'''
读取TFRecord文件中的数据
'''
import tensorflow as tf

# 创建一个reader来读取TFRecord文件中的样例
reader = tf.TFRecordReader()

# 创建一个列队来维护输入文件列表
filename_queue = tf.train.string_input_producer(['./path/to/output.tfrecords'])
# 从文件中读取一个样例,也可以使用read_up_to函数一次读取多个样例
_,serialized_example = reader.read(filename_queue)

# 解析读入的一个样例,如果需要解析多个样例,也可以使用parse_example函数
features = tf.parse_single_example(
    serialized_example,
    features={
        # 解析方法与保存方法应该一致,避免报错
        # TensorFlow 有两种属性解析的方法,
        # tf.FixedLenGeature, 解析结果为一个Tensor
        # tf.VarLenFrature,解析结果为SparseTensor,用于稀疏处理
        'image_raw':tf.FixedLenFeature([],tf.string),
        'pixels':tf.FixedLenFeature([],tf.int64),
        'label':tf.FixedLenFeature([],tf.int64)
    })

# tf.decode_raw 可以将字符串解析成图像对应的像素数组
images = tf.decode_raw(features['image_raw'],tf.uint8)
labels = tf.cast(features['label'],tf.int32)
pixels = tf.cast(features['pixels'],tf.int32)

sess = tf.Session()
# 启用多线程处理
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,coord=coord)

# 每次运行可以读取TFRecord文件中的一个样例,当所有样例读完之后,此样例中程序会在重头读取
for i in range(10):
    images,labels,pixels = sess.run([images,labels,pixels])
has invalid type <class 'numpy.ndarray'>, must be a string or Tensor
***原因:变量命名重复了

猜你喜欢

转载自blog.csdn.net/u014258362/article/details/80676237
今日推荐