在LightGBM中使用eval()评估测试数据集

时间:2019-02-25 03:20:37

标签: eval ranking lightgbm

我已经用LightGBM训练了目标为“ lambdarank”的排名模型。 我想评估模型以使用最佳迭代获得测试数据集的nDCG分数,但我从未能够使用lightgbm.Booster.eval()或lightgbm.Booster.eval_train()函数。

首先,我创建了3个数据集实例,即训练集,有效集和测试集:

lgb_train = lgb.Dataset(x_train, y_train, group=query_train, free_raw_data=False)

lgb_valid = lgb.Dataset(x_valid, y_valid, reference=lgb_train, group=query_valid, free_raw_data=False)

lgb_test = lgb.Dataset(x_test, y_test, group=query_test)

然后我使用lgb_train和lgb_valid训练模型:

gbm = lgb.train(params,
            lgb_train,
            num_boost_round=1500,
            categorical_feature=chosen_cate_features,    
            valid_sets=[lgb_train, lgb_valid],
            evals_result=evals_result,
            early_stopping_rounds=150  
)

训练后我调用eval()或eval_train()函数时,它将返回错误:

gbm.eval(data=lgb_test,name='test')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-122-7ff5ef5136b8> in <module>()
----> 1 gbm.eval(data=lgb_test,name='test')

/usr/local/lib/python3.6/dist-packages/lightgbm/basic.py in eval(self, data, 
name, feval)
   1925             raise TypeError("Can only eval for Dataset instance")
   1926         data_idx = -1
-> 1927         if data is self.train_set:
   1928             data_idx = 0
   1929         else:

AttributeError: 'Booster' object has no attribute 'train_set'

gbm.eval_train()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-123-0ce5fa3139f5> in <module>()
----> 1 gbm.eval_train()

/usr/local/lib/python3.6/dist-packages/lightgbm/basic.py in eval_train(self, 
feval)
   1956             List with evaluation results.
   1957         """
-> 1958         return self.__inner_eval(self.__train_data_name, 0, feval)
   1959 
   1960     def eval_valid(self, feval=None):

/usr/local/lib/python3.6/dist-packages/lightgbm/basic.py in 
__inner_eval(self, data_name, data_idx, feval)
   2352         """Evaluate training or validation data."""
   2353         if data_idx >= self.__num_dataset:
-> 2354             raise ValueError("Data_idx should be smaller than number 
of dataset")
   2355         self.__get_eval_info()
   2356         ret = []

ValueError: Data_idx should be smaller than number of dataset

当我调用eval_valid()函数时,它返回一个空列表。

有人可以告诉我如何正确评估LightGBM模型并使用测试集获得nDCG分数吗?谢谢。

1 个答案:

答案 0 :(得分:0)

如果将 keep_training_booster=True 作为参数添加到 lgb.train,返回的 booster 对象将能够执行 evaleval_train(尽管 {{即使在 eval_valid 中提供了 valid_sets,1}} 仍会出于某种原因返回一个空列表。

Documentation 说:

<块引用>

lgb.train (bool, optional (default=False)) – 返回的 Booster 是否将用于保持训练。如果为False,返回值将在返回前转换为_InnerPredictor。