如何将 numpy 转换为 tfrecords 然后生成批次?
- 2025-03-21 09:06:00
- admin 原创
- 68
问题描述:
我的问题是如何从多个(或分片)tfrecords 获取批量输入。我已阅读示例https://github.com/tensorflow/models/blob/master/inception/inception/image_processing.py#L410。基本流程是,以训练集为例,(1) 首先生成一系列 tfrecords(例如,,,train-000-of-005
... train-001-of-005
),(2) 从这些文件名生成一个列表并将它们输入到tf.train.string_input_producer
队列中,(3) 同时生成一个tf.RandomShuffleQueue
来做其他事情,(4) 用来tf.train.batch_join
生成批量输入。
我认为这很复杂,我不确定这个过程的逻辑。就我而言,我有一个.npy
文件列表,我想生成分片的 tfrecords(多个独立的 tfrecords,而不仅仅是一个大文件)。每个文件都.npy
包含不同数量的正样本和负样本(2 个类)。一个基本方法是生成一个单独的大型 tfrecord 文件。但文件太大(~20Gb
)。所以我求助于分片的 tfrecords。有没有更简单的方法可以做到这一点?
解决方案 1:
整个过程使用 来简化Dataset API
。以下是两个部分:(1): Convert numpy array to tfrecords
和(2): read the tfrecords to generate batches
。
1.从 numpy 数组创建 tfrecords:
Example arrays:
inputs = np.random.normal(size=(5, 32, 32, 3))
labels = np.random.randint(0,2,size=(5,))
def npy_to_tfrecords(inputs, labels, filename):
with tf.io.TFRecordWriter(filename) as writer:
for X, y in zip(inputs, labels):
# Feature contains a map of string to feature proto objects
feature = {}
feature['X'] = tf.train.Feature(float_list=tf.train.FloatList(value=X.flatten()))
feature['y'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[y]))
# Construct the Example proto object
example = tf.train.Example(features=tf.train.Features(feature=feature))
# Serialize the example to a string
serialized = example.SerializeToString()
# write the serialized objec to the disk
writer.write(serialized)
npy_to_tfrecords(inputs, labels, 'numpy.tfrecord')
2.使用 Dataset API 读取 tfrecords:
filenames = ['numpy.tfrecord']
dataset = tf.data.TFRecordDataset(filenames)
# for version 1.5 and above use tf.data.TFRecordDataset
# example proto decode
def _parse_function(example_proto):
keys_to_features = {'X':tf.io.FixedLenFeature(shape=(32, 32, 3), dtype=tf.float32),
'y': tf.io.FixedLenFeature((), tf.int64, default_value=0)}
parsed_features = tf.io.parse_single_example(example_proto, keys_to_features)
return parsed_features['X'], parsed_features['y']
# Parse the record into tensors.
dataset = dataset.map(_parse_function)
# Generate batches
dataset = dataset.batch(5)
检查生成的批次是否正确:
for data in dataset:
break
np.testing.assert_allclose(inputs[0] ,data[0][0])
np.testing.assert_allclose(labels[0] ,data[1][0])
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD