我是神经网络的新手,我想用它们与其他机器学习方法进行比较。我有一个大约两年的多元时间序列数据。我想使用LSTM根据其他变量预测未来几天的“y”。我的数据的最后一天是2020-07-31
df.tail()
y holidays day_of_month day_of_week month quarter
Date
2020-07-27 32500 0 27 0 7 3
2020-07-28 33280 0 28 1 7 3
2020-07-29 31110 0 29 2 7 3
2020-07-30 37720 0 30 3 7 3
2020-07-31 32240 0 31 4 7 3
为了训练LSTM模型,我还将数据分为训练数据和测试数据
from sklearn.model_selection import train_test_split
split_date = '2020-07-27' #to predict the next 4 days
df_train = df.loc[df.index <= split_date].copy()
df_test = df.loc[df.index > split_date].copy()
X1=df_train[['day_of_month','day_of_week','month','quarter','holidays']]
y1=df_train['y']
X2=df_test[['day_of_month','day_of_week','month','quarter','holidays']]
y2=df_test['y']
X_train, y_train =X1, y1
X_test, y_test = X2,y2
因为我正在使用LSTM,所以需要进行一些缩放:
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
现在,我们来看看最难的部分:模型
num_units=50
activation_function = 'sigmoid'
optimizer = 'adam'
loss_function = 'mean_squared_error'
batch_size = 10
num_epochs = 100
# Initialize the RNN
regressor = Sequential()
# Adding the input layer and the LSTM layer
regressor.add(LSTM(units = num_units, return_sequences=True ,activation = activation_function,
input_shape=(X_train.shape[1], 1)))
# Adding the output layer
regressor.add(Dense(units = 1))
# Compiling the RNN
regressor.compile(optimizer = optimizer, loss = loss_function)
# Using the training set to train the model
regressor.fit(X_train_scaled, y_train, batch_size = batch_size, epochs = num_epochs)
但是,我收到以下错误:
ValueError: Input 0 of layer sequential_11 is incompatible with the layer: expected ndim=3, found
ndim=2. Full shape received: [None, 5]
我不明白我们如何选择输入的参数或形状。我看过一些视频,阅读了一些Github页面,每个人似乎都以不同的方式运行LSTM,这使得它更难实现。前面的错误可能来自形状,但除此之外,其他所有错误都正确吗?我怎样才能解决这个问题?谢谢
编辑:This类似的问题不能解决我的问题。。我已经从那里尝试了解决方案
x_train = X_train_scaled.reshape(-1, 1, 5)
x_test = X_test_scaled.reshape(-1, 1, 5)
(我的X_测试和y_测试只有一列)。而且这个解决方案似乎也不起作用。我现在得到这个错误:
ValueError: Input 0 is incompatible with layer sequential_22: expected shape=
(None, None, 1), found shape=[None, 1, 5]
这是一个使用LSTM解决的多元回归问题。在开始编写代码之前,让我们先看看它的含义
问题陈述:
k
天内,您每天有5
功能holidays, day_of_month, day_of_week,month,quarter
y
天的n
正在创建窗口数据集:
p
记录没有可用的预测,其中p
是序列长度李>timeseries_dataset_from_array
方法创建窗口数据集李>LSTM模型
因此,我们希望达到的效果如下:
对于每个LSTM单元展开,我们传入当天的5个特征,并在
m
时间内展开,其中m
是序列长度。我们正在预测最后一天的天气代码:
输出:
输入:
问题是,您的模型需要一个形状为
(batch, sequence, features)
的3D输入,但您的X_train
实际上是一个数据帧切片,因此2D数组:我假设您的列应该是您的特性,所以您通常会对df进行“堆栈切片”,以便
X_train
看起来像这样:以下是形状
(15,5)
的虚拟2D数据集:您可以对其进行重塑以添加批次维度,例如
(15,1,5)
:数据相同,但呈现方式不同。现在在这个例子中,
batch = 15
和sequence = 1
,我不知道在你的例子中序列的长度是多少,但它可以是任何东西型号:
现在在您的模型中,
keras
input_shape
expect(batch, sequence, features)
,当您传递此消息时:这就是您的模型所看到的:
(None, Sequence = X_train.shape[1] , num_features = 1)
None
用于批处理维度。我不认为这就是你想要做的,一旦你改变了形状,你也应该修正input_shape
以匹配新的数组相关问题 更多 >
编程相关推荐