【问题标题】:TensorFlow different input and output shapes for stateful LSTM modelTensorFlow 有状态 LSTM 模型的不同输入和输出形状
【发布时间】:2020-11-15 16:00:43
【问题描述】:

我想创建一个“顺序”模型(您可能已经猜到的时间序列模型),它采用 20 天的特征大小为 2 的过去数据,并将 1 天预测为与2 相同特征大小的未来。

我发现你需要为有状态 LSTM 模型指定批量大小,所以如果我指定批量大小为 32,例如,模型的最终输出形状为 (32, 2),我认为这意味着模型预测 32 未来几天而不是 1

我将如何继续修复它?

另外,在我解决问题之前询问;例如,如果我指定批量大小为32,但我想预测形状为(1, 20, 2) 的输入,模型会正确预测还是什么,因为我将批量大小从32 更改为1。谢谢。

【问题讨论】:

    标签: python tensorflow keras lstm lstm-stateful


    【解决方案1】:

    您不需要指定 batch_size。但是你应该提供 3-d 张量:

    import tensorflow as tf
    from tensorflow.keras.layers import Input, LSTM, Dense
    from tensorflow.keras import Model, Sequential
    features = 2
    dim = 128
    new_model = Sequential([
      LSTM(dim, stateful=True, return_sequences = True),
      Dense(2)
    ])
    
    number_of_sequences = 1000
    sequence_length = 20
    input = tf.random.uniform([number_of_sequences, sequence_length, features], dtype=tf.float32)
    output = new_model(input) # shape is (number_of_sequences, sequence_length, features)
    predicted = output[:,-1] # shape is (number_of_sequences, 1, features)
    

    形状为 (32, 2) 表示您的序列长度为 32。

    批量大小是训练的一个参数(在反向传播误差之前应该向模型输入多少序列 - 请参阅随机梯度下降法)。它不会影响您的数据(应该是 3-d -(序列数、序列长度、特征))。

    如果您只需要预测一个序列 - 只需将形状为 (1, 20, 2) 的张量输入模型即可。

    【讨论】:

    • 感谢您的回答。我认为这解决了它,但只是在我接受你的答案之前确认,因为你忘记了参数,这适用于stateful=True 对吗?
    • 其实多了一个问题:当你说'sequence'时,你的意思是'batch'吗?我是这个“时间序列预测”的新手,所以请原谅我的不专业。
    • 抱歉 - 不明白。序列是 [[0, 1], [2, 3] ...]。 Batch是训练的参数:调用'fit()'时可以设置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多