我正在尝试将单个 LightGBM 决策树(即 num_boost_round = 1 和 num_leaves = 16)转换为 Python 条件语句。有办法做到这一点吗?我在 stackoverflow 上找到了一篇关于使用 sklearn 决策树实现执行此操作的帖子,但这并不直接适用于我的案例。
我刚刚写了一个Python包来做到这一点:
pip install lgbm-to-code
import lightgbm as lgb
from lgbm_to_code import lgbm_to_code
# Train your LightGBM model...
# For example:
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
diabetes = load_diabetes()
X = diabetes.data
y = diabetes.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = lgb.LGBMRegressor(random_state=42)
model.fit(X_train, y_train)
# Convert to desired language
languages = ["python", "cpp", "javascript"]
for language in languages:
code = lgbm_to_code.parse_lgbm_model(model._Booster, language)
with open(f"lgbm_model_{language}.{'py' if language == 'python' else language}", "w") as f:
f.write(code)