Tensorflow 在Keras中使用RNN和CNN

Tensorflow 在Keras中使用RNN和CNN,tensorflow,keras,lstm,recurrent-neural-network,keras-layer,Tensorflow,Keras,Lstm,Recurrent Neural Network,Keras Layer,初学者问题 使用Keras,我有一个连续的CNN模型,根据图像(输入)预测[3*1](回归)大小的输出 如何实现RNN,以便将模型的输出作为第二个输入添加到下一步。 (因此我们有两个输入:图像和前一序列的输出) 我找到的最简单的方法是直接扩展模型。以下代码将在TF 2.0中工作,但在旧版本中可能不工作: class RecurrentModel(Model): def __init__(self, num_timesteps, *args, **kwargs): self

初学者问题

使用Keras,我有一个连续的CNN模型,根据图像(输入)预测[3*1](回归)大小的输出

如何实现RNN,以便将模型的输出作为第二个输入添加到下一步。 (因此我们有两个输入:图像和前一序列的输出)


我找到的最简单的方法是直接扩展
模型
。以下代码将在TF 2.0中工作,但在旧版本中可能不工作:

class RecurrentModel(Model):
    def __init__(self, num_timesteps, *args, **kwargs):
        self.num_timesteps = num_timesteps
        super().__init__(*args, **kwargs)

    def build(self, input_shape):
        inputs = layers.Input((None, None, input_shape[-1]))
        x = layers.Conv2D(64, (3, 3), activation='relu'))(inputs)
        x = layers.MaxPooling2D((2, 2))(x)
        x = layers.Flatten()(x)
        x = layers.Dense(3, activation='linear')(x)
        self.model = Model(inputs=[inputs], outputs=[x])

    def call(self, inputs, **kwargs):
        x = inputs
        for i in range(self.num_timestaps):
            x = self.model(x)
        return x

非常有用的答案对我来说!但运行此命令会在我这方面产生错误:
在赋值之前引用了局部变量“x”
。您能澄清一下吗?
build()
中的第二行应该有
输入作为输入,而不是
x
。修好了,谢谢!
class RecurrentModel(Model):
    def __init__(self, num_timesteps, *args, **kwargs):
        self.num_timesteps = num_timesteps
        super().__init__(*args, **kwargs)

    def build(self, input_shape):
        inputs = layers.Input((None, None, input_shape[-1]))
        x = layers.Conv2D(64, (3, 3), activation='relu'))(inputs)
        x = layers.MaxPooling2D((2, 2))(x)
        x = layers.Flatten()(x)
        x = layers.Dense(3, activation='linear')(x)
        self.model = Model(inputs=[inputs], outputs=[x])

    def call(self, inputs, **kwargs):
        x = inputs
        for i in range(self.num_timestaps):
            x = self.model(x)
        return x