【问题标题】:Training with tf.data API and sample weights使用 tf.data API 和样本权重进行训练
【发布时间】:2018-12-06 14:23:03
【问题描述】:

我所有的训练图像都在 tfrecords 文件中。现在它们以这样的标准方式使用:

dataset = dataset.apply(tf.data.experimental.map_and_batch(
            map_func=lambda x: preprocess(x, data_augmentation_options=data_augmentation), 
            batch_size=images_per_batch)

preprocess 返回解码后的图像和标签,它们都来自 tfrecord 文件。

现在是新情况。我还想要每个示例的样本权重。所以而不是

return image,label

在预处理中,应该是

return image, label, sample_weight

但是,这个 sample_weight 不在 tfrecord 文件中。它是在训练开始时根据每个类的示例数计算的。基本上它是一个 Python 字典 weights[label] = sample_weights。

问题是如何在 tf.data 管道中使用这些样本权重。因为 label 是一个张量,它不能用于索引 Python 字典。

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    您的问题有一些不清楚的地方,例如 x 是什么?如果您可以发布带有问题的完整代码示例,那就更好了。

    我假设 x 是带有图像和标签的张量。如果是这样,您可以使用 map 函数将样本权重的张量添加到数据集中。比如(请注意,此代码未经测试):

    def im_add_weight(image, label, sample_weight):
       #convert to tensor if they are not and make sure to us
       image= tf.convert_to_tensor(image, dtype= tf.float32)
       label = tf.convert_to_tensor(label, dtype= tf.float32)
       sample_weight = tf.convert_to_tensor(sample_weight, dtype= tf.float32)
       return image, label, sample_weight
    
    dataset = dataset .map(
    lambda image, label, sample_weight: tuple(tf.py_func(
        im_add_weight, [image, label,sample_weight], [tf.float32, tf.float32,tf.float32])))
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      相关资源
      最近更新 更多