如何在Python中绘制类似于R中varImpPlot()方法绘制的图形,用于绘制随机森林中重要变量的图形?

4

我有一些关于IT技术的数据,其中包含约370个特征。我已经构建了一个随机森林模型来获取重要的特征,但是当我绘图时,由于x轴上显示了太多的特征,我无法确定应该考虑哪些特征。

有没有人能帮助我在Python中绘制图形,就像在R中使用varImpPlot()绘制的图形一样。

1个回答

3
在R中的randomForest软件包中,varImpPlot()绘制了重要性最高的前30个变量,你可以使用来自sklearn帮助页面的示例在Python中执行类似操作: sklearn help page
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=1000,
                           n_features=370,
                           n_informative=16,
                           n_classes=2,
                           random_state=0)

forest = RandomForestClassifier(random_state=0)
forest.fit(X, y)

为了绘制它,我们可以将重要性评分放入 pd.Series 中并绘制前 30 名:

importances = pd.Series(forest.feature_importances_,index=X.columns)
importances = importances.sort_values()
importances[-30:].plot.barh()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接