【问题标题】:using RNN with CNN in Keras在 Keras 中使用带有 CNN 的 RNN
【发布时间】:2020-06-08 23:00:26
【问题描述】:

初学者问题

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

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

model = models.Sequential()
model.add(layers.Conv2D(64, (3, 3), activation='relu', input_shape=X.shape[1:]))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(3, activation='linear'))

【问题讨论】:

    标签: tensorflow keras lstm recurrent-neural-network keras-layer


    【解决方案1】:

    我发现的最简单的方法是直接扩展Model。以下代码可在 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
    

    【讨论】:

    • 对我来说非常有用的答案!但是运行它会给我一个错误:local variable 'x' referenced before assignment。你能澄清一下吗?
    • build() 中的第二行应该有inputs 作为输入,而不是x。已修复,谢谢!
    猜你喜欢
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2018-12-30
    • 2019-12-06
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多