python - 使用 Scikit-learn 进行加权线性回归

标签 python python-2.7 machine-learning scikit-learn regression

我的数据:

State           N           Var1            Var2
Alabama         23          54              42
Alaska          4           53              53
Arizona         53          75              65
Var1Var2是州级的汇总百分比值。 N是每个状态的参与者数量。我想在 Var1 之间运行线性回归和 Var2考虑到 N作为 Python 2.7 中 sklearn 的权重。

一般线路是:
fit(X, y[, sample_weight])

假设数据加载到 df使用 Pandas 和 N变成 df["N"] ,我是简单地将数据放入下一行,还是需要在将 N 用作 sample_weight 之前以某种方式处理它?在命令中?
fit(df["Var1"], df["Var2"], sample_weight=df["N"])

最佳答案

权重使训练模型对于输入的某些值更准确(例如,错误成本更高的地方)。在内部,权重 w 乘以损失函数中的残差 [1 ]:

enter image description here

因此,重要的是权重的相对比例。 N如果它已经反射(reflect)了优先级,则可以按原样通过。统一缩放不会改变结果。

这是一个例子。在加权版本中,我们强调最后两个样本周围的区域,模型在那里变得更加准确。而且,正如预期的那样,缩放不会影响结果。

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LinearRegression

# Load the diabetes dataset
X, y = datasets.load_diabetes(return_X_y=True)
n_samples = 20

# Use only one feature and sort
X = X[:, np.newaxis, 2][:n_samples]
y = y[:n_samples]
p = X.argsort(axis=0)
X = X[p].reshape((n_samples, 1))
y = y[p]

# Create equal weights and then augment the last 2 ones
sample_weight = np.ones(n_samples) * 20
sample_weight[-2:] *= 30

plt.scatter(X, y, s=sample_weight, c='grey', edgecolor='black')

# The unweighted model
regr = LinearRegression()
regr.fit(X, y)
plt.plot(X, regr.predict(X), color='blue', linewidth=3, label='Unweighted model')

# The weighted model
regr = LinearRegression()
regr.fit(X, y, sample_weight)
plt.plot(X, regr.predict(X), color='red', linewidth=3, label='Weighted model')

# The weighted model - scaled weights
regr = LinearRegression()
sample_weight = sample_weight / sample_weight.max()
regr.fit(X, y, sample_weight)
plt.plot(X, regr.predict(X), color='yellow', linewidth=2, label='Weighted model - scaled', linestyle='dashed')
plt.xticks(());plt.yticks(());plt.legend();

enter image description here

( this transformation 似乎也需要将 Var1Var2 传递给 fit )

关于python - 使用 Scikit-learn 进行加权线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35236836/

相关文章:

python - 迁移学习时 TensorFlow 中的验证和评估指标问题

Python3 写入 gzip 文件 - 内存 View : a bytes-like object is required, 不是 'str'

python - 如何更改opencv检测到的刻度的形状

python - 蛇与梯子,检查是否会降落在最后一个方 block 上

python - 在移动窗口 numpy 数组上有效地应用函数

python - 如何修改 tf.nn.embedding_lookup() 的返回张量?

python - 如何在 python 中四舍五入到更高的 10 位

python - 为什么 os.mkdir() 在显式调用时变慢?

python - 从 unittest 测试调用时 argparse 失败

Python Scikit 学习 : Multilabel Classification ValueError: could not convert string to float: