在子类化Keras模型中获取预训练架构的最后一个卷积层的输出用于Grad-CAM

我正在尝试获取预训练模型的最后一个卷积层的输出。我需要它来计算Grad-CAM。为了做到这一点,我需要创建一个有两个输出的模型,一个用于分类,另一个用于卷积层的输出,就像这个教程中一样。但它不起作用。它显示错误信息如下:

AttributeError: Layer custom_mobile_net_3 has no inbound nodes.

无法更改模型定义。


回答:

为了实现你的需求,我们可以按照以下方式进行操作。

可训练模型

Grad-CAM模型

class GradCustomMobileNet(CustomMobileNet): # or, K.Model    def __init__(self):        super(GradCustomMobileNet, self).__init__()        self.base = K.applications.MobileNetV2(input_shape=(height, width, channels),                                               include_top=True,                                               weights=None)                self.base = tf.keras.models.Model(            [self.base.inputs],             [self.base.get_layer(last_conv_layer_name).output,                       self.base.output]        )                self.out = K.layers.Dense(4, activation='sigmoid')    def call(self, x, training=None, **kwargs):        conv, x = self.base(x)        x = self.out(x)        return conv, xgrad_model = GradCustomMobileNet()

计算梯度

img_array = np.random.rand(1, 224, 224, 3).astype(np.float32)pred_index = Nonewith tf.GradientTape() as tape:    last_conv_layer_output, preds = grad_model(img_array)    if pred_index is None:        pred_index = tf.argmax(preds[0])    class_channel = preds[:, pred_index]grads = tape.gradient(class_channel, last_conv_layer_output)grads.shapeTensorShape([1, 7, 7, 1280])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注