python - 递归神经网络 ValueError : Found array with dim 3. 估计器预期 <= 2

标签 python lstm

我正在使用以下代码运行 LSTM、GRU 和 bilstm 模型

# Create BiLSTM model
def create_model_bilstm(units):
    model = Sequential()
    model.add(Bidirectional(LSTM(units = units,                             
              return_sequences=True),
              input_shape=(X_train.shape[1], X_train.shape[2])))
    #model.add(Bidirectional(LSTM(units = units)))
    model.add(Dense(1))
    #Compile model
    model.compile(loss='mse', optimizer='adam')
    return model

# Create LSTM or GRU model
def create_model(units, m):
    model = Sequential()
    model.add(m (units = units, return_sequences = True,
                input_shape = [X_train.shape[1], X_train.shape[2]]))
    model.add(Dropout(0.1))
    #model.add(m (units = units))
    #model.add(Dropout(0.2))
    model.add(Dense(units = 1))
    #Compile model
    model.compile(loss='mse', optimizer='adam')
    return model

# BiLSTM
model_bilstm = create_model_bilstm(20)

# GRU and LSTM
model_gru = create_model(50, GRU)
model_lstm = create_model(20, LSTM)

# Fit BiLSTM, LSTM and GRU
def fit_model(model):
    early_stop = EarlyStopping(monitor = 'val_loss',
                                               patience = 100)
    
    history = model.fit(X_train, y_train, epochs = 700,  
                        validation_split = 0.2, batch_size = 32, 
                        shuffle = False, callbacks = [early_stop])
    return history

history_bilstm = fit_model(model_bilstm)
history_lstm = fit_model(model_lstm)
history_gru = fit_model(model_gru)

这一切运行顺利并打印出我的损失图。但是当涉及到预测时,我运行以下代码

# Make prediction
def prediction(model):
    prediction = model.predict(X_test)
    prediction = scaler_y.inverse_transform(prediction)
    return prediction

prediction_bilstm = prediction(model_bilstm)
prediction_lstm = prediction(model_lstm)
prediction_gru = prediction(model_gru)

我收到以下错误

   ValueError Traceback (most recent call last)
<ipython-input-387-9d45f01ae2a2> in <module>
      5     return prediction
      6 
----> 7 prediction_bilstm = prediction(model_bilstm)
      8 prediction_lstm = prediction(model_lstm)
      9 prediction_gru = prediction(model_gru)

<ipython-input-387-9d45f01ae2a2> in prediction(model)
      2 def prediction(model):
      3     prediction = model.predict(X_test)
----> 4     prediction = scaler_y.inverse_transform(prediction)
      5     return prediction

                         ...

    ValueError: Found array with dim 3. Estimator expected <= 2.

根据我读过的其他帖子,我假设这与我的 X_test 形状有关,所以我尝试将其 reshape 为 2d,但收到另一个错误,告诉我“预期 bi Direction_3_input 有 3 个维度,但得到了形状为数组( 62, 36)”再次出现在第 7 行。

我做错了什么以及如何解决它?

数据说明: 因此,我尝试使用地下水位(34 个特征)、降水量和温度作为输入来预测排放率(目标变量),这总共给了我 36 个特征。我的数据是按月解析的。我使用 63 个观察值进行测试(5 年预测),其余的用于我的训练。

最佳答案

你做错了什么?假设你的输入数据的形状为X_train.shape = [d0,d1,d2],然后在设置 BiLSTM 模型之后喜欢

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Bidirectional,LSTM,Dense

model = tf.keras.Sequential()
model.add(
   tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
         units = 10,                             
         return_sequences=True),
         input_shape=(d1, d2)
         )
      )
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')

我们可以通过以下方式检查您的模型期望的输入和输出形状

>>model.input.shape
TensorShape([None, d1, d2])
>>model.output.shape
TensorShape([None, d1, 1])

因此,您的模型需要输入形状 (n_batch,d1,d2),其中 n_batch 是数据的批量大小,并返回形状 ( n_batch,d1,1),因此是一个3d张量。

现在,如果您为模型提供 3d 张量,model.prediction 方法将成功返回 3d 张量,但是 sklearn.preprocessing.StandardScaler.inverse_transform 仅适用于二维数据,这就是为什么它说

ValueError: Found array with dim 3. Estimator expected <= 2.

另一方面,如果您首先将数据 reshape 为 2d,则 model.prediction 会报错,因为它被设置为期望 3d 张量。

如何修复它?要获得有关如何修复代码的进一步帮助,您需要向我们提供有关您的模型期望的更多详细信息做什么,尤其是您希望 BiLSTM 模型具有什么输出形状。我假设您实际上希望 BiLSTM 模型为每个样本返回一个标量,因此额外的 Flatten 层可能会达到目的:

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Bidirectional,LSTM,Dense,Flatten

model = tf.keras.Sequential()
model.add(
   tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
         units = 10,                             
         return_sequences=True),
         input_shape=(d1, d2)
         )
      )
model.add(Flatten()) #<-- additional flatten-layer
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')

关于python - 递归神经网络 ValueError : Found array with dim 3. 估计器预期 <= 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64351475/

相关文章:

python - 来自 Windows 客户端的无密码 Python LDAP3 身份验证

Python实时忙轮询数据库

python - 塑造 LSTM 的数据,并将密集层的输出馈送到 LSTM

python - 如何将给定索引处的值(多个索引)插入到张量中?

python - 事前评估-IndexError : index 0 is out of bounds for axis 0 with size 0

python - 使用 Python 查找目录中的所有 CSV 文件

r - Keras 如何预测 11106 个不同客户的(单独)销售序列,每个客户都有一系列不同的长度(从 1 到 15 个周期)

python - LSTM 0 准确率

tensorflow - "truncated gradients"在 LSTM 中意味着什么?

类中的 Python 装饰器