【问题标题】:Use tensor with numpy with eager execution turned off在关闭急切执行的情况下使用带有 numpy 的张量
【发布时间】:2021-11-20 22:19:12
【问题描述】:

我正在尝试使用 TensorFlow 2 对 CNN 中的图像进行热图可视化。我禁用了 Eager Execution,因为我想在 Apple Silicon M1 GPU 上运行模型,并且必须禁用它。这是代码:(取自 Keras 官方文档)

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)
    return heatmap.numpy() 

当我运行这个函数时,我收到以下错误:

AttributeError: 'Tensor' 对象没有属性 'numpy'

启用急切执行后,我没有收到此类错误并且功能正常运行,但正如我所说,我需要禁用它。

如何克服此错误并在禁用急切执行的情况下使该功能正常工作?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    您只需要在张量中调用eval 而不是numpy()

    【讨论】:

    • 错误消失了。现在显示另一个错误:ValueError:无法使用eval()评估张量:未注册默认会话。使用with sess.as_default() 或将显式会话传递给eval(session=sess)。我应该在哪里初始化会话?
    • 如果您使用tf.compat.v1.disable_eager_execution() 禁用急切是的,您需要创建一个会话,您可以找到更多信息here
    猜你喜欢
    • 2021-05-05
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多