簡體   English   中英

Python 中 LOWESS 的置信區間

[英]Confidence interval for LOWESS in Python

我將如何計算 Python 中 LOWESS 回歸的置信區間? 我想將這些作為陰影區域添加到使用以下代碼創建的 LOESS 圖(除 statsmodels 之外的其他包也很好)。

import numpy as np
import pylab as plt
import statsmodels.api as sm

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
lowess = sm.nonparametric.lowess(y, x, frac=0.1)

plt.plot(x, y, '+')
plt.plot(lowess[:, 0], lowess[:, 1])
plt.show()

我已經從 webblog Serious Stats (它是使用 R 中的 ggplot 創建)添加了一個帶有置信區間的示例圖。

在此處輸入圖片說明

LOESS 沒有明確的標准錯誤概念。 在這種情況下,它沒有任何意義。 既然已經結束,你就堅持使用蠻力方法。

引導您的數據。 您將根據自舉數據擬合 LOESS 曲線。 查看此頁面的中間以找到您正在做的事情的漂亮圖片。 http://statweb.stanford.edu/~susan/courses/s208/node20.html

在此處輸入圖片說明

一旦您擁有大量不同的 LOESS 曲線,您就可以找到頂部和底部的第 X 個百分位數。

在此處輸入圖片說明

這是一個非常古老的問題,但它是第一個在谷歌搜索中彈出的問題。 您可以使用 scikit-misc 中的 loess() 函數執行此操作。 這是一個例子(我試圖保留你原來的變量名,但我稍微增加了噪音以使其更明顯)

import numpy as np
import pylab as plt
from skmisc.loess import loess

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.4

l = loess(x,y)
l.fit()
pred = l.predict(x, stderror=True)
conf = pred.confidence()

lowess = pred.values
ll = conf.lower
ul = conf.upper

plt.plot(x, y, '+')
plt.plot(x, lowess)
plt.fill_between(x,ll,ul,alpha=.33)
plt.show()

結果:

黃土光滑帶CI

對於我的一個項目,我需要為時間序列建模創建間隔,並且為了使程序更高效,我創建了tsmoothie :一個用於以矢量化方式進行時間序列平滑和異常值檢測的 Python 庫。

它提供了不同的平滑算法以及計算間隔的可能性。

LowessSmoother的情況下:

import numpy as np
import matplotlib.pyplot as plt
from tsmoothie.smoother import *
from tsmoothie.utils_func import sim_randomwalk

# generate 10 randomwalks of length 200
np.random.seed(33)
data = sim_randomwalk(n_series=10, timesteps=200, 
                      process_noise=10, measure_noise=30)

# operate smoothing
smoother = LowessSmoother(smooth_fraction=0.1, iterations=1)
smoother.smooth(data)

# generate intervals
low, up = smoother.get_intervals('prediction_interval', confidence=0.05)

# plot the first smoothed timeseries with intervals
plt.figure(figsize=(11,6))
plt.plot(smoother.smooth_data[0], linewidth=3, color='blue')
plt.plot(smoother.data[0], '.k')
plt.fill_between(range(len(smoother.data[0])), low[0], up[0], alpha=0.3)

在此處輸入圖片說明

我還指出,tsmoothie 可以以矢量化的方式對多個時間序列進行平滑處理。 希望這可以幫助某人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM