f1_score metric in lightgbm

后端 未结 2 945
别跟我提以往
别跟我提以往 2021-01-01 02:54

I want to train a lgb model with custom metric : f1_score with weighted average.

I went through the advanced examples of lightgbm over here

2条回答
  •  一生所求
    2021-01-01 03:35

    The docs are a bit confusing. When describing the signature of the function that you pass to feval, they call its parameters preds and train_data, which is a bit misleading.

    But the following seems to work:

    from sklearn.metrics import f1_score
    
    def lgb_f1_score(y_hat, data):
        y_true = data.get_label()
        y_hat = np.round(y_hat) # scikits f1 doesn't like probabilities
        return 'f1', f1_score(y_true, y_hat), True
    
    evals_result = {}
    
    clf = lgb.train(param, train_data, valid_sets=[val_data, train_data], valid_names=['val', 'train'], feval=lgb_f1_score, evals_result=evals_result)
    
    lgb.plot_metric(evals_result, metric='f1')
    

    To use more than one custom metric, define one overall custom metrics function just like above, in which you calculate all metrics and return a list of tuples.

    Edit: Fixed code, of course with F1 bigger is better should be set to True.

提交回复
热议问题