liz*_*man 5 python scikit-learn logistic-regression
我对sklearn如何应用我们提供的班级重量感兴趣。该文档没有明确说明在何处以及如何应用类权重。读取源代码也无济于事(似乎使用sklearn.svm.liblinear这样的优化,由于它是.pyd文件,所以我无法读取源代码...)
但是我猜想它可以对cost函数起作用:指定了类权重后,相应类的成本将乘以类权重。例如,如果我分别有2个观察值分别来自类0(权重= 0.5)和类1(权重= 1),则成本函数为:
费用= 0.5 * log(... X_0,y_0 ...)+ 1 * log(... X_1,y_1 ...)+罚款
有人知道这是否正确吗?
检查源代码中的以下几行:
le = LabelEncoder()
if isinstance(class_weight, dict) or multi_class == 'multinomial':
class_weight_ = compute_class_weight(class_weight, classes, y)
sample_weight *= class_weight_[le.fit_transform(y)]
Run Code Online (Sandbox Code Playgroud)
compute_class_weight()这是该函数的源代码:
...
else:
# user-defined dictionary
weight = np.ones(classes.shape[0], dtype=np.float64, order='C')
if not isinstance(class_weight, dict):
raise ValueError("class_weight must be dict, 'balanced', or None,"
" got: %r" % class_weight)
for c in class_weight:
i = np.searchsorted(classes, c)
if i >= len(classes) or classes[i] != c:
raise ValueError("Class label {} not present.".format(c))
else:
weight[i] = class_weight[c]
...
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中,class_weight应用于sample_weight,它在一些内部函数中使用,如_logistic_loss_and_grad、_logistic_loss等:
# Logistic loss is the negative of the log of the logistic function.
out = -np.sum(sample_weight * log_logistic(yz)) + .5 * alpha * np.dot(w, w)
# NOTE: ---> ^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |