Ошибка неподключенных градиентов при реализации Grad-Cam в керасе - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь создать тепловую карту, которая отображает, где мой CNN смотрит, чтобы классифицировать изображение. Для задач классификации я выбираю между неисправными частями и неисправными частями (следовательно, только двоичная классификация). Я пытался повторить этот код . Однако я увидел, что они использовали всю начальную сеть, не меняя верхний слой. Моя проблема сейчас в том, что я не знаю, как правильно соединить слои, чтобы я мог использовать функцию градиента для обратного распространения потерь от конца моей модели (плотный слой с одним нейроном) до последнего сверточного слоя в начальной сети ( "mixed10"). Пока что я получаю AssertionError с сообщением о неподключенных градиентах

Обученная мной модель:

def create_model():

model_inception= InceptionV3(include_top=False, weights='imagenet',input_shape=(299,299,3))

model_inception.trainable=False

model = Sequential()
model.add(model_inception)
model.add(GlobalAveragePooling2D())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy', metrics=['accuracy'])

return model

Сводка модели

Код Grad_CAM:

layer_name = 'mixed10'
image = np.expand_dims(X_valid[0], 0)

#input layter to inception
input_lay = model.get_layer(index=0).layers[0].input

#Heatmap creatd from ConvLayer
conv_output_lay = model.get_layer(index=0).get_layer(layer_name).output

#Output Layer of the network
output_lay = model.get_layer(index=-1).output

#Connect conv_output with model.input
incept_part_till_conv = Model(input_lay,conv_output_lay)
conv_output = incept_part_till_conv(model.input)

gradModel = Model(
inputs=[model.input],
outputs=[conv_output, 
    model.output])

# record operations for automatic differentiation
with tf.GradientTape() as tape:
    # cast the image tensor to a float-32 data type, pass the
    # image through the gradient model, and grab the loss
    # associated with the specific class index
    inputs = tf.cast(image, tf.float32)
    (convOutputs, predictions) = gradModel(inputs)
    loss = predictions[:]

    # use automatic differentiation to compute the gradients
    grads = tape.gradient(loss, convOutputs)

Тогда я получаю сообщение об ошибке. Если бы кто-то мог дать мне несколько советов о том, как я могу заставить это работать, это было бы действительно здорово. Спасибо!

1 Ответ

0 голосов
/ 06 апреля 2020

Единственное, что меня поражает, это то, что вам нужно вычислить градиенты вне области ленты с областью действия (как они сделали в примере):

# record operations for automatic differentiation
with tf.GradientTape() as tape:
    # cast the image tensor to a float-32 data type, pass the
    # image through the gradient model, and grab the loss
    # associated with the specific class index
    inputs = tf.cast(image, tf.float32)
    (convOutputs, predictions) = gradModel(inputs)
    loss = predictions[:]

# use automatic differentiation to compute the gradients
grads = tape.gradient(loss, convOutputs)
...