【问题标题】:merging recurrent layers with dense layer in Keras在 Keras 中将循环层与密集层合并
【发布时间】:2016-10-24 05:23:37
【问题描述】:

我想构建一个神经网络,其中前两层是前馈的,最后一层是循环的。 这是我的代码:

model = Sequential()
model.add(Dense(150, input_dim=23,init='normal',activation='relu'))
model.add(Dense(80,activation='relu',init='normal'))
model.add(SimpleRNN(2,init='normal')) 
adam =OP.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss="mean_squared_error", optimizer="rmsprop")  

我得到了这个错误:

Exception: Input 0 is incompatible with layer simplernn_11: expected  ndim=3, found ndim=2.
model.compile(loss='mse', optimizer=adam)

【问题讨论】:

    标签: python machine-learning tensorflow theano keras


    【解决方案1】:

    在 Keras 中,不能在 Dense 层之后放置 Reccurrent 层,因为 Dense 层的输出为 (nb_samples, output_dim)。但是,循环层期望输入为 (nb_samples, time_steps, input_dim)。因此,Dense 层提供 2-D 输出,但 Recurrent 层需要 3-D 输入。但是,您可以做相反的事情,即在 Recurrent 层之后放置一个 Dense 层。

    【讨论】:

    • 感谢您的回复,实际上我在这里使用的输入是相关的,所以我想在最后一层创建一个短内存,这意味着系统在时间 t 的输出必须占用考虑到时间 t-1 的输出和,(因此我希望最后一层在两个前向层之前循环)你知道我怎样才能使序列数(time_steps)可变吗?
    【解决方案2】:

    在 Keras 中,RNN 层期望输入为(nb_samples, time_steps, input_dim) 是正确的。但是,如果您想在 Dense 层之后添加 RNN 层,您仍然可以在重塑 RNN 层的输入之后执行此操作。 Reshape 既可以用作第一层,也可以用作顺序模型中的中间层。示例如下:

    作为顺序模型中的第一层重塑

    model = Sequential()
    model.add(Reshape((3, 4), input_shape=(12,)))
    # now: model.output_shape == (None, 3, 4)
    # note: `None` is the batch dimension
    

    重塑为序列模型中的中间层

    model.add(Reshape((6, 2)))
    # now: model.output_shape == (None, 6, 2)
    

    例如,如果您按以下方式更改代码,则不会出现错误。我已经检查过它并且编译的模型没有报告任何错误。您可以根据需要更改尺寸。

    from keras.models import Sequential
    from keras.layers import Dense, SimpleRNN, Reshape
    from keras.optimizers import Adam
    
    model = Sequential()
    model.add(Dense(150, input_dim=23,init='normal',activation='relu'))
    model.add(Dense(80,activation='relu',init='normal'))
    model.add(Reshape((1, 80)))
    model.add(SimpleRNN(2,init='normal')) 
    adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
    model.compile(loss="mean_squared_error", optimizer="rmsprop")
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2017-11-26
      相关资源
      最近更新 更多