首页 文章

sin的延迟回声 - 无法在Keras中重现Tensorflow结果

提问于
浏览
3

我正在Keras试验LSTM,几乎没有运气 . 在某些时刻,我决定缩回最基本的问题,以便最终取得一些积极的成果 .
然而,即使是最简单的问题,我发现Keras无法收敛,而Tensorflow中相同问题的实现给出了稳定的结果 .

我不愿意在没有理解为什么Keras在我尝试的任何问题上不断分歧的情况下切换到Tensorflow .

我的问题是延迟sin回波的多对多序列预测,例如:
signal_n_prediction

蓝线是网络输入序列,红色虚线是预期输出 .
该实验的灵感来自于repo,并且也可以从中创建可行的Tensorflow解决方案 . 我的代码的相关摘录如下,我的最小可重复示例的完整版本可用here .

Keras型号:

model = Sequential()
model.add(LSTM(n_hidden,
               input_shape=(n_steps, n_input),
               return_sequences=True))
model.add(TimeDistributed(Dense(n_input, activation='linear')))
model.compile(loss=custom_loss,
              optimizer=keras.optimizers.Adam(lr=learning_rate),
              metrics=[])

Tensorflow模型:

x = tf.placeholder(tf.float32, [None, n_steps, n_input])
y = tf.placeholder(tf.float32, [None, n_steps])

weights = {
    'out': tf.Variable(tf.random_normal([n_hidden, n_steps], seed = SEED))
}
biases = {
    'out': tf.Variable(tf.random_normal([n_steps], seed = SEED))
}
lstm = rnn.LSTMCell(n_hidden, forget_bias=1.0)
outputs, states = tf.nn.dynamic_rnn(lstm, inputs=x,
                                    dtype=tf.float32,
                                    time_major=False)

h = tf.transpose(outputs, [1, 0, 2])
pred = tf.nn.bias_add(tf.matmul(h[-1], weights['out']), biases['out'])
individual_losses = tf.reduce_sum(tf.squared_difference(pred, y),
                                  reduction_indices=1)
loss = tf.reduce_mean(individual_losses)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) \
  .minimize(loss)

我声称代码的其他部分( data_generationtraining )完全相同 . 但是,与Keras的学习进展很早就停止了,并且产生了令人不满意的预测 . 下面附有用于库和示例预测的 logloss 图:

用于Tensorflow训练模型的Logloss:
tensorflow_logloss

用于Keras训练模型的Logloss:
enter image description here
从图中读取并不容易,但Tensorflow达到 target_loss=0.15 并在大约10k批次后提前停止 . 但Keras耗尽了所有13k批次,仅约 loss . 在Keras以10万批次运行的单独实验中,它没有进一步停留在 1.0 附近 .

下图包含:黑线 - 模型输入信号,绿色虚线 - 地面实况输出,红线 - 采集模型输出 .

Tensorflow训练模型的预测:

predictions_tensorflow
Keras训练模型的预测:
enter image description here
感谢您的建议和见解,亲爱的同事们!

1 回答

  • 0

    好的,我设法解决了这个问题 . Keras的实施现在也稳步收敛到一个合理的解决方案:

    keras_new_training_loss

    keras_new_inference_example

    这些模型实际上并不完全相同 . 您可以格外检查问题中的 Tensorflow 型号版本并自行验证下面列出的实际 Keras 等效物,并且不是问题中所述的内容:

    model = Sequential()
    model.add(LSTM(n_hidden,
                   input_shape=(n_steps, n_input),
                   return_sequences=False))
    model.add(Dense(n_steps, input_shape=(n_hidden,), activation='linear'))
    model.compile(loss=custom_loss,
                  optimizer=keras.optimizers.Adam(lr=learning_rate),
                  metrics=[])
    

    我会详细说明 . 这里可行的解决方案使用LSTM吐出的最后一列大小 n_hidden 作为中间激活,然后输入到 Dense 层 .
    因此,在某种程度上,这里的实际预测是由常规感知器进行的 .

    一个额外的带走注释 - 原始 Keras 解决方案中的错误来源已经从问题附带的推理示例中明显看出 . 我们看到那里的早期时间戳完全失败,而后来的时间戳接近完美 . 这些早期时间戳对应于LSTM的状态,当它刚刚在新窗口上初始化并且无法上下文时 .

相关问题