属性错误:“张量”对象没有属性“numpy”;同时扩展keras序列模型
我正在尝试在急切执行模式下编译 Keras Sequential
模型(在 TF2 中)。 以下是我的自定义层:
class CustomLayer(Layer):
def __init__(self, output_shape, **kwargs):
self.output_shape = output_shape
super(CustomLayer, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 2
input_dim = input_shape[1]
def call(self, inputs, mask=None, **kwargs):
y_pred = inputs.numpy() #<---- raise error
return y_pred
我使用该层来扩展另一个序列模型,如下所示:
encoder = Sequential(encoders) # encoders is a bunch of Dense layers
encoder.compile(
loss='mse',
optimizer=SGD(lr=self.learning_rate, decay=0, momentum=0.9),
run_eagerly=True
)
self.MyModel = Sequential([encoder, CustomLayer(output_shape=output_shape)])
self.MyModel.compile(
loss='MSE',
optimizer=sgd,
run_eagerly=True
)
原始模型是带有去噪层的自动编码器,我在瓶颈之后添加一个新层以进行一些自定义预测。 我需要访问新层中的张量值。 这样做会引发以下错误:
Traceback (most recent call last):
File "main.py", line 185, in initialize
self.DEC = Sequential([encoder, CustomingLayer(input_shape=input_shape,
File ".virtualenvs/vision/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File ".virtualenvs/vision/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File ".virtualenvs/vision/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 699, in wrapper
raise e.ag_error_metadata.to_exception(e)
AttributeError: Exception encountered when calling layer "custom_layer" (type CustomLayer).
in user code:
File "custom_layer.py", line 25, in call *
y_pred = inputs.numpy()
AttributeError: 'Tensor' object has no attribute 'numpy'
Call arguments received:
• inputs=tf.Tensor(shape=(None, 10), dtype=float32)
• mask=None
• kwargs={'training': 'None'}
I am trying to compile a Keras Sequential
model (in TF2) in the eager execution mode.
Following is my custom layer:
class CustomLayer(Layer):
def __init__(self, output_shape, **kwargs):
self.output_shape = output_shape
super(CustomLayer, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 2
input_dim = input_shape[1]
def call(self, inputs, mask=None, **kwargs):
y_pred = inputs.numpy() #<---- raise error
return y_pred
I use this layer to extend another Sequential Model as follow:
encoder = Sequential(encoders) # encoders is a bunch of Dense layers
encoder.compile(
loss='mse',
optimizer=SGD(lr=self.learning_rate, decay=0, momentum=0.9),
run_eagerly=True
)
self.MyModel = Sequential([encoder, CustomLayer(output_shape=output_shape)])
self.MyModel.compile(
loss='MSE',
optimizer=sgd,
run_eagerly=True
)
The original model is an autoencoder with denoising layers, and I'm adding a new layer after the bottleneck to make some customized predictions.
I need to have access to the tensor values within the new layer.
Doing so raises the following error:
Traceback (most recent call last):
File "main.py", line 185, in initialize
self.DEC = Sequential([encoder, CustomingLayer(input_shape=input_shape,
File ".virtualenvs/vision/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File ".virtualenvs/vision/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File ".virtualenvs/vision/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py", line 699, in wrapper
raise e.ag_error_metadata.to_exception(e)
AttributeError: Exception encountered when calling layer "custom_layer" (type CustomLayer).
in user code:
File "custom_layer.py", line 25, in call *
y_pred = inputs.numpy()
AttributeError: 'Tensor' object has no attribute 'numpy'
Call arguments received:
• inputs=tf.Tensor(shape=(None, 10), dtype=float32)
• mask=None
• kwargs={'training': 'None'}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接使用这个 numpy 函数是不可能的 - 因为它既没有在 Tensorflow 中也没有在 Theano 中实现。而且,张量和数组之间没有直接的对应关系。张量应理解为代数变量,而 numpy 数组应理解为数字。张量是一个抽象的东西,对其应用 numpy 函数通常是不可能的。
但您仍然可以尝试使用 keras.backend 自行重新实现您的函数。然后您将使用有效的张量运算,并且不会出现任何问题。
解决问题的另一种方法是使用 tf.numpy_function,请参阅 文档,这允许您使用 numpy 函数,但有一些限制。
The direct using of this numpy function is impossible - as it's neither implemented in Tensorflow nor in Theano. Moreover, there is no direct correspondence between tensors and arrays. Tensors should be understood as algebraic variables whereas numpy arrays as numbers. Tensor is an abstract thing and applying a numpy function to it is usually impossible.
But you could still try to re-implement your function on your own using
keras.backend
. Then you'll use the valid tensor operations and no problem would be raised.Another way to tackle your problem would be to use
tf.numpy_function
, see the documentation, this allows you to use numpy functions but there are some limitations.