xgboost icon indicating copy to clipboard operation
xgboost copied to clipboard

problems with custom objective function for mean absolute percentage error(MAPE)

Open CaoQi92 opened this issue 10 years ago • 12 comments

Hi,everyone. I have some problems when implement custom objective functions for mean absolute percentage error(MAPE) .

the evaluation metric is defined as follow:

` def evalmape(preds,dtrain):

labels = dtrain.get_label()

error = sum(abs(preds-labels)*1.0/(labels))*1.0/len(labels)

return 'error',error`

the objective function is: ` def mapeobj(preds,dtrain):

labels = dtrain.get_label()

preds = preds

grad = np.sign(preds-labels)*1.0/labels

hess = 0*np.ones(len(preds))

return grad,hess

`

and my parameters' setting is: ` param = {

            'bst:max_depth':6,

            'min_child_weight':1,

            'bst:eta':0.01,

            'subsample':1.0,

            'silent':0, 

            'objective':'reg:linear',

            'tree_method':'exact',

            'lambda':'1' 

}`

but i just found that the tree didn't split at all and the prediction value stay 0.5 all the time. all my labels is larger than 1.

than I found that there is a line in xgboost\src\tree\param.h,

if (sum_hess < min_child_weight) return 0.0;

I guess it may because the hess in my objective function is 0,so I set the parameter min_child_weight = 0. The results shows that the tree start split now,but the MAPE Swings back and forth between the 1 and 1000. But the min MAPE abviously should be smaller than 0.

Is there any problems in my setting?

And I also wonder that if xgboost can optimal the loss function such as MAPE? Has anyone tried that? I would be grateful if you can help me.Thank you.

CaoQi92 avatar Nov 27 '16 08:11 CaoQi92

The scores on leaves are calculated by dividing sum_hess. https://github.com/dmlc/xgboost/blob/master/src/tree/param.h#L242 In this objective, scores and grad tends to be very large.(It may be negative)

  1. Greater lambda
  2. Lesser learning_rate

Both prevent that the scores are too far. But I don't think these are effective.

marugari avatar Nov 28 '16 07:11 marugari

  1. Set max_delta_step > 0

marugari avatar Nov 28 '16 07:11 marugari

@bloom77 : please see #1428 and #603

khotilov avatar Nov 29 '16 16:11 khotilov

I opened an issue explaining the case https://github.com/dmlc/xgboost/issues/1825

tqchen avatar Nov 29 '16 21:11 tqchen

@tqchen Is it possible to give an example of how that would work for the MAPE metric? Are we supposed to find the function that approximates the upper bound of MAPE?

I'm trying to use the Mean Squared Percentage Error to give it a derivative:

def mspe(y, dtrain):
    yhat = dtrain.get_label()
    grad = 2.0/yhat * (y * 1.0 / yhat - 1)
    hess = 2.0/(yhat**2)
    return grad, hess

and then I run it with

params={'eta': 0.05, 'max_depth': 7, 'colsample_bytree': 1, 'subsample': 1, 'min_child_weight':12}
clf = xgb.train(params, xg_train, num_boost_round=500,
                early_stopping_rounds=10, evals=[(xg_train, 'train'), (xg_test, 'test')],
                 obj= mspe
               )

but same as @bloom77 the predictions are stuck at 0.5, probably because the hessian is too small (assuming I did the derivatives correctly..)

zweicoder avatar Dec 05 '16 10:12 zweicoder

yes, use an upper bound. In most cases, for example, set second order gradient to be bigger than zero could do, you can try to plot the curve and see how well the function approximates the upper bound

tqchen avatar Dec 05 '16 10:12 tqchen

@zweicoder why not consider using the "autograd" package in-place of computing your own gradient & hessian?

def mspe(y, y_pred): from autograd import grad from autograd import hessian mape = lambda y, y_pred: autograd.numpy.sum(autograd.numpy.abs(y_pred - y)*1.0/(y))*1.0/len(y) grad = grad(mape) hessian = hessian(mape) return grad, hess

vatsan avatar Dec 12 '16 11:12 vatsan

@vatsan autograd is very slowly in computation when dealing with moderately sized data. In my case it is unusable (taking hessian of 5000 elements would already take a few minutes). The results is also the same as with the analytical function - the gradients are too small and the predictions are stuck at 0.5

zweicoder avatar Dec 13 '16 13:12 zweicoder

@zweicoder True, i observed it while running it on my own task. It was very slow & XGBoost crashed eventually.

vatsan avatar Dec 13 '16 14:12 vatsan

Hey, mape is too small to converge , 100* grad and 100hess it will work better label = t.get_label() grad = -100((label-y)/label) hess = 100/(label) return grad,hess

alanleemachinelearning avatar May 09 '17 02:05 alanleemachinelearning

@alanleemachinelearning thanks,may I ask why the grad and hess can express like this and work fine? the derivation of grad and hess should like this: grad =sign(preds-labels)/labels hess =zeros(len(preds))

zhaibowen avatar Sep 07 '17 00:09 zhaibowen

@alanleemachinelearning when I use your method,the train err and val err are all decrease initially, but then increase both, they can't converge

zhaibowen avatar Sep 07 '17 01:09 zhaibowen