返回介绍

RNN Regressor 循环神经网络

发布于 2025-05-02 13:36:26 字数 2678 浏览 0 评论 0 收藏

作者: Mark JingNB 编辑: Morvan

这次我们使用 RNN 来求解回归(Regression) 问题. 首先生成序列 sin(x) ,对应输出数据为 cos(x) ,设置序列步长为 20,每次训练的 BATCH_SIZE 为 50.

def get_batch():
    global BATCH_START, TIME_STEPS
    # xs shape (50batch, 20steps)
    xs = np.arange(BATCH_START, BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE, TIME_STEPS)) / (10*np.pi)
    seq = np.sin(xs)
    res = np.cos(xs)
    BATCH_START += TIME_STEPS
    return [seq[:, :, np.newaxis], res[:, :, np.newaxis], xs]

然后添加 LSTM RNN 层,输入为训练数据,输出数据大小由 CELL_SIZE 定义。因为每一个输入都对应一个输出,所以 return_sequences=True 。 每一个点的当前输出都受前面所有输出的影响,BATCH 之间的参数也需要记忆,故 stateful=True

model.add(LSTM(
    batch_input_shape=(BATCH_SIZE, TIME_STEPS, INPUT_SIZE),       # Or: input_dim=INPUT_SIZE, input_length=TIME_STEPS,
    output_dim=CELL_SIZE,
    return_sequences=True,      # True: output at all steps. False: output as last step.
    stateful=True,              # True: the final state of batch1 is feed into the initial state of batch2
))

最后添加输出层,LSTM 层的每一步都有输出,使用 TimeDistributed 函数。

model.add(TimeDistributed(Dense(OUTPUT_SIZE)))

设置优化方法, loss 函数和 metrics 方法之后就可以开始训练了。 训练 501 次,调用 matplotlib 函数采用动画的方式输出结果。

for step in range(501):
    # data shape = (batch_num, steps, inputs/outputs)
    X_batch, Y_batch, xs = get_batch()
    cost = model.train_on_batch(X_batch, Y_batch)
    pred = model.predict(X_batch, BATCH_SIZE)
    plt.plot(xs[0, :], Y_batch[0].flatten(), 'r', xs[0, :], pred.flatten()[:TIME_STEPS], 'b--')
    plt.ylim((-1.2, 1.2))
    plt.draw()
    plt.pause(0.1)
    if step % 10 == 0:
        print('train cost: ', cost)

如果你觉得这篇文章或视频对你的学习很有帮助,请你也分享它,让它能再次帮助到更多的需要学习的人。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。