原文链接

from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# convert series to supervised learningfrom pandas import read_csv
from datetime import datetime
# load data
def parse(x):return datetime.strptime(x, '%Y %m %d %H')
dataset = read_csv('lg.csv',  parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse)
dataset.drop('No', axis=1, inplace=True)
# manually specify column names
dataset.columns = ['pollution', 'dew', 'temp', 'press', 'wnd_dir', 'wnd_spd', 'snow', 'rain']
dataset.index.name = 'date'
# mark all NA values with 0
dataset['pollution'].fillna(0, inplace=True)
# drop the first 24 hours
dataset = dataset[24:]
# summarize first 5 rows
print(dataset.head(5))
# save to file
dataset.to_csv('pollution.csv')def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):n_vars = 1 if type(data) is list else data.shape[1]df = DataFrame(data)cols, names = list(), list()# input sequence (t-n, ... t-1)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)]# forecast sequence (t, t+1, ... t+n)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 togetheragg = concat(cols, axis=1)agg.columns = names# drop rows with NaN valuesif dropnan:agg.dropna(inplace=True)return agg
# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# frame as supervised learning
reframed = series_to_supervised(scaled, 1, 1)
# drop columns we don't want to predict
reframed.drop(reframed.columns[[9,10,11,12,13,14,15]], axis=1, inplace=True)
print(reframed.head())
# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
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]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
# 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=50, batch_size=72, 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
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
inv_y = scaler.inverse_transform(test_X)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)


代码下载

keras 多维时间序列预测相关推荐

  1. Kesci: Keras 实现 LSTM——时间序列预测

    博主之前参与的一个科研项目是用 LSTM 结合 Attention 机制依据作物生长期内气象环境因素预测作物产量.本篇博客将介绍如何用 keras 深度学习的框架搭建 LSTM 模型对时间序列做预测. ...

  2. Keras 实现 LSTM时间序列预测

    向AI转型的程序员都关注了这个号

  3. 基于 keras lstm 的时间序列预测 上证指数 股票价格预测 十份数据超全数据 毕业设计

    项目参考:https://www.bilibili.com/video/BV1Fg4y1t7MA/ 附完整代码数据: 运行参考:

  4. 【深度学习论文翻译】基于LSTM深度神经网络的时间序列预测(Time Series Prediction Using LSTM Deep Neural Networks)

    目录 一.前言 二.摘要 三.什么是LSTM神经元? 四.简单正弦波示例 五. 不那么简单的股票市场 六.多维LSTM预测 七.结论 一.前言 最近需要用到时间序列,在网上也找到了一篇相关的文章及源代 ...

  5. 基于Keras的LSTM多变量时间序列预测

    LSTM是一种时间递归神经网络,它出现的原因是为了解决RNN的一个致命的缺陷.原生的RNN会遇到一个很大的问题,叫做The vanishing gradient problem for RNNs,也就 ...

  6. bagging和时间序列预测_时间序列的LSTM模型预测——基于Keras

    一.问题背景     现实生活中,在一系列时间点上观测数据是司空见惯的活动,在农业.商业.气象军事和医疗等研究领域都包含大量的时间序列数据.时间序列的预测指的是基于序列的历史数据,以及可能对结果产生影 ...

  7. 使用Keras框架进行单变量时间序列预测——以上证指数为例

    文章目录 写在前面 代码及其解释 模型的缺点&分析 后记 写在前面 之前一直纠结于DL框架的选用,直到看到了<Practical Time Series Analysis>这本书, ...

  8. keras进行时间序列预测

    时间序列预测 概述 数据集的预处理 基准方法 调优 增加dropout层 增加网络深度 小结和补充 概述 用深度学习的方法进行端到端的时间序列预测需要一下几个步骤 1.对数据进行预处理,比如数据清洗, ...

  9. 【深度学习 项目实战】Keras深度学习多变量时间序列预测的LSTM模型

    无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家.教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家.点这里可以跳转到教程.人工智能教程 本篇文章将介绍基于 ...

最新文章

  1. uni-app在iOS移动端页面上下滑动关闭(页面回弹问题,非刷新)
  2. 新站如何使用标签才对SEO优化更有利
  3. Java多线程-CountDownLatch用法
  4. 写给新手的WebAPI实践
  5. 笔记,Vector类模板的基本功能
  6. 明年新iphone使用增强版5nm芯片_苹果A15芯片或将采用台积电5nm+工艺!性能提升极强...
  7. Detected that PyTorch and torch_sparse were compiled with different CUDA versions. PyTorch has CUDA
  8. C++ 动态联编实现原理分析
  9. 【转】CSS transitions#CSS3变换入门
  10. Linux中的7件武器详解
  11. 【从C到C++学习笔记】面向对象/抽象/封装/继承/多态
  12. 六、瞰景Smart3D三维重建
  13. DWG文件打开乱码怎么办?
  14. Linux内核态调用用户态函数
  15. mac mini 储存文件的服务器,另一种“NAS”的玩法---mac系统的远程管理和文件共享...
  16. CC2640R2F BLE5.0 CC2640R2F软件架构
  17. 生成特定于查询的类API摘要 (Generating Query-Specific Class API Summaries)
  18. 华为IPsec实现支部与支部间借助总部进行隧道中转
  19. 按键精灵:函数之可选参数
  20. 根据年份提取dblp内容

热门文章

  1. s:textfield format date
  2. nodejs-stream部分
  3. Oracle的FIXED_DATE参数
  4. “隐私快递单”的保护理念应全面推行
  5. Web项目中文件上传Filter处理
  6. Linux 入门学习-LINUX基本认识及常用命令
  7. 记:PyInstaller打包一个最简单的kivy应用
  8. openstack之neutron linuxbridge + vlan组网
  9. .htm .html .shtml的区别
  10. sql server2005 出现一个或多个参数无效