Tensorflow 2.0:如何从 MapDataset(从 TFRecord 读取后)转换为一些可以输入到 model.fit 的结构

Alb*_*o A 4 python tensorflow tfrecord

我将训练和验证数据存储在两个单独的 TFRecord 文件中,其中存储了 4 个值:信号 A(float32 形状(150,)),信号 B(float32 形状(150,)),标签(标量 int64), id(字符串)。我的阅读解析功能是:

def _parse_data_function(sample_proto):

    raw_signal_description = {
        'label': tf.io.FixedLenFeature([], tf.int64),
        'id': tf.io.FixedLenFeature([], tf.string),
    }

    for key, item in SIGNALS.items():
        raw_signal_description[key] = tf.io.FixedLenFeature(item, tf.float32)

    # Parse the input tf.Example proto using the dictionary above.
    return tf.io.parse_single_example(sample_proto, raw_signal_description)
Run Code Online (Sandbox Code Playgroud)

其中SIGNALS是字典映射信号名称->信号形状。然后,我阅读了原始数据集:

training_raw = tf.data.TFRecordDataset(<path to training>), compression_type='GZIP')
val_raw = tf.data.TFRecordDataset(<path to validation>), compression_type='GZIP')
Run Code Online (Sandbox Code Playgroud)

并使用 map 来解析值:

training_data = training_raw.map(_parse_data_function)
val_data = val_raw.map(_parse_data_function)
Run Code Online (Sandbox Code Playgroud)

显示training_dataor的标题val_data,我得到:

<MapDataset shapes: {Signal A: (150,), Signal B: (150,), id: (), label: ()}, types: {Signal A: tf.float32, Signal B: tf.float32, id: tf.string, label: tf.int64}>

这几乎和预期的一样。我还检查了一些值的一致性,它们似乎是正确的。

现在,我的问题是:我如何从 MapDataset 中获得类似字典的结构,以获得可以作为模型输入的内容?

我的模型的输入是对(信号 A,标签),但将来我也会使用信号 B。

对我来说,最简单的方法似乎是在我想要的元素上创建一个生成器。就像是:

def data_generator(mapdataset):
    for sample in mapdataset:
        yield (sample['Signal A'], sample['label'])
Run Code Online (Sandbox Code Playgroud)

然而,用这种方法,我失去的数据集,如配料的一些方便,而且也不清楚如何使用相同的方法对validation_data的paramenter model.fit。理想情况下,我只会在地图表示和数据集表示之间进行转换,它在信号 A 张量和标签对上进行迭代。

编辑:我的最终产品应该是类似标题的东西: <TensorSliceDataset shapes: ((150,), ()), types: (tf.float32, tf.int64)> 但不一定TensorSliceDataset

xdu*_*ch0 5

您可以简单地在 parse 函数中执行此操作。例如:

def _parse_data_function(sample_proto):

    raw_signal_description = {
        'label': tf.io.FixedLenFeature([], tf.int64),
        'id': tf.io.FixedLenFeature([], tf.string),
    }

    for key, item in SIGNALS.items():
        raw_signal_description[key] = tf.io.FixedLenFeature(item, tf.float32)

    # Parse the input tf.Example proto using the dictionary above.
    parsed = tf.io.parse_single_example(sample_proto, raw_signal_description)

    return parsed['Signal A'], parsed['label']
Run Code Online (Sandbox Code Playgroud)

如果您在 上使用map此函数TFRecordDataset,您将拥有元组 数据集(signal_a, label)而不是字典数据集。你应该可以model.fit直接把它放进去。