【问题标题】:Tensor to categorical, tensorflow problem with fit.generator使用 fit.generator 从张量到分类的张量流问题
【发布时间】:2021-09-03 05:56:55
【问题描述】:

我在创建一个热张量来训练多类分割时遇到了问题。分割掩码中的像素标记为 {0, 200, 210, 220, 230, 240},如果我这样做的话

tf.utils.keras.to_categorical(masks, 6)

代码不起作用。我还将像素转换为值 {0,1,2,3,4,5},并且代码可以工作,但是当我绘制第 1 层或第 2 层时,我什么也看不到。 使用后:

tf.one_hot(masks,6) 

这很好,但是当我将这条线的结果提供给 model.fit() 生成器时,我的训练停止了。

【问题讨论】:

    标签: python tensorflow deep-learning computer-vision image-segmentation


    【解决方案1】:

    您必须确保您的列表中确实只有 6 个不同的标签,并且它们从 0 开始,并且范围仅到 num_classes-1。

    tf.keras.utils.to_categorical(y, num_classes=None, dtype='float32')
    

    参数:

    • y :要转换为矩阵的类向量(从 0 到 num_classes 的整数)。
    • num_classes :类的总数。如果没有,这将被推断为(y 中的最大数)+ 1

    © TensorFlow:异构系统上的大规模机器学习,2015 年。(CC BY 4.0),来源:https://www.tensorflow.org/api_docs/python/tf/keras/utils/to_categorical

    否则会失败。此外,tf.utils.keras 在您的函数调用中可能是错误的方式。

    >>>import tensorflow as tf
    >>>tf.keras.utils.to_categorical([0,1,2,3,4,5], 6)
    array([[1., 0., 0., 0., 0., 0.],
           [0., 1., 0., 0., 0., 0.],
           [0., 0., 1., 0., 0., 0.],
           [0., 0., 0., 1., 0., 0.],
           [0., 0., 0., 0., 1., 0.],
           [0., 0., 0., 0., 0., 1.]], dtype=float32)
    

    有效,但是

    >>>tf.keras.utils.to_categorical([0, 200, 210, 220, 230, 240], 6)
    IndexError: index 200 is out of bounds for axis 1 with size 6
    

    失败。您还可以将 num_classes 设置为 None。这会起作用,但它也会将您的一个热编码标签的长度增加到max([0, 200, 210, 220, 230, 240]) + 1

    >>>tf.keras.utils.to_categorical([0, 200, 210, 220, 230, 240], None)
    array([[1., 0., 0., ..., 0., 0., 0.], ... ], dtype=float32)
    
    # with
    # len([1., 0., 0., ..., 0., 0., 0.]) == 241
    

    您可以使用sklearn.preprocessing.LabelEncoder 来准备/规范您的标签:

    >>>from sklearn import preprocessing
    >>>le = preprocessing.LabelEncoder()
    >>>le.fit([1, 2, 2, 6])
    LabelEncoder()
    >>>le.classes_
    array([1, 2, 6])
    >>>le.transform([1, 1, 2, 6])
    array([0, 0, 1, 2]...)
    >>>le.inverse_transform([0, 0, 1, 2])
    array([1, 1, 2, 6])
    

    © 2007 - 2020,scikit-learn 开发人员(BSD 许可证),来源:https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 1970-01-01
      • 2017-12-01
      • 2018-04-18
      • 2018-06-10
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多