【问题标题】:How to replace Keras' gradients() function with GradientTape in TF2.0?如何在 TF2.0 中用 GradientTape 替换 Keras 的 gradients() 函数?
【发布时间】:2019-10-07 14:37:58
【问题描述】:

借助“旧”Keras 库,我使用 keras.backend.gradients() 函数为我的 CNN 创建了热图,如下所示:

# load model and image, then predict the class this image belongs to
model = load_model(os.path.join(model_folder, "custom_model.h5"))
image = image.load_img(image_path)
img_tensor = image.img_to_array(image)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor = preprocess_input(img_tensor)

preds = model.predict(img_tensor)
model_prediction = model.output[:, np.argmax(preds[0])]

# Calculate pooled grads for heatmap
conv_layer = model.get_layer("block5_conv3")  # last conv. layer
grads = K.gradients(model_prediction, conv_layer.output)[0]
pooled_grads = K.mean(grads, axis=(0, 1, 2))

# Get values of pooled grads and model conv. layer output as Numpy arrays
input_layer = model.get_layer("model_input")
iterate = K.function([input_layer], [pooled_grads, conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([img_tensor])

# Continue with heatmap generation ...

现在我切换到 TF2.0,它是内置的 Keras 实现。一切正常,但是,使用该代码调用K.gradients() 时出现以下错误:

tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead.

我做了一些研究并试图了解如何使用GradientTape,但不幸的是我对 TF 和 TF2.0 了解不多 - 我一直使用 Keras。你们能指导我如何通过我的设置使这个梯度计算再次起作用吗?

【问题讨论】:

标签: python tensorflow keras conv-neural-network tensorflow2.0


【解决方案1】:

这是您的问题的解决方案。这意味着创建一个同时输出 conv_output 和预测的模型,因此我们可以正确应用 GradientTape

没有你的模型/数据,所以我拿了一个 ResNet50 和随机值。

import numpy as np
import tensorflow as tf

model = tf.keras.applications.resnet50.ResNet50()
img_tensor = np.random.random((1, 224, 224, 3))

conv_layer = model.get_layer('conv5_block3_1_conv')

heatmap_model = tf.keras.models.Model(
    [model.inputs], [model.get_layer('conv5_block3_1_conv').output, model.output]
)

with tf.GradientTape() as tape:
    conv_output, predictions = heatmap_model(img_tensor)
    loss = predictions[:, np.argmax(predictions[0])]

grads = tape.gradient(loss, conv_output)

【讨论】:

  • 谢谢,这解决了我的问题。但是,现在K.function([input_layer], [pooled_grads, conv_layer.output[0]]) 的以下行导致另一个错误:“AttributeError: Tensor.op is meaningless when eager execution is enabled.”你知道什么可能导致这个问题吗?
【解决方案2】:

您不能使用 K.function,因为它在启用 Eager Execution 时不起作用,这是默认完成的。从我有限的理解来看,K.function 可以在静态图上使用,当急切执行被禁用时会发生这种情况。

tensorflow.compat.v1.disable_eager_execution()

块上方可以缓解一些问题,但会产生新问题。更好的解决方法是使用引导梯度方法,您只考虑正梯度和正卷积输出来获得引导梯度。

castConvOutputs = tensorflow.cast(conv_output > 0, "float32")
castGrads = tensorflow.cast(grads > 0, "float32")
guidedGrads = castConvOutputs * castGrads * grads

# My goal was to create the class activation map for single image, so we are skipping axis=0 which is meant to have the batch_size of images at axis=0
convOutputs = conv_output[0]
guidedGrads = guidedGrads[0]

最后,我沿图像的宽度和高度取平均值(池化引导梯度),并将所有通道(深度层)的数学加权激活求和,以创建类激活图。

weights = tensorflow.reduce_mean(guidedGrads, axis=(0, 1))
cam = tensorflow.reduce_sum(tensorflow.multiply(weights, convOutputs), axis=-1)

这可以在标准化和缩放到 0-255 整数范围后使用 cv2.applycolormap 选择的颜色图进行修改。

致谢:Adrian Rosebrock 博客

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2020-04-14
    • 2020-03-10
    相关资源
    最近更新 更多