简体   繁体   English

如何使用 TF2.0 (tf.keras) 中的内置 Keras 生成 CNN 热图

[英]How to generate CNN heatmaps using built-in Keras in TF2.0 (tf.keras)

I used to generate heatmaps for my Convolutional Neural Networks, based on the stand-alone Keras library on top of TensorFlow 1. That worked fine, however, after my switch to TF2.0 and built-in tf.keras implementation (with eager execution ) I cannot use my old heatmap generation code any longer.我曾经为我的卷积神经网络生成热图,基于 TensorFlow 1 之上的独立 Keras 库。但是,在我切换到 TF2.0 和内置tf.keras执行之后效果很好) 我不能再使用旧的热图生成代码了。

So I re-wrote parts of my code for TF2.0 and ended up with the following:因此,我为 TF2.0 重新编写了部分代码,结果如下:

from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.models import load_model

from tensorflow.keras import preprocessing
from tensorflow.keras import backend as K
from tensorflow.keras import models

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

image_size = 150
image_path = "/tmp/images/test-image.jpg"
model_path = "/tmp/models/prototype/basic_vgg16.h5"

# Load pre-trained Keras model and the image to classify
model = load_model(model_path)  # VGG16 CNN with custom classifier head
image = load_img(image_path, target_size=(image_size, image_size))
img_tensor = preprocessing.image.img_to_array(image)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor = preprocess_input(img_tensor)

input_layer = model.get_layer("model_input")
conv_layer = model.get_layer("block5_conv3")
heatmap_model = models.Model([model.inputs], [conv_layer.output, model.output])

# Get gradient of the winner class w.r.t. the output of the (last) conv. layer
with tf.GradientTape() as gtape:
    conv_output, predictions = heatmap_model(img_tensor)
    loss = predictions[:, np.argmax(predictions[0])]
    grads = gtape.gradient(loss, conv_output)
    pooled_grads = K.mean(grads, axis=(0, 1, 2))

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

# Multiply each channel in the feature-map array by "how important it is"
for i in range(pooled_grads_value.shape[0]):
    conv_layer_output_value[:, :, i] *= pooled_grads_value[i]

# Channel-wise mean of resulting feature-map is the heatmap of class activation
heatmap = np.mean(conv_layer_output_value, axis=-1)
heatmap = np.maximum(heatmap, 0)
max_heat = np.max(heatmap)
if max_heat == 0:
    max_heat = 1e-10
heatmap /= max_heat

# Render heatmap via pyplot
plt.matshow(heatmap)
plt.show()

But now the following line:但现在以下行:

iterate = K.function([model.inputs], [pooled_grads, conv_layer.output[0]])

leads to this error message:导致此错误消息:

AttributeError: Tensor.op is meaningless when eager execution is enabled.

I always used Keras and did not work with TF directly, so I am bit lost here.我一直使用 Keras 并没有直接使用 TF,所以我在这里有点迷失了。
Any ideas what could be the problem here?有什么想法可能是这里的问题吗?


PS: If you want to c&p this code, you can create the VGG16-based model like so: PS:如果你想c&p这段代码,你可以像这样创建基于VGG16的model:

# Create Keras model from pre-trained VGG16 and custom classifier
input_layer = layers.Input(shape=(image_size, image_size, 3), name="model_input")
vgg16_model = VGG16(weights="imagenet", include_top=False, input_tensor=input_layer)
model_head = vgg16_model.output
model_head = layers.Flatten(name="model_head_flatten")(model_head)
model_head = layers.Dense(256, activation="relu")(model_head)
model_head = layers.Dense(3, activation="softmax")(model_head)
model = models.Model(inputs=input_layer, outputs=model_head)
model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adam(), metrics=["accuracy"])

At the end of the GradientTape loop, conv_output and grads already holds the value.GradientTape循环结束时, conv_outputgrads已经保存了该值。 The iterate function is no longer need to compute the values.迭代 function 不再需要计算值。

Working example below:下面的工作示例:

from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.models import load_model

from tensorflow.keras import preprocessing
from tensorflow.keras import backend as K
from tensorflow.keras import models

import tensorflow as tf
import numpy as np

image_size = 224

# Load pre-trained Keras model and the image to classify
model = tf.keras.applications.vgg16.VGG16()
image = np.random.random((image_size, image_size, 3))
img_tensor = preprocessing.image.img_to_array(image)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor = preprocess_input(img_tensor)

conv_layer = model.get_layer("block5_conv3")
heatmap_model = models.Model([model.inputs], [conv_layer.output, model.output])

# Get gradient of the winner class w.r.t. the output of the (last) conv. layer
with tf.GradientTape() as gtape:
    conv_output, predictions = heatmap_model(img_tensor)
    loss = predictions[:, np.argmax(predictions[0])]
    grads = gtape.gradient(loss, conv_output)
    pooled_grads = K.mean(grads, axis=(0, 1, 2))

heatmap = tf.reduce_mean(tf.multiply(pooled_grads, conv_output), axis=-1)
heatmap = np.maximum(heatmap, 0)
max_heat = np.max(heatmap)
if max_heat == 0:
    max_heat = 1e-10
heatmap /= max_heat

print(heatmap.shape)

one more issue to view the heatmap查看热图的另一个问题

import matplotlib.pyplot as plt
hm=np.squeeze(heatmap)
hm.shape

(14, 14) (14, 14)

plt.imshow(hm)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TF2.0 图像生成器无法使用 Keras ImageDataGenerator - TF2.0 image generator not working using Keras ImageDataGenerator 如何在TF2.0中使用自定义渐变创建keras层? - How to create a keras layer with a custom gradient in TF2.0? 如何在 TF2.0 中用 GradientTape 替换 Keras 的 gradients() function? - How to replace Keras' gradients() function with GradientTape in TF2.0? TensorFlow 2.0:如何使用tf.keras对图表进行分组? tf.name_scope / tf.variable_scope不再使用了? - TensorFlow 2.0: how to group graph using tf.keras? tf.name_scope/tf.variable_scope not used anymore? Image Classification using tf.keras CNN 关于 kernel 的问题以及如何创建测试数据集? - Image Classification using tf.keras CNN questions about kernel and how to create test dataset? tf2.0:tf.image.resize_with_pad 失败,“使用 `tf.Tensor` 作为 Python `bool” 和 tf.keras.Input - tf2.0: tf.image.resize_with_pad fails with “using a `tf.Tensor` as a Python `bool” with tf.keras.Input 在 tf.keras 中使用 tensorflow 函数 - using tensorflow functions with tf.keras 如何使用 tf.keras 拟合 LSTM 模型 - How to fit a LSTM model using tf.keras 将 Horovod 与 tf.keras 一起使用时如何从检查点恢复? - How to resume from a checkpoint when using Horovod with tf.keras? 如何使用 tf.keras 加载模型? - How to load a model with tf.keras?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM