是否可以从 LGBMClassifier 获取训练集的行数?

Is it possible to get the number of rows of the training set from a LGBMClassifier?

我使用 lightgbm 包中的 lightgbm.sklearn.LGBMClassifier 训练了一个模型。我可以从模型中找出训练数据的列数和列名,但我还没有找到找到训练数据行号的方法。有可能这样做吗?最好的解决方案是从模型中获取训练数据,但我还没有遇到过这样的事情。

# This gives the number of the columns the model is trained with
lgbm_model.n_features_
# Any way to find out the row number of the training data as well?
lgbm_model.n_instances_ # does not exist!

LightGBM 模型的树结构包含有关训练数据中有多少记录会落入树中每个节点(如果该节点是叶节点)的信息。在LightGBM的代码中,这个值叫做internal_count.

由于所有数据都与每棵树的根节点匹配,在大多数情况下,您可以使用该信息计算出给定 LightGBM 模型,训练数据中有多少个实例。

考虑以下示例,使用 lightgbm==3.3.2 和 Python 3.8.8.

import lightgbm as lgb
from sklearn.datasets import make_blobs

X, y = make_blobs(n_samples=1234, centers=[[-4, -4], [-4, 4]])
clf = lgb.LGBMClassifier(num_iterations=10, subsample=0.5)
clf.fit(X, y)
num_data = clf.booster_.dump_model()["tree_info"][0]["tree_structure"]["internal_count"]

print(num_data)
# 1234

这在大多数情况下都有效。在两种特殊情况下,这个数字可能会误导“使用多少数据来训练这个模型”这个问题的答案:

  1. 如果你设置bagging_fraction<1.0,那么在每次迭代中LightGBM将只使用一小部分训练数据来评估分割(see the LightGBM docs for details on bagging_fraction)
  2. 如果您使用“继续训练”,即采用现有模型并执行额外的增强轮次,并且为这些额外的增强轮次使用不同的训练集,则“使用了多少数据来训练该模型”将有一个复杂的答案,这取决于您所指的“此模型”
  3. 所指的增强回合范围