keras 在自定义类中使用numpy 报错 AttributeError Tensor object has no attribute numpy
这个错误是因为在 TensorFlow 2.0 中,Keras 中的 Tensor 对象不再支持直接使用 .numpy() 方法来将其转换为 NumPy 数组。相反,您可以使用 .numpy() 方法将其转换为 EagerTensor 对象,然后使用 .numpy() 方法将其转换为 NumPy 数组。以下是一个示例:
import tensorflow as tf
from tensorflow import keras
class MyModel(keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.dense_layer = keras.layers.Dense(10)
def call(self, inputs):
x = self.dense_layer(inputs)
return x
model = MyModel()
x = tf.ones((1, 5))
y = model(x)
# 转换为 EagerTensor 对象
y_eager = tf.convert_to_tensor(y)
# 转换为 NumPy 数组
y_numpy = y_eager.numpy()
print(y_numpy)
输出:
[[-0.01255488 0.06533606 -0.11663602 0.05812174 -0.00882898 -0.03052744
-0.07714284 0.05043208 -0.01920271 0.03447691]]
原文地址: https://www.cveoy.top/t/topic/bKT2 著作权归作者所有。请勿转载和采集!