【问题标题】:tensorflow: Combining to_categorical() with Datasets and map()tensorflow:结合 to_categorical() 与 Datasets 和 map()
【发布时间】:2021-09-13 18:20:26
【问题描述】:

简而言之,我正在努力尝试将 tf.data.Dataset 中的图像每像素类别掩码从整数类编码转换为 one-hot 编码。

考虑这里的图像分割 tensorflow 教程示例: https://www.tensorflow.org/tutorials/images/segmentation.

输入是图像,输出是每像素整数标记的类别掩码。在他们的示例中,掩码在每个像素处都有一个由整数表示的类别值:{0、1 或 2}。

traintest 变量的类型为 tf.data.Dataset,每个样本都是一个(图像,掩码)元组。

这种形式的掩码/输出与教程中的sparse_categorical_crossentropy损失函数一致。但是,我希望能够使用其他需要 one-hot 编码的损失函数。

我一直在尝试使用 map() 调用通过 tf.keras.utils.to_categorical() 函数转换数据集,即:

    def mask_to_categorical(image, mask):
        mask = tf.keras.utils.to_categorical(mask,3)
        return image, mask
    
    train = train.map(mask_to_categorical)

但是,这会失败并出现以下错误:

    {...}/tensorflow_core/python/keras/utils/np_utils.py:40 to_categorical
        y = np.array(y, dtype='int')

    TypeError: __array__() takes 1 positional argument but 2 were given

注意:

到目前为止,我的搜索已将急切/非急切问题作为可能的原因之一。对于它的价值,我通过以下方式验证了我正在以渴望模式运行:

    >>> print('tf.executing_eagerly() = ', tf.executing_eagerly())
    
    tf.executing_eagerly() =  True

有什么建议吗?谢谢!

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    尝试像这样修改 one-hot encoding 的函数:

    def mask_to_categorical(image, mask):
        mask = tf.one_hot(tf.cast(mask, tf.int32), 3)
        mask = tf.cast(mask, tf.float32)
        return image, mask
    

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2016-10-19
      • 2020-12-25
      相关资源
      最近更新 更多