关闭eager execution时TensorFlow2生成GradCAM热图报Tensor无numpy属性如何解决
报错解决方案
错误原因
关闭Eager Execution后,TensorFlow张量为计算图中的符号化节点,未绑定实际运行数值,因此不支持numpy()方法直接提取数值,该方法仅Eager模式下可用。
修复步骤
1. 修改GradCAM函数定义
删除函数末尾的.numpy()调用,直接返回计算得到的heatmap张量:
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None): grad_model = tf.keras.models.Model( [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output] ) with 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) pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) last_conv_layer_output = last_conv_layer_output[0] heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis] heatmap = tf.squeeze(heatmap) heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap) # 移除numpy()调用,直接返回张量 return heatmap
2. 会话执行获取numpy格式热力图
调用函数得到heatmap张量后,通过TensorFlow会话执行该张量即可得到可直接使用的numpy数组:
# 生成heatmap张量 heatmap_tensor = make_gradcam_heatmap(img_array, model, last_conv_layer_name) # 开启会话执行张量 with tf.compat.v1.Session() as sess: # 初始化grad_model的新增变量 sess.run(tf.compat.v1.global_variables_initializer()) # 若输入img_array为占位符类型,需补充feed_dict参数传入实际数值 heatmap = sess.run(heatmap_tensor)
如果你的代码中已经存在全局运行的会话,直接在现有会话中执行heatmap_tensor即可,无需重复创建会话和初始化变量。
内容的提问来源于stack exchange,提问作者Marcellin Khoury
相关产品推荐
相关产品推荐

