【问题标题】:Keras stateful LSTM errorKeras 有状态的 LSTM 错误
【发布时间】:2026-01-03 17:05:02
【问题描述】:

我想在 keras 中创建有状态的 LSTM。我给了它一个这样的命令:

model.add(LSTM(300,input_dim=4,activation='tanh',stateful=True,batch_input_shape=(19,13,4),return_sequences=True))

其中批量大小=19。但是运行时会报错

 Exception: In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: 8816 samples. Batch size: 32.

我没有在脚本中的任何地方指定批处理大小 32,而 19 可以被 8816 整除

【问题讨论】:

    标签: keras lstm


    【解决方案1】:

    model.fit() 进行批处理(例如,与 model.train_on_batch 相反)。因此它有一个batch_size 参数,默认为 32。

    将此更改为您的输入批量大小,它应该可以按预期工作。

    例子:

    batch_size = 19
    
    model = Sequential()
    model.add(LSTM(300,input_dim=4,activation='tanh',stateful=True,batch_input_shape=(19,13,4),return_sequences=True))
    
    model.fit(x, y, batch_size=batch_size)
    

    【讨论】:

    • 那么你应该用一个复制错误的最小工作示例来更新你的问题。
    • 如果你使用validation_data,那里的样本数也必须能被batch_size整除。
    【解决方案2】:

    有两种情况可能会出现 batch_size 错误。

    1. model.fit(train_x, train_y, batch_size= n_batch, shuffle=True,verbose=2)

    2. trainPredict = model.predict(train_x, batch_size=n_batch) 或 testPredict = model.predict(test_x,batch_size=n_batch)

    在这两种情况下,您都必须提及不。批次。

    注意:我们需要同时预测训练和测试,因此最佳做法是将测试和训练分开,使您的批量大小是两者的倍数 stateful=True案例

    【讨论】:

      【解决方案3】:

      动态调整数据和批次的大小:

      大小数据和训练样本拆分:

      data_size = int(len(supervised_values))
      train_size_initial = int(data_size * train_split)
      x_samples = supervised_values[-data_size:, :]
      

      训练样本的大小到批量大小:

      if train_size_initial < batch_size_div:
          batch_size = 1
      else:
          batch_size = int(train_size_initial / batch_size_div)
      train_size = int(int(train_size_initial / batch_size) * batch_size)  # provide even division of training / batches
      val_size = int(int((data_size - train_size) / batch_size) * batch_size)  # provide even division of val / batches
      print('Data Size: {}  Train Size: {}   Batch Size: {}'.format(data_size, train_size, batch_size))
      

      将数据拆分为训练集和验证集

      train, val = x_samples[0:train_size, 0:-1], x_samples[train_size:train_size + val_size, 0:-1]
      

      【讨论】:

        【解决方案4】:

        训练和验证数据都需要被批量大小整除。确保使用批量大小的模型的任何部分都采用相同的数字(例如,LSTM 层中的batch_input_shapemodel.fit()model.predict() 中的batch_size。如果需要,对训练和验证数据进行下采样这项工作。

        例如

        >>> batch_size = 100
        >>> print(x_samples_train.shape)
        >>> print(x_samples_validation.shape)
            (42028, 24, 14)
            (10451, 24, 14) 
        
        # Down-sample so training and validation are both divisible by batch_size
        >>> x_samples_train_ds = x_samples_train[-42000:]
        >>> print(x_samples_train_ds.shape)
        >>> y_samples_train_ds = y_samples_train[-42000:]
        >>> print(y_samples_train_ds.shape)
            (42000, 24, 14)
            (42000,)
        >>> x_samples_validation_ds = x_samples_validation[-10000:]
        >>> print(x_samples_validation_ds.shape)
        >>> y_samples_validation_ds = y_samples_validation[-10000:]
        >>> print(y_samples_validation_ds.shape)
            (10000, 24, 14)
            (10000,)
        

        【讨论】: