在本节中,我们将更新上一节中开发的编码器-解码器LSTM,使用8个时间序列变量中的每一个来预测下一个标准周的每日总功耗。我们将通过将每个一维时间序列作为单独的输入序列提供给模型来实现这一点。LSTM将依次创建每个输入序列的内部表示,这些输入序列将由解码器一起解释。使用多元输入有助于解决这样的问题,即输出序列是来自多个不同特征的先前时间步长的某个函数,而不只是(或包括)预测的特征。目前还不清楚在电力消耗问题上是否存在这种情况,但我们可以探索它。首先,我们必须更新培训数据的准备工作,使其包含所有八个特性,而不仅仅是每天消耗的总能量。

它需要一行更改:

X.append(data[in_start:in_end, :])

完成此更改的to_supervised()函数如下所示。

# convert history into inputs and outputs
def to_supervised(train, n_input, n_out=7):# flatten datadata = train.reshape((train.shape[0]*train.shape[1], train.shape[2]))X, y = list(), list()in_start = 0# step over the entire history one time step at a timefor _ in range(len(data)):# define the end of the input sequencein_end = in_start + n_inputout_end = in_end + n_out# ensure we have enough data for this instanceif out_end < len(data):X.append(data[in_start:in_end, :])y.append(data[in_end:out_end, 0])# move along one time stepin_start += 1return array(X), array(y)

我们还必须更新使用fit模型进行预测的函数,以使用前面时间步骤中的所有8个特性。还有一个小变化:

# retrieve last observations for input data
input_x = data[-n_input:, :]
# reshape into [1, n_input, n]
input_x = input_x.reshape((1, input_x.shape[0], input_x.shape[1]))

修改后的complete forecast()函数如下:

# make a forecast
def forecast(model, history, n_input):# flatten datadata = array(history)data = data.reshape((data.shape[0]*data.shape[1], data.shape[2]))# retrieve last observations for input datainput_x = data[-n_input:, :]# reshape into [1, n_input, n]input_x = input_x.reshape((1, input_x.shape[0], input_x.shape[1]))# forecast the next weekyhat = model.predict(input_x, verbose=0)# we only want the vector forecastyhat = yhat[0]return yhat

直接使用相同的模型体系结构和配置,尽管我们将把训练周期的数量从20个增加到50个,因为输入数据量增加了8倍。

完整的示例如下所示。

# multivariate multi-step encoder-decoder lstm
from math import sqrt
from numpy import split
from numpy import array
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import LSTM
from keras.layers import RepeatVector
from keras.layers import TimeDistributed# split a univariate dataset into train/test sets
def split_dataset(data):# split into standard weekstrain, test = data[1:-328], data[-328:-6]# restructure into windows of weekly datatrain = array(split(train, len(train)/7))test = array(split(test, len(test)/7))return train, test# evaluate one or more weekly forecasts against expected values
def evaluate_forecasts(actual, predicted):scores = list()# calculate an RMSE score for each dayfor i in range(actual.shape[1]):# calculate msemse = mean_squared_error(actual[:, i], predicted[:, i])# calculate rmsermse = sqrt(mse)# storescores.append(rmse)# calculate overall RMSEs = 0for row in range(actual.shape[0]):for col in range(actual.shape[1]):s += (actual[row, col] - predicted[row, col])**2score = sqrt(s / (actual.shape[0] * actual.shape[1]))return score, scores# summarize scores
def summarize_scores(name, score, scores):s_scores = ', '.join(['%.1f' % s for s in scores])print('%s: [%.3f] %s' % (name, score, s_scores))# convert history into inputs and outputs
def to_supervised(train, n_input, n_out=7):# flatten datadata = train.reshape((train.shape[0]*train.shape[1], train.shape[2]))X, y = list(), list()in_start = 0# step over the entire history one time step at a timefor _ in range(len(data)):# define the end of the input sequencein_end = in_start + n_inputout_end = in_end + n_out# ensure we have enough data for this instanceif out_end < len(data):X.append(data[in_start:in_end, :])y.append(data[in_end:out_end, 0])# move along one time stepin_start += 1return array(X), array(y)# train the model
def build_model(train, n_input):# prepare datatrain_x, train_y = to_supervised(train, n_input)# define parametersverbose, epochs, batch_size = 0, 50, 16n_timesteps, n_features, n_outputs = train_x.shape[1], train_x.shape[2], train_y.shape[1]# reshape output into [samples, timesteps, features]train_y = train_y.reshape((train_y.shape[0], train_y.shape[1], 1))# define modelmodel = Sequential()model.add(LSTM(200, activation='relu', input_shape=(n_timesteps, n_features)))model.add(RepeatVector(n_outputs))model.add(LSTM(200, activation='relu', return_sequences=True))model.add(TimeDistributed(Dense(100, activation='relu')))model.add(TimeDistributed(Dense(1)))model.compile(loss='mse', optimizer='adam')# fit networkmodel.fit(train_x, train_y, epochs=epochs, batch_size=batch_size, verbose=verbose)return model# make a forecast
def forecast(model, history, n_input):# flatten datadata = array(history)data = data.reshape((data.shape[0]*data.shape[1], data.shape[2]))# retrieve last observations for input datainput_x = data[-n_input:, :]# reshape into [1, n_input, n]input_x = input_x.reshape((1, input_x.shape[0], input_x.shape[1]))# forecast the next weekyhat = model.predict(input_x, verbose=0)# we only want the vector forecastyhat = yhat[0]return yhat# evaluate a single model
def evaluate_model(train, test, n_input):# fit modelmodel = build_model(train, n_input)# history is a list of weekly datahistory = [x for x in train]# walk-forward validation over each weekpredictions = list()for i in range(len(test)):# predict the weekyhat_sequence = forecast(model, history, n_input)# store the predictionspredictions.append(yhat_sequence)# get real observation and add to history for predicting the next weekhistory.append(test[i, :])# evaluate predictions days for each weekpredictions = array(predictions)score, scores = evaluate_forecasts(test[:, :, 0], predictions)return score, scores# load the new file
dataset = read_csv('household_power_consumption_days.csv', header=0, infer_datetime_format=True, parse_dates=['datetime'], index_col=['datetime'])
# split into train and test
train, test = split_dataset(dataset.values)
# evaluate model and get scores
n_input = 14
score, scores = evaluate_model(train, test, n_input)
# summarize scores
summarize_scores('lstm', score, scores)
# plot scores
days = ['sun', 'mon', 'tue', 'wed', 'thr', 'fri', 'sat']
pyplot.plot(days, scores, marker='o', label='lstm')
pyplot.show()

