如何在趋势和季节性存在的时间序列数据中检测异常?

2024-04-28 17:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检测包含趋势和季节性成分的“时间序列数据”中的异常值。我想省略那些季节性的峰值,只考虑其他峰值,并将它们标记为异常值。由于我是时间序列分析的新手,请帮助我解决这个时间序列问题。在

使用的编码平台是Python。在

尝试一:使用ARIMA模型

我训练了我的模型并预测了测试数据。然后能够计算预测结果与我的测试数据的实际值之间的差异,然后能够根据观察到的方差找出异常值。在

自动Arima

的实现
!pip install pyramid-arima
from pyramid.arima import auto_arima
stepwise_model = auto_arima(train_log, start_p=1, start_q=1,max_p=3, max_q=3,m=7,start_P=0, seasonal=True,d=1, D=1, trace=True,error_action='ignore', suppress_warnings=True,stepwise=True)

^{pr2}$

将数据拆分为列车和测试集

train, test = actual_vals[0:-70], actual_vals[-70:]

对数变换

train_log, test_log = np.log10(train), np.log10(test)

转换为列表

history = [x for x in train_log]
predictions = list()
predict_log=list()

逐步拟合ARIMA模型

for t in range(len(test_log)):
stepwise_model.fit(history)
    output = stepwise_model.predict(n_periods=1)
    predict_log.append(output[0])
    yhat = 10**output[0]
    predictions.append(yhat)
    obs = test_log[t]
    history.append(obs)

绘制

figsize=(12, 7)
plt.figure(figsize=figsize)
pyplot.plot(test,label='Actuals')
pyplot.plot(predictions, color='red',label='Predicted')
pyplot.legend(loc='upper right')
pyplot.show()

但我只能在测试数据中检测到异常值。实际上,我必须检测整个时间序列数据的异常值,包括我所拥有的列车数据。在

尝试2:使用季节分解

我使用下面的代码将原始数据分成季节性、趋势性、残差,可以在下图中看到。在

from statsmodels.tsa.seasonal import seasonal_decompose

decomposed = seasonal_decompose()

enter image description here

然后利用残差数据,利用箱线图找出剔除季节和趋势分量后的异常值。这有道理吗?在

或者有没有其他简单或更好的方法?在


Tags: 数据模型testlogtruemodel时间train
1条回答
网友
1楼 · 发布于 2024-04-28 17:26:33

您可以:

  • 在第四张图(残差图)的"Attempt 2 : Using Seasonal Decomposition"尝试检查极值点,这可能会导致季节序列中的一些异常。在
  • 监督(如果你有一些标记的数据):做一些分类。在
  • 无监督:尝试预测下一个值,并创建一个置信区间,以检查预测是否位于其中。在
  • 你可以试着计算数据的相对极值。使用如下所示的argrelextrema例如:
from scipy.signal import argrelextrema
x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) 
argrelextrema(x, np.greater)

输出:

(array([3, 6]),)

一些随机数据(我对上述argrelextrema的实现): enter image description here

相关问题 更多 >