您可以采用一个完整的模型,并在其之上创建一个包含后处理功能的自定义模型。
让我们采用一个预训练的模型:
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)]]
它返回后处理函数的输出。