时间序列--自回归模型

就是利用序列上一步或者更上一步的值取预测下一步的值

比如:X(t) = b0 + b1*X(t-1) + b2*X(t-2)

我们可以用统计量来计算输出变量与不同时滞下的前一时刻的值之间的相关性。输出变量与特定滞后变量的相关性越强,自回归模型在建模时对该变量的权重越大。

有趣的是,如果所有的滞后变量与输出变量的相关性都很低或没有相关性,那么这就表明时间序列问题可能是不可预测的

Minimum Daily Temperature Dataset Plot

我们的数据长成上面那个样子

第一:迅速检查自相关值散点图

我们可以做一个快速、直观的检查,看看时间序列数据集中是否存在自相关。我们可以将上一个时间步(t-1)的观测值绘制成散点图,下一个时间步(t+1)的观测值绘制成散点图。这可以手动完成,首先创建时间序列数据集的滞后版本,并在panda库中使用内置的散点图函数。但是有一个更简单的方法。panda提供了一个内建的plot来实现这一点,called the lag_plot() function.。下面是一个创建最小日温度数据集滞后图的示例。

from pandas import Series
from matplotlib import pyplot
from pandas.tools.plotting import lag_plot
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
lag_plot(series)
pyplot.show()

Minimum Daily Temperature Dataset Lag Plot

沿着对角线的这种带规律的图说明很大可能存在自相关

第二:迅速检查自相关之皮尔森相关系数

We can use a statistical test like the Pearson correlation coefficient

这产生了一个数字来总结两个变量在-1(负相关)和+1(正相关)之间的相关性,小值接近零表示相关性低,高值在0.5以上或-0.5以下表示相关性高。利用滞后数据集的DataFrame上的corr()函数可以方便地计算相关性。

from pandas import Series
from pandas import DataFrame
from pandas import concat
from matplotlib import pyplot
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
values = DataFrame(series.values)
dataframe = concat([values.shift(1), values], axis=1)
dataframe.columns = ['t-1', 't+1']
result = dataframe.corr()
print(result)

         t-1      t+1
t-1  1.00000  0.77487
t+1  0.77487  1.00000

相关系数0.7可以看出还是有挺大相关的

第三:大规模数据集上检验自相关

我们可以画出每个滞后变量的相关系数。这可以很快地让我们了解哪些滞后变量可能是在预测模型中使用的最佳候选变量,以及观察值与历史值之间的关系如何随时间变化。我们可以手工计算每个滞后变量的相关值并绘制结果。值得庆幸的是,panda提供了一个名为autocorrelation_plot()函数的内置绘图。该图提供了x轴上的滞后数以及y轴上-1和1之间的相关系数值。图中还包括实线和虚线,它们表示相关值的95%和99%置信区间。这些线以上的相关值比线以下的更重要,为选择更多相关的滞后值提供了一个阈值或截止值。

from pandas import Series
from matplotlib import pyplot
from pandas.tools.plotting import autocorrelation_plot
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
autocorrelation_plot(series)
pyplot.show()

Pandas Autocorrelation Plot

The statsmodels library also provides a version of the plot in the plot_acf() function as a line plot.

from pandas import Series
from matplotlib import pyplot
from statsmodels.graphics.tsaplots import plot_acf
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
plot_acf(series, lags=31)
pyplot.show()

Statsmodels Autocorrelation Plot

其实我们可以利用这种相关性去选特征变量,我在bite公司一开始是用这种pearson去选变量的,根据p-value的大小选的,但是,嗯,我觉得他只能刻画线性相关性,最后在项目里面我就没有使用这个方法,用的是随机森林、RFE的方法,

当然这里我认为看自相关主要想看滞后项有没有用,大致上有用才能进行自回归。所以是看做自回归模型的一个初检验吧,还是不要用这个方法挑变量了最好。

ok,现在我们利用自回归模型去预测吧。

目标:利用之前的时间的气温预测今天的气温

baseline:就用上一天的值当做今天的气温值

from pandas import Series
from pandas import DataFrame
from pandas import concat
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
# create lagged dataset
values = DataFrame(series.values)
dataframe = concat([values.shift(1), values], axis=1)
dataframe.columns = ['t-1', 't+1']
# split into train and test sets
X = dataframe.values
train, test = X[1:len(X)-7], X[len(X)-7:]
train_X, train_y = train[:,0], train[:,1]
test_X, test_y = test[:,0], test[:,1]

# persistence model
def model_persistence(x):
	return x

# walk-forward validation
predictions = list()
for x in test_X:
	yhat = model_persistence(x)
	predictions.append(yhat)
test_score = mean_squared_error(test_y, predictions)
print('Test MSE: %.3f' % test_score)
# plot predictions vs expected
pyplot.plot(test_y)
pyplot.plot(predictions, color='red')
pyplot.show()

 Predictions From Persistence Model

