转载于:https://blog.csdn.net/kylin_learn/article/details/85225400
https://machinelearningmastery.com/time-series-trends-in-python/
趋势是时间序列水平的长期增加或减少
有趋势的时间序列是非平稳的。
可以模拟确定的趋势。建模之后,它可以从时间系列数据集中去除。这就是时间序列去趋势。
该数据集有明显的上升趋势
差分法去趋势
时间序列去趋势最简单的方法就是差分。
具体而言,在等时间步长的基础上,计算前一观察点和观察点之差构造出新的序列。
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()
去趋势之后变成这样
拟合模型去趋势
趋势通常可视化为一条直线穿过。
线性趋势可以用线性模型总结,非线性趋势可以用多项式或其它曲线拟合方法概括
例如,一个线性模型适用于时间指标预测。数据集如下所示︰
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,当然也可以换成其他
在原始数据集(蓝色)上绘制趋势线 (绿色)
下一步,原始数据集减去这一趋势,然后绘制结果,结果为去趋势数据集。