特征重要性图代码,纵轴表示特征名,横轴表示特征重要性得分
时间: 2023-12-27 12:47:54 浏览: 22
以下是一个简单的特征重要性图的代码示例,使用了matplotlib绘制:
```python
import matplotlib.pyplot as plt
import seaborn as sns
# feature_names是一个列表,包含所有的特征名
# feature_importances是一个列表或数组,包含所有特征的重要性得分
def plot_feature_importances(feature_names, feature_importances):
# 将特征名和重要性得分组合成一个元组的列表
feature_importances = list(zip(feature_names, feature_importances))
# 按照重要性得分进行排序
feature_importances.sort(key=lambda x: x[1], reverse=True)
# 取出前10个特征及其重要性得分
top_features = feature_importances[:10]
# 创建一个包含特征名和重要性得分的DataFrame
top_features_df = pd.DataFrame(top_features, columns=['Feature', 'Importance'])
# 绘制水平条形图
sns.barplot(x='Importance', y='Feature', data=top_features_df, color='blue')
# 添加标题和轴标签
plt.title('Top 10 Feature Importances')
plt.xlabel('Importance')
plt.ylabel('Feature')
plt.show()
```
使用示例:
```python
feature_names = ['feature1', 'feature2', 'feature3', 'feature4']
feature_importances = [0.2, 0.3, 0.1, 0.4]
plot_feature_importances(feature_names, feature_importances)
```
这将绘制一个水平条形图,显示前10个特征及其重要性得分。您可以根据需要修改代码以适应不同的数据集和绘图需求。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)