[英]Tensorflow - ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer`
I have created an RNN with the Keras functional API in TensorFlow 2.0 where the following piece of code workes我在 TensorFlow 2.0 中使用 Keras 函数式 API 创建了一个 RNN,其中以下代码有效
sum_input = keras.Input(shape=(UNIT_SIZE, 256,), name='sum')
x = tf.unstack(sum_input,axis=2, num=256)
t_sum = x[0]
for i in range(len(x) - 1):
t_sum = keras.layers.Add()([t_sum, x[i+1]])
sum_m = keras.Model(inputs=sum_input, outputs=t_sum, name='sum_model')
I then had to changed to Tensorflow 1.13 which gives me the following error然后我不得不更改为 Tensorflow 1.13,这给了我以下错误
ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer` (thus holding past layer metadata). Found: Tensor("add_254/add:0", shape=(?, 40), dtype=float32)
I don't understand why the output tensor is not from a Tensorflow layer, since t_sum is the output from keras.layers.Add.我不明白为什么输出张量不是来自 Tensorflow 层,因为 t_sum 是 keras.layers.Add 的输出。
I have tried to wrap parts of the code into keras.layers.Lambda as suggested in ValueError: Output tensors to a Model must be the output of a TensorFlow Layer , but it doesn't seem to work for me.我试图按照ValueError: Output tensors to a Model must be the output of a TensorFlow Layer 中的建议将部分代码包装到 keras.layers.Lambda 中,但它似乎对我不起作用。
The problem is not with Add()
layer but with tf.unstack()
- it is not an instance of keras.layers.Layer()
.问题不在于Add()
层,而tf.unstack()
- 它不是keras.layers.Layer()
的实例。 You can just wrap it up as custom layer:您可以将其包装为自定义层:
import tensorflow as tf
class Unstack(tf.keras.layers.Layer):
def __init__(self):
super(Unstack, self).__init__()
def call(self, inputs, num=256):
return tf.unstack(inputs, axis=2, num=num)
x = Unstack()(sum_input)
or, instead of subclassing, you can do it using Lambda
layer:或者,您可以使用Lambda
层代替子类化:
x = tf.keras.layers.Lambda(lambda t: tf.unstack(t, axis=2, num=256))(sum_input)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.