时间序列预测(二)—— AR模型

欢迎大家来我的个人博客网站观看原文:https://xkw168.github.io/2019/05/20/时间序列预测-二-AR模型.html

文章链接

(一)数据预处理

(二)AR模型(自回归模型)

(三)Xgboost模型

(四)LSTM模型

(五)Prophet模型(自回归模型)


模型原理

  AR(auto-regressive)模型,亦即是自回归模型,是时间序列分析模型中最简单的两个模型其中之一(另一个是MA/Moving Average/滑动平均模型)。其原理是利用观测点前若干时刻的变量的线性组合来描述观测点后若干时刻变量的值,属于线性回归模型。AR§模型认为,任意时刻的观测值xtx_txt​取决于前面p个时刻的观测值加上一个误差,见下式:
xt=ϕ0+ϕ1xt−1+ϕ2xt−2+⋯+ϕpxt−p+εtx_t = \phi_0 + \phi_1x_{t-1} + \phi_2x_{t-2} + \dots + \phi_px_{t-p} + \varepsilon_txt​=ϕ0​+ϕ1​xt−1​+ϕ2​xt−2​+⋯+ϕp​xt−p​+εt​
εt\varepsilon_tεt​是均值为0,方差为σ2\sigma^2σ2的白噪声序列。


模型安装

pip install tensorflow


模型实现

  这里使用的是TensorFlow里面的Timeseries模块实现AR模型

def now():return datetime.now().strftime("%m_%d_%H_%M_%s")def parse_result_tf(tf_data):"""parse the result of model output in tensorflow:param tf_data: the output of tensorflow:return: data in DataFrame format"""return pd.DataFrame.from_dict({"ds": tf_data["times"].reshape(-1), "y": tf_data["mean"].reshape(-1)})def generate_time_series(start_date=datetime(2006, 1, 1),cnt=4018, delta=timedelta(days=1), timestamp=False
):"""generate a time series/index:param start_date: start date:param cnt: date count. If =cnt are specified, delta must not be; one is required:param delta: time delta, default is one day.:param timestamp: output timestamp or format string:return: list of time string or timestamp"""def per_delta():curr = start_datewhile curr < end_date:yield currcurr += deltaend_date = start_date + delta * cnttime_series = []if timestamp:for t in per_delta():time_series.append(t.timestamp())else:for t in per_delta():time_series.append(t)# print(t.strftime("%Y-%m-%d"))return time_seriesdef AR_predict_tf(train_data, evaluation_data, forecast_cnt=365, freq="D", model_dir=""):"""predict time series with auto-regressive model in tensorflow:param train_data: data use to train the model:param evaluation_data: data use to evaluate the model:param forecast_cnt: how many point needed to be predicted:param freq: the interval between time index:param model_dir: directory of pre-trained model(checkpoint, params):return:"""model_directory = "./model/AR_%s" % now()params = {# periodicities of the input data, in the same units as the time feature.# Note this can be a single value or a list of values for multiple periodicities."periodicities": 52,# Number of past time steps of data to look at when doing the regression"input_window_size": 12,# Number of future time steps to predict. Note that setting it to > 1 empirically seems to give a better fit"output_window_size": 5,# The dimensionality of the time series (one for univariate, more than one for multivariate)"num_features": 1,# how many steps we train the model"global_steps": 3000}# if there is a pre-trained model, use parameters from itif model_dir:model_directory = model_dirparams = read_model_param(model_dir + "/params.txt")# create time index for model training(use int)time_int = range(len(train_data) + len(evaluation_data))data_train = {tf.contrib.timeseries.TrainEvalFeatures.TIMES: time_int[:len(train_data)],tf.contrib.timeseries.TrainEvalFeatures.VALUES: train_data["y"],}data_eval = {tf.contrib.timeseries.TrainEvalFeatures.TIMES: time_int[len(train_data):],tf.contrib.timeseries.TrainEvalFeatures.VALUES: evaluation_data["y"],}reader_train = NumpyReader(data_train)reader_eval = NumpyReader(data_eval)"""define in tensorflow/contrib/timeseries/python/timeseries/input_pipeline.pyNote window_size must equal to input_window_size + output_window_size"""train_input_fn = tf.contrib.timeseries.RandomWindowInputFn(reader_train, batch_size=20, window_size=params["input_window_size"] + params["output_window_size"])"""define in tensorflow.contrib.timeseries.python.timeseries.estimatorsperiodicities: periodicities of the input data, in the same units as the time feature. Note this can be a single value or a list of values for multiple periodicitiesnum_features: The dimensionality of the time series (one for univariate, more than one for multivariatewebsite: https://www.tensorflow.org/api_docs/python/tf/contrib/timeseries/ARRegressor"""estimator_ar = tf.contrib.timeseries.ARRegressor(periodicities=params["periodicities"],input_window_size=params["input_window_size"],output_window_size=params["output_window_size"],num_features=params["num_features"],model_dir=model_directory,loss=tf.contrib.timeseries.ARModel.NORMAL_LIKELIHOOD_LOSS)# only train the model when there is no pre-trained modelif not model_dir:estimator_ar.train(input_fn=train_input_fn, steps=params["global_steps"])evaluation_input_fn = tf.contrib.timeseries.WholeDatasetInputFn(reader_eval)evaluation = estimator_ar.evaluate(input_fn=evaluation_input_fn, steps=1)# Predict starting after the evaluation(predictions,) = tuple(estimator_ar.predict(input_fn=tf.contrib.timeseries.predict_continuation_input_fn(evaluation, steps=forecast_cnt)))save_model_param(model_directory, params)if "loss" in evaluation.keys():# mean loss per mini-batchprint("loss:%.5f" % evaluation["loss"])f = open(model_directory + "/%s" % evaluation["loss"], "w")f.close()model_log(evaluation["loss"],average_loss=-1 if "average_loss" not in evaluation.keys() else evaluation["average_loss"],content=model_dir)evaluation = parse_result_tf(evaluation)predictions = parse_result_tf(predictions)# here we should add an offset which is related to window size due to the inherent attribute of ARfirst_date = evaluation_data["ds"].tolist()[0] + \delta_dict[freq] * (params["input_window_size"] + params["output_window_size"])evaluation["ds"] = generate_time_series(first_date, cnt=len(evaluation), delta=delta_dict[freq])latest_date = evaluation["ds"].tolist()[-1]predictions["ds"] = generate_time_series(latest_date, cnt=len(predictions), delta=delta_dict[freq])return evaluation, predictions

