在 keras 中处理数据集时进行批量预处理
Batch preprocessing when working on Datasets in keras
我有一些可变长度数据矩阵及其关联标签的示例,我想用它来训练 LSTM 网络。我知道我应该至少为每个批次填充数据样本(例如使用 keras.preprocessing.sequence.pad_sequences
)并且我成功地为网络提供了 numpy 数组,但我不知道如何使用 TFRecord 数据集.
我的TFRecord文件有一个典型的读取代码如下:
featuresDict = {'data': tf.FixedLenSequenceFeature([], dtype=tf.string),
'dataShape': tf.FixedLenSequenceFeature([], dtype=tf.int64),
'label': tf.FixedLenSequenceFeature([], dtype=tf.int64)
}
def parse_tfrecord(example):
context, features = tf.parse_single_sequence_example(example, sequence_features=featuresDict)
label = features['label']
data_shape = features['dataShape']
data = tf.decode_raw(features['data'], tf.int64)
data = tf.reshape(data, data_shape)
return label, data
def DataGenerator(fileName, numEpochs=None, batchSize=None):
dataset = tf.data.TFRecordDataset(fileName, compression_type='GZIP')
dataset = dataset.map(parse_tfrecord)
dataset = dataset.batch(batchSize)
dataset = dataset.repeat(numEpochs)
return dataset
我可以解析每个示例并生成我的原始数据矩阵和标签。 DataGenerator 函数然后定义数据集并设置其批处理和重复功能。然后我创建一个 DataGenerator 对象并使用它来拟合我的模型:
train_data = DataGenerator(fileName='train.gz', numEpochs=epochs, batchSize=batch_size)
model.fit(train_data, epochs=epochs, steps_per_epoch = train_steps, ...)
padding函数可以放在代码的什么地方?一般来说,如果我想对数据集 API 进行批级预处理,我该怎么做?
一种方法是在写入 TFRecords 时在预处理期间填充序列。然后你可以使用与上面相同的代码。
但我建议 padded_batch,它的工作原理类似于 Keras 序列预处理。
如果维度已知(padded_shapes 是某个常量),序列将填充到该常量。否则,它们被填充到最长的序列。
我有一些可变长度数据矩阵及其关联标签的示例,我想用它来训练 LSTM 网络。我知道我应该至少为每个批次填充数据样本(例如使用 keras.preprocessing.sequence.pad_sequences
)并且我成功地为网络提供了 numpy 数组,但我不知道如何使用 TFRecord 数据集.
我的TFRecord文件有一个典型的读取代码如下:
featuresDict = {'data': tf.FixedLenSequenceFeature([], dtype=tf.string),
'dataShape': tf.FixedLenSequenceFeature([], dtype=tf.int64),
'label': tf.FixedLenSequenceFeature([], dtype=tf.int64)
}
def parse_tfrecord(example):
context, features = tf.parse_single_sequence_example(example, sequence_features=featuresDict)
label = features['label']
data_shape = features['dataShape']
data = tf.decode_raw(features['data'], tf.int64)
data = tf.reshape(data, data_shape)
return label, data
def DataGenerator(fileName, numEpochs=None, batchSize=None):
dataset = tf.data.TFRecordDataset(fileName, compression_type='GZIP')
dataset = dataset.map(parse_tfrecord)
dataset = dataset.batch(batchSize)
dataset = dataset.repeat(numEpochs)
return dataset
我可以解析每个示例并生成我的原始数据矩阵和标签。 DataGenerator 函数然后定义数据集并设置其批处理和重复功能。然后我创建一个 DataGenerator 对象并使用它来拟合我的模型:
train_data = DataGenerator(fileName='train.gz', numEpochs=epochs, batchSize=batch_size)
model.fit(train_data, epochs=epochs, steps_per_epoch = train_steps, ...)
padding函数可以放在代码的什么地方?一般来说,如果我想对数据集 API 进行批级预处理,我该怎么做?
一种方法是在写入 TFRecords 时在预处理期间填充序列。然后你可以使用与上面相同的代码。
但我建议 padded_batch,它的工作原理类似于 Keras 序列预处理。 如果维度已知(padded_shapes 是某个常量),序列将填充到该常量。否则,它们被填充到最长的序列。