zl程序教程

您现在的位置是:首页 >  其它

当前栏目

xgboost 自定义目标函数和评估函数

函数 自定义 目标 评估 xgboost
2023-09-14 08:58:38 时间

https://zhpmatrix.github.io/2017/06/29/custom-xgboost/

https://www.cnblogs.com/silence-gtx/p/5812012.html

https://blog.csdn.net/hfzd24/article/details/76903927

 

如下,自定义评估函数 maxrecall:

def maxRecall(preds,dtrain): #preds是结果(概率值),dtrain是个带label的DMatrix
    labels=dtrain.get_label() #提取label
    preds=1-preds
    precision,recall,threshold=precision_recall_curve(labels,preds,pos_label=0)
    pr=pd.DataFrame({'precision':precision,'recall':recall})
    return 'Max Recall:',pr[pr.precision>=0.97].recall.max()

参数和轮数就按一般设置,然后watchlist不能少,不然就不会输出东西了,比如watchlist=[(xgb_train,'train'), (xgb_test,'eval')]

最后就是xgb.train中的内容了,写成:

bst=xgb.train(param,xg_train,n_round,watchlist,feval=maxRecall,maximize=False)

就行了。feval就是你的metric,maximize要加上,虽然不知道具体有什么用……

 

2、如果你需要自定义损失函数的话。先写你的损失函数,比如:

def custom_loss(y_pre,D_label): #别人的自定义损失函数
    label=D_label.get_label()
    penalty=2.0
    grad=-label/y_pre+penalty*(1-label)/(1-y_pre) #梯度
    hess=label/(y_pre**2)+penalty*(1-label)/(1-y_pre)**2 #2阶导
    return grad,hess

bst=xgb.train(param,xg_train,n_round,watchlist,feval=maxRecall,obj=custom_loss,maximize=False)

只要再加上obj=custom_loss就可以了...