AttributeError:EagerTensor 对象没有属性“astype”

问题描述 投票:0回答:2

我正在尝试在 Google Colab 中制作 GradCAM 热图,如下所示:

import tensorflow as tf
from tensorflow.keras import backend as K
from tf_keras_vis.activation_maximization import ActivationMaximization
from tf_keras_vis.utils.callbacks import Print

def model_modifier(m):
    m.layers[-1].activation = tf.keras.activations.linear

activation_maximization = ActivationMaximization(model, model_modifier)

loss = lambda x: K.mean(x[:, 1])

activation = activation_maximization(loss, callbacks=[Print(interval=100)])
image = activation[0].astype(np.uint8)         # <----- error

f, ax = plt.subplots(figsize=(10, 5), subplot_kw={'xticks': [], 'yticks': []})
ax.imshow(image)
plt.show()

但我收到错误

AttributeError: EagerTensor object has no attribute 'astype'. 
python tensorflow keras tensor attributeerror
2个回答
2
投票

首先使用

activation[0].numpy()
转换为 numpy,然后你应该能够使用 numpy 数组方法。


0
投票

虽然转换为 numpy ndarray 并调用

astype()
当然有效,但有时,最好继续使用张量对象。在这种情况下,可以使用
astype()
,而不是
tf.cast()

import tensorflow as tf

x = tf.constant([1, 2, 3])
xx = tf.cast(x, tf.uint8)
print(xx)                   # tf.Tensor([1 2 3], shape=(3,), dtype=uint8)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.