tensorflow:将to_categorical()与数据集和map()组合

时间:2019-10-26 02:12:02

标签: python tensorflow keras

简而言之,我正在努力将tf.data.Dataset中的图像每像素类别蒙版从整数类编码转换为单热编码。

在此处考虑图像分割tensorflow教程示例: https://www.tensorflow.org/tutorials/images/segmentation

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

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

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

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

    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

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试像这样修改一键编码的功能:

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