时间序列--去趋势

https://machinelearningmastery.com/time-series-trends-in-python/

趋势是时间序列水平的长期增加或减少

有趋势的时间序列是非平稳的。

可以模拟确定的趋势。建模之后,它可以从时间系列数据集中去除。这就是时间序列去趋势。

Shampoo Sales Dataset Plot

该数据集有明显的上升趋势

差分法去趋势

时间序列去趋势最简单的方法就是差分。

具体而言,在等时间步长的基础上,计算前一观察点和观察点之差构造出新的序列。

value(t) = observation(t) - observation(t-1)

from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot

def parser(x):
	return datetime.strptime('190'+x, '%Y-%m')

series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
X = series.values
diff = list()
for i in range(1, len(X)):
	value = X[i] - X[i - 1]
	diff.append(value)
pyplot.plot(diff)
pyplot.show()

去趋势之后变成这样

Shampoo Sales Dataset Difference Detrended

拟合模型去趋势

趋势通常可视化为一条直线穿过。

线性趋势可以用线性模型总结,非线性趋势可以用多项式或其它曲线拟合方法概括

例如,一个线性模型适用于时间指标预测。数据集如下所示︰

X,y

1,obs1

2,obs2

3,obs3

4,obs4

5,obs5

这个模型的预测将形成一条直线,可以作为该数据集的趋势线。这些预测也可以从原始时间序列中减去,以提供数据集的去趋势版本。

value(t) = observation(t) - prediction(t)

from pandas import read_csv
from pandas import datetime
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot
import numpy

def parser(x):
	return datetime.strptime('190'+x, '%Y-%m')

series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
# fit linear model
X = [i for i in range(0, len(series))]
X = numpy.reshape(X, (len(X), 1))
y = series.values
model = LinearRegression()
model.fit(X, y)
# calculate trend
trend = model.predict(X)
# plot trend
pyplot.plot(y)
pyplot.plot(trend)
pyplot.show()
# detrend
detrended = [y[i]-trend[i] for i in range(0, len(series))]
# plot detrended
pyplot.plot(detrended)
pyplot.show()

这里用了线性回归的model,当然也可以换成其他

在原始数据集(蓝色)上绘制趋势线 (绿色)

Shampoo Sales Dataset Plot With Trend 

下一步,原始数据集减去这一趋势,然后绘制结果,结果为去趋势数据集。

Shampoo Sales Dataset Model Detrended

进一步深入:http://www.ltrr.arizona.edu/webhome/dmeko/notes_7.pdf

 

  • 15
    点赞
  • 112
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值