第一种方法:利用统计量
You can split your time series into two (or more) partitions and compare the mean and variance of each group. If they differ and the difference is statistically significant, the time series is likely non-stationary.
注意:如果我们利用均值和方差,必须假设时间序列服从正态分布才可以,其他分布的话比较均值和方差意义不太大
如果一个时间序列值的分布长这样就不能直接比较均值方差,一个比较好的办法是log转化
from pandas import Series
from matplotlib import pyplot
from numpy import log
series = Series.from_csv('international-airline-passengers.csv', header=0)
X = series.values
X = log(X)
pyplot.hist(X)
pyplot.show()
pyplot.plot(X)
pyplot.show()
下面分别是转换之后的分布,和时间序列趋势图
可以看到更像正态分布了
这个也是log转换过后的
from pandas import Series
from matplotlib import pyplot
from numpy import log
series = Series.from_csv('international-airline-passengers.csv', header=0)
X = series.values
X = log(X)
split = len(X) / 2
X1, X2 = X[0:split], X[split:]
mean1, mean2 = X1.mean(), X2.mean()
var1, var2 = X1.var(), X2.var()
print('mean1=%f, mean2=%f' % (mean1, mean2))
print('variance1=%f, variance2=%f' % (var1, var2))
现在比较了均值和方差
mean1=5.175146, mean2=5.909206
variance1=0.068375, variance2=0.049264
Perhaps, from these numbers alone, we would say the time series is stationary, but we strongly believe this to not be the case from reviewing the line plot.
所以 方法虽然简单,但不一定有效。
第二个方法:单位根检验的一种最常用的检验Augmented Dickey-Fuller test
The Augmented Dickey-Fuller test is a type of statistical test called a unit root test.
原假设:it suggests the time series has a unit root, meaning it is non-stationary. It has some time dependent structure.
备择假设:it suggests the time series does not have a unit root, meaning it is stationary. It does not have time-dependent structure.
The statsmodels library provides the adfuller() function that implements the test.
from pandas import Series
from statsmodels.tsa.stattools import adfuller
series = Series.from_csv('international-airline-passengers.csv', header=0)
X = series.values
result = adfuller(X)
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
print('Critical Values:')
for key, value in result[4].items():
print('\t%s: %.3f' % (key, value))
最后结果如下
ADF Statistic: 0.815369
p-value: 0.991880
Critical Values:
5%: -2.884
1%: -3.482
10%: -2.579
所以我们可以无法拒绝原假设,因此认为这个序列是不平稳的
那我们log之后呢
from pandas import Series
from statsmodels.tsa.stattools import adfuller
from numpy import log
series = Series.from_csv('international-airline-passengers.csv', header=0)
X = series.values
X = log(X)
result = adfuller(X)
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
for key, value in result[4].items():
print('\t%s: %.3f' % (key, value))
ADF Statistic: -1.717017
p-value: 0.422367
5%: -2.884
1%: -3.482
10%: -2.579
嘿!我们还是不能拒绝H0,所以还是不平稳的
https://machinelearningmastery.com/time-series-data-stationary-python/