【问题标题】:How to plot the graph in python like varImpPlot() method plots in R ,for plotting the important variables in Random forest?如何在 python 中绘制图形,如 R 中的 varImpPlot() 方法图,用于绘制随机森林中的重要变量?
【发布时间】:2018-02-22 22:08:20
【问题描述】:

我的数据包含大约 370 个特征,并且我已经建立了一个随机森林模型来获取重要特征,但是当我绘制时我无法弄清楚要考虑的特征,因为 370 个特征在 x 中看起来非常笨拙-轴。

谁能帮我在python中绘制图表,就像varImpPlot()在R中绘制的图表。

【问题讨论】:

    标签: python r matplotlib machine-learning random-forest


    【解决方案1】:

    在 R 的 randomForest 包中,varImpPlot() 绘制最重要的前 30 个变量,您可以在 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()
    

    【讨论】:

      猜你喜欢
      • 2012-06-10
      • 2017-01-12
      • 2021-08-15
      • 2014-05-25
      • 2020-06-06
      • 1970-01-01
      • 2022-01-12
      • 2017-03-25
      相关资源
      最近更新 更多