关键参数

  • periodicities:数据的周期性,这个周期可以是一个列表(数据拥有多个周期);
  • input_window_size:输入的窗口大小,亦即是做回归分析的时候一次性观察多少个过去观测值;
  • output_window_size:输出窗口的大小,亦即是一次预测多少个未来数据;
  • num_features:时间序列的维度,亦即是一个时间点对应的观察值数量,同时分析多少个时间序列,这个值就为多少;
  • model_dir:预训练模型保存的位置(可以不指定);
  • loss:损失函数;
  • steps:模型的训练迭代次数,这里设置为3000次。

时间序列预测(二)—— AR模型相关推荐

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

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

  2. 时间序列预测任务的模型选择最全总结

    在第一部分,将了解多种时间序列的模型,如 经典的时间序列模型 监督学习模型 基于深度学习的模型 在第二部分,将建立几个时间序列模型来预测股市的应用案例,并了解一些时间序列建模技术.这些模型将相互比较, ...

  3. arima 公式_时间序列预测之--ARIMA模型

    什么是 ARIMA模型 ARIMA模型的全称叫做自回归移动平均模型,全称是(ARIMA, Autoregressive Integrated Moving Average Model).也记作ARIM ...

  4. 时间序列预测之--ARIMA模型

    什么是 ARIMA模型 ARIMA模型的全称叫做自回归移动平均模型,全称是(ARIMA, Autoregressive Integrated Moving Average Model).也记作ARIM ...

  5. 时间序列预测-传统统计学模型ARIMA

    ARIMA单变量预测股价DEMO 时间序列介绍: 统计学模型-ARIMA介绍 ARIMA 参数选择说明 源代码解析 参考资料 时间序列介绍: 时间序列(TIME-SERISE)充斥着我们生活的空间,在 ...

  6. 时间序列预测(四)—— LSTM模型

    时间序列预测(四)-- LSTM模型 欢迎大家来我的个人博客网站观看原文:https://xkw168.github.io/2019/05/20/时间序列预测-四-LSTM模型.html 文章链接 ( ...

  7. flag兑现:这次聊一聊Deep AR 模型用于PHM2012工况1轴承数据集的RUL预测

    基于Deep AR模型的轴承RUL预测 Deep AR模型 1.直接将特征输入到Deep AR模型进行RUL预测 2.将Deep AR应用于HI的后处理 总结 Deep AR模型 最早接触DeepAR ...

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

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

  9. 如何用XGBoost做时间序列预测?

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 来源:Jason Brownlee,整理:数据派THU 本文约3300字 ...

最新文章

  1. (灌水)如何限制一个WinForm应用程序只能在一个进程运行
  2. 多重继承和虚继承的内存布局
  3. Python的三种格式化输出
  4. 将Fiddler的服务器证书导入到Java的cacerts证书库里
  5. html5控制单片机,10.2 单片机中 PWM 的原理与控制程序
  6. 深度学习(十六)基于2-channel network的图片相似度判别
  7. android 组件化_你曾遇到的某大厂奇葩问题:Android组件化开发,组件间的Activity页面跳转...
  8. java中正则表达式截取字符串
  9. ps aux 输出格式
  10. Silverlight WCF RIA服务(二十九)Silverlight 客户端 10
  11. Spring Cloud(8):Sleuth和Zipkin的使用
  12. List、Set、Map比较
  13. flame linux mac,Autodesk版蓝宝石插件 GenArts Sapphire V10.0 (Mac/Linux)
  14. Linux中tar的参数zxf,tar命令
  15. 贝叶斯网络之父Judea Pearl力荐、LeCun点赞,这篇长论文全面解读机器学习中的因果关系
  16. Linux 2.6 劫持系统调用 隐藏进程
  17. 查找算法——二分查找(原理+源码)
  18. java并发编程实战wwj----------第二阶段-------------classloader----------------42-55
  19. 和谐敏感词(百度2017秋招真题)
  20. inputStream转File

热门文章

  1. Python自学笔记4:关于print的简单实操项目(打印一句话、天气预报、机票购买、北京地铁一号线运行图)
  2. 国内的聚宽量化平台好不好用?
  3. php yii composer,使用Composer安装Yii框架的方法
  4. linux中uniq c命令详解,linux uniq 命令整理
  5. limit分页查询的学习
  6. php 序列化 反序列化 __sleep __wakeup
  7. PS色彩平衡工具修复偏蓝风景照片色彩
  8. layui element tab 无法切换(tab偶尔能切换,偶尔不行,踩的一个坑)
  9. [34期] 在兄弟连的感受
  10. 算法工程师:在算法“黑箱”中保障用户知情权