【问题标题】:For-Loop stops working after 2 iterationsFor-Loop 在 2 次迭代后停止工作
【发布时间】:2020-02-11 10:10:25
【问题描述】:

我正在使用 Keras API 在 tensorflow 2.0 中设置时间卷积网络以进行时间序列预测,并且我目前正在预测下一个时间步长。现在我遇到了这个 for 循环的问题:

def make_prediction(model, x_to_predict):
    next_step = model.predict(x_to_predict)
    return next_step

sequence = x_pred[0, :150, 0]

for next_timestep in range(20):
    range_to_predict = 150 + next_timestep
    sequence = sequence[next_timestep: range_to_predict].reshape([1, 150, 1])
    next_datapoint = make_prediction(model, sequence)
    sequence = np.append(sequence, next_datapoint)
    print("Timestep" + str(next_timestep))
    print("Predicted Value" + str(next_datapoint))

此循环适用于前两次迭代,然后它停止并出现以下错误:

Timestep0 预测值[[0.49933335]] Timestep1 预测值 值[[0.5245512]] Traceback(最近一次调用最后一次):文件“E:/...”, 第 105 行,在 sequence = sequence[next_timestep:range_to_predict].reshape([1, 150, 1]) ValueError: cannot reshape array of size 149 into shape (1,150,1)

我的模型采用形状 (None, 150, 1) 的输入,但我不明白为什么它在前 2 次迭代中有效。

如果有任何建议可以解决我的问题,我将不胜感激

【问题讨论】:

    标签: python-3.x tensorflow for-loop


    【解决方案1】:

    我的意思是,func sequence[next_timestep: range_to_predict] 创建长度为 range_to_predict - next_timestep 的序列。第一次迭代next_timestep等于0,序列长度为150。在第二次迭代next_timestep等于1,predict - next_timestep = 149,那么序列的形状为149,不能被整形为(1,150,1)。

    【讨论】:

    • 感谢您的回答。但是我将新的数据点附加到序列中,因此序列的长度在每次迭代中增加 1
    • 是的,但是在下一步中,您将写入大小为 150 (sequence = sequence[next_timestep: range_to_predict]) 的 sequence 变量新数组。您可以为其创建单独的变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2018-04-13
    • 2020-07-13
    相关资源
    最近更新 更多