【问题标题】:Understanding Sklearn's Linear Regression Weighting了解 Sklearn 的线性回归加权
【发布时间】:2020-07-07 06:03:15
【问题描述】:

我很难让sklearn 的线性回归中的加权数组影响输出。

这是一个没有加权的例子。

import numpy as np
import seaborn as sns
from sklearn import linear_model

x = np.arange(0,100.)
y = (x**2.0)

xr = np.array(x).reshape(-1, 1)
yr = np.array(y).reshape(-1, 1)

regr = linear_model.LinearRegression()
regr.fit(xr, yr)
y_pred = regr.predict(xr)

sns.scatterplot(x=x, y = y)
sns.lineplot(x=x, y = y_pred.T[0].tolist())

现在,当添加权重时,我得到了相同的最佳拟合线。我希望看到回归有利于曲线的较陡部分。我做错了什么?

w = [p**2 for p in x.reshape(-1)]
wregr = linear_model.LinearRegression()
wregr.fit(xr,yr, sample_weight=w)
yw_pred = regr.predict(xr)

wregr = linear_model.LinearRegression(fit_intercept=True)
wregr.fit(xr,yr, sample_weight=w)
yw_pred = regr.predict(xr)

sns.scatterplot(x=x, y = y)                      #plot curve
sns.lineplot(x=x, y = y_pred.T[0].tolist())      #plot non-weighted best fit line
sns.lineplot(x=x, y = yw_pred.T[0].tolist())     #plot weighted best fit line

【问题讨论】:

    标签: python scikit-learn linear-regression


    【解决方案1】:

    这是由于您的代码中的错误。您的加权模型的拟合应该是:

    yw_pred = wregr.predict(xr)
    

    而不是

    yw_pred = regr.predict(xr)
    

    这样你得到:

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2015-01-29
      • 2019-07-04
      • 2014-05-05
      • 2020-12-24
      相关资源
      最近更新 更多