用lgb.LGBMClassifier训练二分类模型,并输出feature importrance
时间: 2024-02-13 11:07:58 浏览: 171
下面是使用lgb.LGBMClassifier训练二分类模型,并输出feature importance的示例代码:
```python
import lightgbm as lgb
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
# 加载数据集并划分训练集和测试集
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# 定义LightGBM分类器
params = {'objective': 'binary', 'metric': 'binary_logloss'}
clf = lgb.LGBMClassifier(**params)
# 训练模型
clf.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=10, verbose=False)
# 获取特征重要性得分
importance = clf.feature_importances_
feature_names = np.array(data.feature_names)
# 打印特征重要性得分
for name, score in zip(feature_names, importance):
print('{}: {}'.format(name, score))
```
在上面的代码中,我们首先加载了乳腺癌数据集,并将其划分为训练集和测试集。然后,我们使用LGBMClassifier定义了一个分类器,并在训练集上训练模型。训练完成后,我们使用`feature_importances_`属性获取了特征重要性得分,并将每个特征和其对应的得分打印出来。
阅读全文