我正在尝试获取预训练模型的最后一个卷积层的输出。我需要它来计算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])