ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 如何在sklearn逻辑回归中应用class_weights?

2019-07-05 15:57:16  阅读:1044  来源: 互联网

标签:python scikit-learn logistic-regression


我对sklearn如何应用我们提供的课程重量感兴趣. documentation没有明确说明应用类权重的位置和方式.阅读源代码也没有帮助(似乎sklearn.svm.liblinear用于优化,我无法读取源代码,因为它是.pyd文件……)

但我想它适用于成本函数:当指定类权重时,相应类的成本将乘以类权重.例如,如果我分别从0级(权重= 0.5)和1级(权重= 1)得到2个观察值,那么成本函数将是:

Cost = 0.5*log(…X_0,y_0…) + 1*log(…X_1,y_1…) + penalization

有谁知道这是否正确?

解决方法:

检查the following lines in the source code

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)]

Here is the source code for the compute_class_weight() function

...
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]
...

在上面的代码片段中,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: --->  ^^^^^^^^^^^^^^^

标签:python,scikit-learn,logistic-regression
来源: https://codeday.me/bug/20190705/1388571.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有