使用LSTM进行多属性预测,现在是前一天真实值预测后一天虚拟值,怎么改成用前一天预测的值预测下一天的值,我在网上看到说创建一个预测数组,每预测一个Y就往数组里放一个,同时更新你用来预测的自变量X数组,剔除最早的X,把预测值加入到X里,依次往后预测,但最开始就定义了训练数据和测试数据,应该怎么改
给定输入、输出序列的长度,它可以自动地将时间序列数据转型为适用于监督学习的数据
最初代码来自https://blog.csdn.net/u012735708/article/details/82769711
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
# n_vars为列数,此处为4
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, names = list(), list()
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
# put it all together
agg = pd.concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
# 它的返回值只有一个, 即转型后适用于监督学习的DataFrame
return agg
## load dataset
dataset = pd.read_csv('data_set/air_pollution_new_预测2.csv', header=0, index_col=0)
values = dataset.values
# LabelEncoder是对不连续的数字或文本编号。
encoder = LabelEncoder()
values[:,2] = encoder.fit_transform(values[:, 2])
# ensure all data is float
values = values.astype('float32')
# 数据归一化:此时已经去掉时间值,第一列为污染指数PM2.5:
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# 将数据规整成为可以放进神经网络的dataframe。
reframed = series_to_supervised(scaled, 1, 1)
# drop columns we don't want to predict
# reframed一共有8列,首先去除6-8列:经过这一变化,
# 数据集的最后一行表示下一刻空气的污染程度。第一行表示这一刻空气的污染程度
# 模型通过对前4行的数据,即这一刻的数据,预测第5行,即下一刻的污染程度
reframed.drop(reframed.columns[[5,6,7]], axis=1, inplace=True)
# 整理好所需要的数据:
# split into train and test sets
values = reframed.values
n_train_hours = 30 * 3
train = values[:n_train_hours, :]
test = values[n_train_hours:,:]#n_train_hours+10
# 取所有行,区分最后一列:[:, :-1]:不取最后一列;[:, -1]获取最后一列
# 经过上面的处理之后形成了新的数列,然后整理出y值
# X是前4行,Y是第5行。
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=300, batch_size=30, validation_data=(test_X, test_y),
verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
# 显示图例:
pyplot.legend()
pyplot.show()
# make a prediction
# 1、测试集是处理之后的数据:新的数据在输入模型之前需要进行一系列同上的操作,
# 所以需要实现数据的预处理模型,将其整理为一个对应的方法。
# 2、将整理好的数据放入模型中处理:
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
print(test_X)
# invert scaling for forecast concatenate:数据拼接
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
print(inv_yhat)
# 3、是将标准化后的数据转换为原始数据:
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:, 0]
inv_yhat = np.array(inv_yhat)
inv_yhat = np.trunc(inv_yhat)
# invert scaling for actual
inv_y = scaler.inverse_transform(test_X)
inv_y = inv_y[:, 0]