如何将焦距损失添加到lightgbm&xgboost的自定义目标函数中

时间:2019-03-19 16:18:11

标签: xgboost loss-function lightgbm

这是我的客户目标功能,我想在lightgbm中添加“焦点损失”。

###############我的代码
from numpy import log
def grad_func(y_true,y_pred):
   if y_true==1:
        return -0.5*(2y_pred - 2)log(y_pred) - 0.5(-y_pred + 1)**2/y_pred
   if y_true==0:
        return 0.5y_pred**2/(-y_pred + 1) - 1.0y_predlog(-y_pred + 1)

def hess_func(y_true,y_pred):
    if y_true==1:
         return -1.0log(y_pred) - (2.0y_pred - 2.0)/y_pred + 0.5*(y_pred - 1)2/y_pred2
    if y_true==0:
         return 0.5y_pred**2/(y_pred - 1)**2 - 2.0y_pred/(y_pred - 1) - 1.0*log(-y_pred + 1)

def focal_loss(y_true,y_pred):
    gamma=2.0
    alpha=0.5
    y_true=y_true.tolist()
    y_pred=y_pred.tolist()
    grad=[]
    hess=[]
    for i in range(len(y_true)):
    if y_pred[i]==0:
       y_pred[i]=y_pred[i]+1e-12 ## avoid that the y_pred==0
#and can not be divided

    grad.append(grad_func(y_true[i],y_pred[i]))
    hess.append(hess_func(y_true[i],y_pred[i]))
    return np.array(grad),np.array(hess)

它可以工作,但始终像小偷一样工作 enter image description here

0 个答案:

没有答案