0

我理解将训练数据中的标签作为单热编码传递给 Keras 模型的想法,但我正在尝试创建一个模型,该模型将在推理过程中返回一个字符串,而不是我拥有的单热编码解码自己。

具体来说,我不想执行以下操作:

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()和返回自定义的东西,例如最高预测的字符串及其相应的概率?

4

1 回答 1

0

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

让我们采用一个预训练的模型:

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)]]

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

于 2021-10-28T17:11:41.010 回答