【问题标题】:How to get multiclass Keras model to output category name instead of probabilities?如何让多类 Keras 模型输出类别名称而不是概率?
【发布时间】:2021-10-28 16:18:06
【问题描述】:

我理解将训练数据中的标签作为 one-hot 编码传递给 Keras 模型的想法,但我正在尝试创建一个模型,该模型将在推理期间返回一个字符串,而不是我的 one-hot 编码我必须自己解码。

具体来说,我不想做以下事情:

encoder = LabelEncoder() 
encoder = encoder.fit(labels)
encoded_Y = encoder.transform(labels)
y_true = np_utils.to_categorical(encoded_Y). # Model accepts this during training

prediction = model.predict(query)
label_string = encoder.inverse_transform(prediction)

如何创建一个模型来调用.predict() 并返回一些自定义的内容,例如最高预测的字符串及其对应的概率?

【问题讨论】:

    标签: python tensorflow machine-learning keras


    【解决方案1】:

    您可以获取一个完整的模型,并在其之上创建一个包含后处理功能的自定义模型。

    让我们采用预训练模型:

    import tensorflow as tf
    from skimage.data import chelsea
    
    model = tf.keras.applications.MobileNetV2()
    

    该模型带有一个函数,该函数将输出概率矩阵转换为字符串(您必须自己制作)

    decoder = tf.keras.applications.mobilenet_v2.decode_predictions
    

    然后,我们创建一个包含两部分的模型:1)模型 2)后处理函数

    class NewModel(tf.keras.models.Model):
        def __init__(self, model, decoder):
            super(NewModel, self).__init__()
            self.model = model
            self.decoder = decoder
    
        def call(self, x):
            x = self.model(x).numpy()
            x = self.decoder(x)
            return x
    
    
    m = NewModel(model, decoder)
    

    现在,只需使用适当的输入调用它:

    cat_picture = tf.image.resize(chelsea(), (224, 224))[None, ...]/255
    
    m(cat_picture)
    
    [[('n02124075', 'Egyptian_cat', 0.7610773),
      ('n02123045', 'tabby', 0.12039327),
      ('n02123159', 'tiger_cat', 0.039847013),
      ('n02127052', 'lynx', 0.009957394),
      ('n04553703', 'washbasin', 0.0015057808)]]
    

    它返回后处理函数的输出。

    【讨论】:

    • 感谢您的回复!我的问题是需要单独提供解码器......如果我想将模型保存到磁盘并将其加载到另一个位置,我是否需要将解码器保存为泡菜文件并移动它?理想情况下,我会创建一个在标签编码/解码步骤中隐式烘焙的模型,允许我调用 model.fit(train_x, train_y, ...) 其中 train_y 是字符串列表
    • 嗯,这将是问题中包含的一个重要元素,因为您的问题的主要挑战并没有真正出现在您的帖子中。老实说,我不知道。我认为当你保存一个 Tensorflow 模型时,你可以同时保存自定义对象。
    猜你喜欢
    • 2019-05-19
    • 2018-07-15
    • 2016-12-04
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多