理解Sklearn的线性回归权重

2024-09-30 06:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难在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


Tags: importmodelnppredictfit权重linearyr
1条回答
网友
1楼 · 发布于 2024-09-30 06:24:37

这是由于代码中的错误造成的。加权模型的拟合应为:

yw_pred = wregr.predict(xr)

而不是

yw_pred = regr.predict(xr)

通过这一点,您可以:

enter image description here

相关问题 更多 >

    热门问题