首页 > 解决方案 > LSTM RNN 同时预测多个时间步长和多个特征

问题描述

我有一个来自 4 个温度传感器的数据集,测量建筑物内/周围的不同位置: 在此处输入图像描述

我正在训练一个模型,该模型接受形状 (96, 4) 的输入,4 个传感器的 96 个时间步长。据此,我想为每个传感器预测 48 个点,形状 (48, 4)。

到目前为止,我已经有了一个只能预测一个传感器的实现。我主要遵循TensorFlow 教程中的这一部分

我的火车 X 是形状 (6681, 96, 4),火车 Y 是形状 (6681, 48),因为我只将其限制为一个传感器。如果我只是在训练时将训练 Y 更改为 (6681, 48, 4),我当然会得到ValueError: Dimensions must be equal, but are 48 and 4 for 'loss/dense_loss/sub' (op: 'Sub') with input shapes: [?,48], [?,48,4].,因为我的模型并不期望这种形状。

我遇到困难的地方是我的 LSTM 层的输入/输出形状。我只是不知道如何以 (BATCH_SIZE, 48, 4) 的形状完成。

这是我目前的图层设置:

tf.keras.backend.clear_session()


print("Input shape", x_train_multi.shape[-2:])

multi_step_model = tf.keras.models.Sequential()
multi_step_model.add(tf.keras.layers.LSTM(32,
                                          return_sequences=True,
                                          input_shape=x_train_multi.shape[-2:]))
multi_step_model.add(tf.keras.layers.Dropout(rate=0.5)) # Dropout layer after each LSTM to reduce overfitting.
multi_step_model.add(tf.keras.layers.LSTM(16, activation='relu'))
multi_step_model.add(tf.keras.layers.Dropout(rate=0.5)) 
# The argument to Dense shapes the results to give the number of time steps we want.
# But how do I make it keep 4 features as well?!?
multi_step_model.add(tf.keras.layers.Dense(future_target / STEP))
multi_step_model.compile(optimizer=tf.keras.optimizers.RMSprop(clipvalue=1.0), loss='mae')

# Shape of predictions
for x, y in val_data_multi.take(1):
    print ("Prediction shape", multi_step_model.predict(x).shape)

一些想法:

谢谢!:)

标签: pythontensorflowkeraslstmrecurrent-neural-network

解决方案


最后,我设法通过使用 Dense 层实现了这一点,该层具有我想要的时间步数乘以我预测的特征数。然后,我将其重新塑造成我想要的输出形状。

我不确定这是否是执行此操作的最佳方法,但它可以正常工作。

#Experimental code for predicting multiple sensors
import tensorflow.keras.layers as tfl

tf.keras.backend.clear_session()


print("Input shape", x_train_multi.shape[-2:]) 
# Input shape (96, 4)

multi_step_model = tf.keras.Sequential()
multi_step_model.add(tf.keras.layers.LSTM(32, return_sequences=True, input_shape=x_train_multi.shape[-2:]))
multi_step_model.add(tf.keras.layers.Dropout(rate=0.5))
multi_step_model.add(tf.keras.layers.LSTM(16, return_sequences=False, activation='relu'))
multi_step_model.add(tf.keras.layers.Dropout(rate=0.5)) 
print("After LSTMs", multi_step_model.output_shape)  
# After LSTMs (None, 16)
multi_step_model.add(tf.keras.layers.Dense((future_target / STEP) * 4))
print("After Dense Layer", multi_step_model.output_shape) 
#  After Dense Layer (None, 192)
multi_step_model.add(tf.keras.layers.Reshape((int(future_target / STEP), 4)))
print("After Reshape", multi_step_model.output_shape)
# After Reshape (None, 48, 4)


multi_step_model.compile(optimizer=tf.keras.optimizers.RMSprop(clipvalue=1.0), loss='mae')

# Shape of predictions
for x, y in val_data_multi.take(1):
    print ("Prediction shape", multi_step_model.predict(x).shape)
    # Prediction shape (512, 48, 4)

推荐阅读