Encoder-Decoder LSTM模型对家庭用电进行多步时间序列预测(多变量输入)相关推荐

  1. 开发和设计实现LSTM模型用于家庭用电的多步时间序列预测

    鉴于智能电表的兴起以及太阳能电池板等发电技术的广泛采用,有大量的用电数据可供选择.该数据代表了多变量时间序列的功率相关变量,这些变量又可用于建模甚至预测未来的电力消耗. 与其他机器学习算法不同,长期短 ...

  2. LSTM模型对家庭用电进行多步时间序列预测

    随着智能电表的兴起和太阳能电池板等发电技术的广泛应用,有大量可用的用电数据.这些数据代表了一系列与电力相关的多元时间序列,进而可以用来建模甚至预测未来的用电量.与其他机器学习算法不同,长短时记忆递归神 ...

  3. Encoder-Decoder LSTM Model模型对家庭用电进行多步时间序列预测

    在本节中,我们可以更新普通的LSTM以使用编解码器模型.这意味着模型不会直接输出向量序列.相反,该模型将由两个子模型组成,用于读取和编码输入序列的编码器,以及读取编码的输入序列并对输出序列中的每个元素 ...

  4. python用电度数设计_Python时间序列预测实战(电力负荷预测)

    这是我之前工作做的一个项目 import os import pandas as pd import numpy path = "E:/工作/负荷预测/历史负荷数据-每天" #文件 ...

  5. 时间序列预测07:如何开发LSTM实现时间序列预测详解 01 Univariate LSTM

    [时间序列预测/分类] 全系列60篇由浅入深的博文汇总:传送门 Long Short-Term Memory networks(长-短期记忆网络),简称 LSTMs,可用于时间序列预测.有许多类型的L ...

  6. 基于Keras的LSTM多变量时间序列预测(北京PM2.5数据集pollution.csv)

                                 基于Keras的LSTM多变量时间序列预测 传统的线性模型难以解决多变量或多输入问题,而神经网络如LSTM则擅长于处理多个变量的问题,该特性使 ...

  7. 如何建立Multi-Step(多步预测)的LSTM时间序列模型(以对家庭用电预测为例)

    译自How to Develop LSTM Models for Multi-Step Time Series Forecasting of Household Power Consumption~ ...

  8. 最后一期:如何更新LSTM模型?(附代码)| 博士带你学LSTM

    最后一期:如何更新LSTM模型?(附代码)| 博士带你学LSTM LSTM是一种时间递归神经网络,适合于处理和预测时间序列中间隔和延迟相对较长的重要事件.在自然语言处理.语言识别等一系列的应用上都取得 ...

  9. LSTM及peehole LSTM模型

    1.LSTM模型 其中ooo表示元素相乘,遗忘门fff,输入们iii,输出门ooo,σgσ_gσg​,σcσ_cσc​分别为sigmoid函数与tanh函数.WWW和bbb分别为权重和偏置.c~\wi ...

最新文章

  1. U3D 代码自动化生成定制预置体的旋转问题
  2. 端计算(4)-kotlin(2)
  3. nginx模块_使用gdb调试nginx源码
  4. 是栈还是队列c语言实验报告怎么写,队列和栈(C语言)
  5. mysql几个timeout参数_MySQL中 timeout相关参数解析
  6. 世界上最欢乐的职业,可能就是蹦极的工作人员了!
  7. 华为开始对嵌入式开发者下手了!
  8. java 实现websocket的两种方式
  9. 我对NHibernate的感受(3):有些尴尬的集合支持
  10. TextView赋值int型,并显示
  11. Hibernate常出现的报错
  12. java jxls导出excel
  13. 高雅复古立式钢琴音源 Native Instruments The Gentleman Kontakt
  14. 【安全知识分享】PPTX|精益安全管理(130页)(附下载)
  15. 群里的初级工程师求助说,要采集采招数据,必须给他安排上
  16. NAS系列 为什么你需要一台NAS
  17. mysql查找三个年龄最大的人_mysql 查寻重复姓名且年龄最大的列表 - count
  18. EtherCAT--介绍
  19. 简黑时钟 AClock 2.8 中文版 ,一款全屏翻页时钟/倒计时/番茄钟
  20. 在英特尔硬件上部署深度学习模型的无代码方法 OpenVINO 深度学习工作台的三部分系列文章 - CPU AI 第一部

热门文章

  1. 【夜曲编程Python数据分析】百题斩最后一题!!
  2. 360SEO 如何创建和提交360网站地图
  3. NYOJ 99-单词拼接
  4. 树莓派控制局域网内笔记本电脑开关机
  5. 【机器学习算法】决策树案例详解
  6. 结论太小,以致于大家都看不见它
  7. 已经31岁了,阿里P6还有必要去吗?
  8. Linux CentOS7下载实操
  9. 理解残差神经网络(Resnet)
  10. Vagrant:vagrant up卡死