gpt4 book ai didi

python - 如何使用存储在 TFRecords 文件中的图像为 Estimator 构建 input_fn

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:57 25 4
gpt4 key购买 nike

是否有示例说明如何为图像分类模型构建tf.contrib.learn.Estimator 所需的input_fn?我的图像存储在多个 TFRecords 文件中。

使用 tf.contrib.learn.read_batch_record_features,我能够生成成批的编码图像字符串。但是,我没有看到将这些字符串转换为图像的简单方法。

最佳答案

引用 here您可以对存储在 train.tfrecordstest.tfrecords 中的 mnistfashion-mnist 数据集使用类似下面的内容.

tfrecords 的转换由代码here 完成并且您需要有一个解析器来取回原始图像和标签。

def parser(serialized_example):
"""Parses a single tf.Example into image and label tensors."""
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([28 * 28])

# Normalize the values of the image from the range [0, 255] to [-0.5, 0.5]
image = tf.cast(image, tf.float32) / 255 - 0.5
label = tf.cast(features['label'], tf.int32)
return image, label

有了解析器之后,剩下的就很简单了,你只需要调用 TFRecordDataset(train_filenames) 然后将解析器函数映射到每个元素,这样你就会得到一个图像和标签作为输出。

# Keep list of filenames, so you can input directory of tfrecords easily
training_filenames = ["data/train.tfrecords"]
test_filenames = ["data/test.tfrecords"]

# Define the input function for training
def train_input_fn():
# Import MNIST data
dataset = tf.contrib.data.TFRecordDataset(train_filenames)

# Map the parser over dataset, and batch results by up to batch_size
dataset = dataset.map(parser, num_threads=1, output_buffer_size=batch_size)
dataset = dataset.batch(batch_size)
dataset = dataset.repeat()
iterator = dataset.make_one_shot_iterator()

features, labels = iterator.get_next()

return features, labels

关于python - 如何使用存储在 TFRecords 文件中的图像为 Estimator 构建 input_fn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com