【问题标题】:weighted regression sklearn加权回归sklearn
【发布时间】:2020-04-11 02:37:51
【问题描述】:

我想根据训练数据的新近度为其添加权重。

如果我们看一个简单的例子:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures, normalize
from sklearn.linear_model import LinearRegression

X = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)
Y = np.array([0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 10]).reshape(-1,1)

poly_reg = PolynomialFeatures(degree=2)
X_poly = poly_reg.fit_transform(X)
pol_reg = LinearRegression()
pol_reg.fit(X_poly, Y)

plt.scatter(X, Y, color='red')
plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue')

现在假设 X 值是基于时间的,而 Y 值是传感器的快照。所以我们随着时间的推移对一些行为进行建模。我相信最新的数据点是最重要的,因为它们是最新的,最能代表未来的行为。我想调整我的模型,使最新数据点的权重最高。

在 R 中有一个关于这样做的问题: https://stats.stackexchange.com/questions/196653/assigning-more-weight-to-more-recent-observations-in-regression

我想知道 sklearn 包(或任何其他 python 包)是否有这个功能?

此加权模型将具有相似的曲线,但更适合较新的点。如果我想用这个模型来预测未来,那么非加权模型的预测总是过于保守,因为它们对最新数据不会那么敏感。

除了使用这种方法之外,我还使用 curve_fit 来使用幂函数或指数函数:

from scipy.optimize import curve_fit

def func(x, a, b):
    return a*(x**b)

X = [1,2,3,4,5,6,7,8,9,10]
Y = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 10]

popt, pcov = curve_fit(func, X, Y, bounds=([-np.inf,1], [np.inf, np.inf]))
plt.plot(X, func(X, *popt), color = 'green')

如果使用funccurve_fit 的解决方案是可能的,我也愿意接受,或任何其他方法。唯一需要注意的是,我的真实数据并不总是暗示解决方案是单调递增的函数,但我的理想解决方案将是。

【问题讨论】:

    标签: python scikit-learn regression weighted


    【解决方案1】:

    我查看了 sklearn 的 LinearRegression API here,发现该类有一个 fit() 方法,该方法具有以下签名:fit(self, X, y[, sample_weight]) 所以,据我所知,你实际上可以为你的样本赋予一个权重向量。

    【讨论】:

      【解决方案2】:

      从头开始实现:

      import matplotlib.pyplot as plt
      import numpy as np
      from sklearn.preprocessing import PolynomialFeatures, normalize
      from sklearn.linear_model import LinearRegression
      
      #%matplotlib inline
      
      X = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)
      #Weights.sum() = 1 
      w = np.exp(X)/sum(np.exp(X))
      
      Y = np.array([0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 10]).reshape(-1,1)
      
      poly_reg = PolynomialFeatures(degree=2)
      #Vandermonde Matrix
      X_poly = poly_reg.fit_transform(X)
      
      #Solve Weighted Normal Equation
      A = np.linalg.inv(X_poly.T @ (w*X_poly))
      beta = (A @ X_poly.T) @ (w*Y)
      
      #Define Ploynomial - Use Numpy for optimzation
      def polynomial(x, coeff):
          y = 0
          for p, c in enumerate(coeff):
              y += c * x**p
          return y
      
      plt.scatter(X, Y, color='red')
      plt.plot(X, polynomial(X, beta), color='blue')
      
      #Source https://en.wikipedia.org/wiki/Weighted_least_squares#Introduction
      

      请注意,这与 Teo 的答案相同,而且他的答案更短。

      【讨论】:

        猜你喜欢
        • 2020-07-07
        • 2018-03-14
        • 2014-01-20
        • 2018-05-16
        • 2018-11-17
        • 2017-02-25
        • 2015-06-15
        • 1970-01-01
        • 2018-02-22
        相关资源
        最近更新 更多