【问题标题】:How to detrend time series in python (to remove outliers)如何在 python 中去除时间序列的趋势(去除异常值)
【发布时间】:2019-12-06 03:27:36
【问题描述】:

我有一个朝某个方向发展的时间序列。正因为如此,它使得标准偏差不是分析数据的一个很好的工具。有没有办法可以“去趋势”或扁平化数据,以便我可以更轻松地进行异常值分析?

【问题讨论】:

标签: python time-series outliers


【解决方案1】:

所以对于其他想要做同样事情的人来说,我发现对我想做的事情有用...

import numpy as np
from sklearn.linear_model import LinearRegression

def flatten_data(x, y):
    lr = LinearRegression().fit(x, y)
    slope = lr.coef_[0][0]
    y_int = lr.intercept_[0]
    flattened = []
    for i in range(len(x)):
        expected_val = slope * x[i] + y_int
        flattened.append(y[i] - expected_val)
    return flattened

这将对您的数据进行线性回归。然后只需遍历您的数据点并计算每个点与最佳拟合线的距离。这应该会为您提供数据的扁平化版本。

【讨论】:

    【解决方案2】:

    如果您想为此使用 R,有很多软件包支持去趋势时间序列(取决于您拥有的趋势,加法/乘法)。您可以使用时间序列分解技术,例如 stl [1]、decompose [2] 和 stR [3]。一次,您将时间序列分解为季节性、趋势和余数,出于去趋势的目的,您可以排除趋势分量(使用季节性 + 余数)

    另外,如果你想坚持使用Python,请按照[4]分解时间序列,并如上所述从时间序列中排除趋势分量。

    另外,如果你有兴趣稳定数据的方差,我建议你对你的时间序列应用对数转换(只取时间序列的对数)

    希望这会有所帮助。

    [1]https://www.rdocumentation.org/packages/stats/versions/3.6.1/topics/stl

    [2]https://stat.ethz.ch/R-manual/R-devel/library/stats/html/decompose.html

    [3]https://cran.r-project.org/web/packages/stR/vignettes/stRvignette.html

    [4]https://machinelearningmastery.com/decompose-time-series-data-trend-seasonality/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 2019-08-07
      相关资源
      最近更新 更多