Tensorflow-ValueError:模型的输出张量必须是TensorFlow`Layer`的输出 [英] Tensorflow - ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer`

查看:967
本文介绍了Tensorflow-ValueError:模型的输出张量必须是TensorFlow`Layer`的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在TensorFlow 2.0中使用Keras功能API创建了一个RNN,以下代码可以在其中运行

I have created an RNN with the Keras functional API in TensorFlow 2.0 where the following piece of code workes

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

然后我不得不更改为Tensorflow 1.13,这给了我以下错误

I then had to changed to Tensorflow 1.13 which gives me the following error

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)

我不明白为什么输出张量不是来自Tensorflow层,因为t_sum是来自keras.layers.Add的输出.

I don't understand why the output tensor is not from a Tensorflow layer, since t_sum is the output from 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.

推荐答案

问题不是与Add()层有关,而是与tf.unstack()有关-它不是keras.layers.Layer()的实例.您可以将其包装为自定义图层:

The problem is not with Add() layer but with tf.unstack() - it is not an instance of 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)

或者,您可以使用Lambda层来代替子类化:

or, instead of subclassing, you can do it using Lambda layer:

x = tf.keras.layers.Lambda(lambda t: tf.unstack(t, axis=2, num=256))(sum_input)

这篇关于Tensorflow-ValueError:模型的输出张量必须是TensorFlow`Layer`的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