几个重要的lightgbm自定义损失函数和评测函数(包括F1 score等)

f1_score自定义损失函数及评测函数

def custom_f1_eval(y_true, y_pred):
    num_TP = 0
    num_pred = 0
    threshold = 0.5
    for i in range(len(y_true)):
        if y_pred >= threshold:
            num_pred += 1
            if y_true == 1:
                num_TP += 1
    precision = num_TP / num_pred
    recall = num_TP / len(y_true[y_true == 1])
    f1 = 2 * precision * recall / (precision + recall)
    return "f1", f1_mean, True

def f1_loss(y, pred):
    beta = 2
    p = 1. / (1 + np.exp(-pred))
    grad = p * ((beta - 1) * y + 1) - beta * y
    hess = ((beta - 1) * y + 1) * p * (1.0 - p)

    return grad, hess

f1_lossfe

使用方法:

   clf = LGBMClassifier(
        learning_rate=0.001,
        n_estimators=n_estimators,
        num_leaves=127, # 20, max_depth:5
        subsample=0.8,
        colsample_bytree=0.8,
        random_state=2019,
        #scale_pos_weight=50,
        metric=None,
    )
    clf.set_params(**{"objective": f1_loss})
    clf.fit(X_train, y_train, eval_set=[(X_test, y_test)], 
            eval_metric=lambda y_true, y_pred: [custom_f1_eval(y_true, y_pred)], 
            early_stopping_rounds=early_stopping_rounds, verbose=10)

参考网址:

(1)https://jonuknownothingsnow.github.io/2019/01/09/%E8%B0%90%E9%97%A8%E6%AD%A6%E5%AD%A6%EF%BC%9A%E4%BD%9C%E4%B8%BAloss%E5%87%BD%E6%95%B0%E7%9A%84F1-score/

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值