Kub*_*888 7 python regression machine-learning python-2.7 scikit-learn
我的数据:
State N Var1 Var2
Alabama 23 54 42
Alaska 4 53 53
Arizona 53 75 65
Run Code Online (Sandbox Code Playgroud)
Var1并且Var2是州级的汇总百分比值。N是每个状态的参与者数量。我想之间运行的线性回归Var1和Var2与所述考虑的N作为重量与在Python 2.7 sklearn。
一般线路是:
fit(X, y[, sample_weight])
Run Code Online (Sandbox Code Playgroud)
假设数据被加载到df使用 Pandas 并且N变成了df["N"],我是简单地将数据放入下一行还是我需要在使用它之前以某种方式处理 N 就像sample_weight在命令中一样?
fit(df["Var1"], df["Var2"], sample_weight=df["N"])
Run Code Online (Sandbox Code Playgroud)
权重能够训练对输入的某些值更准确的模型(例如,在错误成本较高的情况下)。在内部,权重w乘以损失函数 [ 1 ] 中的残差:
因此,重要的是权重的相对比例。N如果它已经反映了优先级,则可以按原样通过。统一缩放不会改变结果。
这是一个例子。在加权版本中,我们强调最后两个样本周围的区域,模型在那里变得更加准确。而且,正如预期的那样,缩放不会影响结果。
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();
Run Code Online (Sandbox Code Playgroud)
(这种转变似乎也是必要的传递Var1,并Var2于fit)
| 归档时间: |
|
| 查看次数: |
15658 次 |
| 最近记录: |