Home > Enterprise >  Use tensor with numpy with eager execution turned off
Use tensor with numpy with eager execution turned off

Time:09-30

I am trying to make a to visualize a heatmap for an image in a CNN using TensorFlow 2. I disabled eager execution because I want to run the model on Apple Silicon M1 GPU, and it has to be disabled. This is the code: (taken from Keras official docs)

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() 

When I run this function I am receiving the following error:

AttributeError: 'Tensor' object has no attribute 'numpy'

When eager execution is enabled, I do not receive such error and the function runs normally, but as I said, I need it disabled.

How can I overcome this error and make the function work with eager execution disabled?

CodePudding user response:

You only need to call eval in the tensor instead numpy()

  • Related