for i, feature in enumerate(data.feature_names): print(f"{feature}: {importance[i]}")
时间: 2024-04-18 11:34:01 浏览: 168
这段代码是一个循环,用于遍历`data.feature_names`中的特征名称,并打印每个特征的重要性评估值。
`enumerate()`函数用于同时获取索引和元素值,`i`代表索引,`feature`代表特征名称。通过`enumerate(data.feature_names)`,可以依次遍历每个特征名称。
在每次循环中,使用`importance[i]`来获取对应特征的重要性评估值,并使用`print()`函数将特征名称和对应的重要性评估值打印出来。`f"{feature}: {importance[i]}"`是一个格式化字符串,用于将特征名称和对应的重要性评估值拼接成一条字符串进行打印。
相关问题
lightgbm调用feature importance
在 LightGBM 中,可以通过调用 `feature_importance()` 函数来获取每个特征的重要性得分。该函数返回一个包含每个特征得分的列表,列表的顺序与特征在训练数据中的顺序相同。
以下是一个示例代码,展示了如何使用 `feature_importance()` 函数:
```python
import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 加载数据集
boston = load_boston()
X, y = boston.data, boston.target
feature_names = boston.feature_names
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义 LightGBM 模型
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': 'mse',
'num_leaves': 31,
'learning_rate': 0.05
}
lgb_train = lgb.Dataset(X_train, y_train)
lgb_test = lgb.Dataset(X_test, y_test, reference=lgb_train)
model = lgb.train(params, lgb_train, num_boost_round=1000, valid_sets=lgb_test, early_stopping_rounds=100)
# 获取每个特征的重要性得分
importance_list = model.feature_importance()
importance_dict = {feature_names[i]: score for i, score in enumerate(importance_list)}
importance_df = pd.DataFrame.from_dict(importance_dict, orient='index', columns=['Score'])
importance_df = importance_df.sort_values(by='Score', ascending=False)
# 输出特征重要性得分
print(importance_df)
```
在上面的代码中,首先加载了波士顿房价数据集,然后将其划分为训练集和测试集。接着定义了 LightGBM 模型,并在训练集上进行训练。最后,调用 `feature_importance()` 函数获取每个特征的重要性得分,并将其转化为 DataFrame 类型并按得分从高到低排序输出。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![none](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)