如何使用xgboost.XGBCClassifier.feature_importances_模型画图?(Matplotlib)
在机器学习中,模型的特征重要性一直是一个很重要的问题。许多算法都提供了某些方法来估计模型特征的重要性。在XGBoost中,我们通过XGBCClassifier.feature_importances_来获取每个特征的重要性得分。本文将讲解如何使用Matplotlib来绘制特征重要性的柱状图。
XGBCClassifier.feature_importances_
首先,我们需要清楚XGBCClassifier的feature_importances_属性来自哪里。由于XGBoost是一种集成模型,该属性是由所有弱学习器的特征重要性得分(以树的形式)的加权平均值计算得出的。因此,该属性表示每个特征对预测的整体贡献程度。让我们看一下一个简单的例子来理解它:
from xgboost import XGBClassifier
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
X, y = data.data, data.target
model = XGBClassifier()
model.fit(X, y)
importances = model.feature_importances_
print(importances)
执行上述代码,可以输出每个特征的重要性得分。
使用Matplotlib绘制柱状图
接下来,我们将使用Matplotlib来绘制柱状图,以更直观地查看特征重要性得分。我们将先将特征得分从高到低排列,然后将它们绘制为一个垂直条形图,其中每个条形表示一个特征,其高度表示该特征的得分。
importances = pd.Series(importances, index=data.feature_names)
importances.sort_values().plot(kind='barh')
plt.title("Feature Importances")
plt.show()
在这个例子中,我们把特征名作为了水平柱形图中每个条形的标签。您可以轻松地编辑此代码,以使柱形图适应任何大小的数据。
编辑样式和颜色
您可以根据需要编辑图形的样式和颜色。在下面的代码中,我们演示了如何更改柱状图的颜色和方向。我们还添加了每个柱形顶部的数字,以方便附加信息。
import numpy as np
# Sort features by importance
indices = np.argsort(importances)[::-1]
# Rearrange feature names so they match the sorted order
names = [data.feature_names[i] for i in indices]
# Create plot
plt.figure(figsize=(20, 10))
plt.title("Feature Importances")
plt.bar(range(X.shape[1]), importances[indices])
plt.xticks(range(X.shape[1]), names, rotation=90)
plt.xlabel('Features')
plt.ylabel('Relative Importance')
# Add numbers at top of each bar
for i in range(X.shape[1]):
plt.text(i, importances[indices][i], round(importances[indices][i], 3), ha='center')
plt.show()
结论
绘制特征重要性的柱状图是一种非常有用的工具,可帮助您理解模型特征如何影响预测结果。通过使用XGBoost的feature_importances_属性和Matplotlib,您可以轻松地生成这些信息丰富的图形。希望本文可以帮助你更好地理解特征重要性的计算和可视化。