预测集上表现如上

 

下面看自回归model:

自回归模型是使用滞后变量作为输入变量的线性回归模型。

我们可以使用scikit-learn中的LinearRegession类手工计算线性回归模型,手工指定要使用的滞后输入变量。

另外,statsmodels库提供了一个自动回归模型,该模型使用统计测试自动选择适当的滞后值,并训练线性回归模型。它是在AR类中提供的。我们可以使用这个模型,首先创建模型AR(),然后调用fit()在数据集上训练它。这将返回一个ARResult对象。

一旦合适,我们就可以通过调用predict()函数来对未来的一些观察结果进行预测。这将创建1个7天预测

划重点:也就是我们划分test集合没啥意义了,用train去训练,然后利用predict自动给出来以后n天的预测,test的t-1时刻的数据根本没有用到,只是用test的t时刻数据当做y看看我们自动预测的好不好而已

from pandas import Series
from matplotlib import pyplot
from statsmodels.tsa.ar_model import AR
from sklearn.metrics import mean_squared_error
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
# split dataset
X = series.values
train, test = X[1:len(X)-7], X[len(X)-7:]
#train和test都是一个列
# train autoregression
model = AR(train)
# AR(train)之后对这一个时间序列自动滞后很多项去做线性回归,并且选出来合适的滞后项
model_fit = model.fit()
print('Lag: %s' % model_fit.k_ar)
print('Coefficients: %s' % model_fit.params)
# make predictions
predictions = model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)
# 注意我这里predict只是指定我想预测的以后的多步的范围,我用的数据只是train的数据,test我并没有去构建多个滞后项去拟合,这从代码里面没有涉及到test也可以看出来
for i in range(len(predictions)):
	print('predicted=%f, expected=%f' % (predictions[i], test[i]))
# 看看我的预测和真是的值
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)
# plot results
pyplot.plot(test)
pyplot.plot(predictions, color='red')
pyplot.show()

结果如下:

Lag: 29
Coefficients: [  5.57543506e-01   5.88595221e-01  -9.08257090e-02   4.82615092e-02
   4.00650265e-02   3.93020055e-02   2.59463738e-02   4.46675960e-02
   1.27681498e-02   3.74362239e-02  -8.11700276e-04   4.79081949e-03
   1.84731397e-02   2.68908418e-02   5.75906178e-04   2.48096415e-02
   7.40316579e-03   9.91622149e-03   3.41599123e-02  -9.11961877e-03
   2.42127561e-02   1.87870751e-02   1.21841870e-02  -1.85534575e-02
  -1.77162867e-03   1.67319894e-02   1.97615668e-02   9.83245087e-03
   6.22710723e-03  -1.37732255e-03]
predicted=11.871275, expected=12.900000
predicted=13.053794, expected=14.600000
predicted=13.532591, expected=14.000000
predicted=13.243126, expected=13.600000
predicted=13.091438, expected=13.500000
predicted=13.146989, expected=15.700000
predicted=13.176153, expected=13.000000
Test MSE: 1.502

Predictions From Fixed AR Model

效果额没有很好,这其实就是预测多步!!!!

这很不符合我们机器学习的思想鸭!我们机器学习是想说,在test集合上利用train的系数和变量去拟合预测,然后再比较效果,下面给出了这个思路的代码

from pandas import Series
from matplotlib import pyplot
from statsmodels.tsa.ar_model import AR
from sklearn.metrics import mean_squared_error
series = Series.from_csv('daily-minimum-temperatures.csv', header=0)
# split dataset
X = series.values
train, test = X[1:len(X)-7], X[len(X)-7:]
# train autoregression
model = AR(train)
model_fit = model.fit()
window = model_fit.k_ar
coef = model_fit.params
# walk forward over time steps in test
history = train[len(train)-window:]
history = [history[i] for i in range(len(history))]
predictions = list()
for t in range(len(test)):
	length = len(history)
	lag = [history[i] for i in range(length-window,length)]
	yhat = coef[0]
	for d in range(window):
		yhat += coef[d+1] * lag[window-d-1]
	obs = test[t]
	predictions.append(yhat)
	history.append(obs)
	print('predicted=%f, expected=%f' % (yhat, obs))
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)
# plot
pyplot.plot(test)
pyplot.plot(predictions, color='red')
pyplot.show()

结果如下:

predicted=11.871275, expected=12.900000
predicted=13.659297, expected=14.600000
predicted=14.349246, expected=14.000000
predicted=13.427454, expected=13.600000
predicted=13.374877, expected=13.500000
predicted=13.479991, expected=15.700000
predicted=14.765146, expected=13.000000
Test MSE: 1.451

Predictions From Rolling AR Model

emmmm其实有点细节没搞明白,以后再翻过来看

https://machinelearningmastery.com/autoregression-models-time-series-forecasting-python/

  • 11
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值