了解Sklearn的线性回归加权

问题描述 投票:0回答:1

我很难获得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())

enter image description here

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

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

enter image description here

python scikit-learn linear-regression
1个回答
1
投票

这是由于您的代码错误。您的加权模块的拟合度应为:

yw_pred = wregr.predict(xr)

有了这个你得到:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.