使用局部加权回归(LOESS / LOWESS)预测新数据

时间:2016-03-27 20:42:39

标签: python python-3.x pandas statsmodels

如何在python中拟合局部加权回归,以便可以用它来预测新数据?

private static ArrayList<String[][]> boardsAll = new ArrayList<String[][]>(); public static void setBoardsAll(String[][] input) { boardsAll.add(input); } public static String[][] getBoardsAll(int location) { return Player.boardsAll.get(location); } public static ArrayList<String[][]> getBoardsAll() { return boardsAll; } ,但它只返回原始数据集的估算值;所以它似乎只是statsmodels.nonparametric.smoothers_lowess.lowessfit一起,而不是像我预期的那样单独进行。

predict始终有一个scikit-learn方法,允许稍后在fit的新数据上使用该对象;但它没有实现predict

4 个答案:

答案 0 :(得分:9)

Lowess非常适合预测(与插值结合使用时)!我认为代码非常简单 - 如果您有任何问题,请告诉我! Matplolib Figure

import matplotlib.pyplot as plt
%matplotlib inline
from scipy.interpolate import interp1d
import statsmodels.api as sm

# introduce some floats in our x-values
x = list(range(3, 33)) + [3.2, 6.2]
y = [1,2,1,2,1,1,3,4,5,4,5,6,5,6,7,8,9,10,11,11,12,11,11,10,12,11,11,10,9,8,2,13]

# lowess will return our "smoothed" data with a y value for at every x-value
lowess = sm.nonparametric.lowess(y, x, frac=.3)

# unpack the lowess smoothed points to their values
lowess_x = list(zip(*lowess))[0]
lowess_y = list(zip(*lowess))[1]

# run scipy's interpolation. There is also extrapolation I believe
f = interp1d(lowess_x, lowess_y, bounds_error=False)

xnew = [i/10. for i in range(400)]

# this this generate y values for our xvalues by our interpolator
# it will MISS values outsite of the x window (less than 3, greater than 33)
# There might be a better approach, but you can run a for loop
#and if the value is out of the range, use f(min(lowess_x)) or f(max(lowess_x))
ynew = f(xnew)


plt.plot(x, y, 'o')
plt.plot(lowess_x, lowess_y, '*')
plt.plot(xnew, ynew, '-')
plt.show()

答案 1 :(得分:3)

请考虑使用内核回归。

statmodels有implementation

如果你有太多的数据点,为什么不使用sk.learn&#39; radiusNeighborRegression并指定一个三重权重函数?

答案 2 :(得分:2)

我创建了一个名为 moepy 的模块,它为 LOWESS 模型(包括拟合/预测)提供了一个类似于 sklearn 的 API。这使得可以使用基础局部回归模型而不是其他答案中描述的插值方法进行预测。下面显示了一个极简示例。

# Imports
import numpy as np
import matplotlib.pyplot as plt
from moepy import lowess

# Data generation
x = np.linspace(0, 5, num=150)
y = np.sin(x) + (np.random.normal(size=len(x)))/10

# Model fitting
lowess_model = lowess.Lowess()
lowess_model.fit(x, y)

# Model prediction
x_pred = np.linspace(0, 5, 26)
y_pred = lowess_model.predict(x_pred)

# Plotting
plt.plot(x_pred, y_pred, '--', label='LOWESS', color='k', zorder=3)
plt.scatter(x, y, label='Noisy Sin Wave', color='C1', s=5, zorder=1)
plt.legend(frameon=False)

enter image description here

有关如何使用模型(及其置信区间和预测区间变体)的更详细指南,请参见 here

答案 3 :(得分:0)

我将使用SAS PROC LOESS,然后使用PROC SCORE进行预测。 否则我会使用R。Python对于很多其他东西来说很棒而且很棒。但是,如果可以使用经过良好测试的解决方案,那么为什么要重新发明统计分析的方向呢?

相关问题