【问题标题】:DICT() and MATPLOTLIB?DICT() 和 MATPLOTLIB?
【发布时间】:2016-10-26 22:58:46
【问题描述】:

我创建了一个字典来将 sklearn 中决策树的特征重要性与我的 df 中的相应特征名称相匹配。下面是代码:

   importances = clf.feature_importances_
   feature_names = ['age','BP','chol','maxh',
          'oldpeak','slope','vessels',
          'sex_0.0','sex_1.0', 
          'pain_1.0','pain_2.0','pain_3.0','pain_4.0',
          'bs_0.0','bs_1.0',
          'ecg_0.0','ecg_1.0','ecg_2.0',
          'ang_0.0','ang_1.0',
          'thal_3.0','thal_6.0','thal_7.0']
   CLF_sorted = dict(zip(feature_names, importances))

在输出中我得到了这个:

   {'BP': 0.053673644739136502,
    'age': 0.014904980747733202,
    'ang_0.0': 0.0,
    'ang_1.0': 0.0,
    'bs_0.0': 0.0,
    'bs_1.0': 0.0,
    'chol': 0.11125922817930389, ...}

正如我所料。我有两个问题要问你:

  1. 如何创建一个条形图,其中 x 轴代表 feature_names,y 轴代表对应的 importances

  2. 如果可能的话,我怎样才能以降序方式对条形图进行排序?

【问题讨论】:

    标签: python-2.7 numpy matplotlib scikit-learn sklearn-pandas


    【解决方案1】:

    试试这个:

    import pandas as pd
    
    df = pd.DataFrame({'feature': feature_names , 'importance': importances})
    df.sort_values('importance', ascending=False).set_index('feature').plot.bar(rot=0)
    

    演示:

    d ={'BP': 0.053673644739136502,
        'age': 0.014904980747733202,
        'ang_0.0': 0.0,
        'ang_1.0': 0.0,
        'bs_0.0': 0.0,
        'bs_1.0': 0.0,
        'chol': 0.11125922817930389}
    
    df = pd.DataFrame({'feature': [x for x in d.keys()], 'importance': [x for x in d.values()]})
    
    In [63]: import matplotlib as mpl
    
    In [64]: mpl.style.use('ggplot')
    
    In [65]: df.sort_values('importance', ascending=False).set_index('feature').plot.bar(rot=0)
    Out[65]: <matplotlib.axes._subplots.AxesSubplot at 0x8c83748>
    

    【讨论】:

    • 谢谢!我正在使用 Python 2.7,它返回如下错误:“name 'd' is not defined”。这个问题有什么解决办法吗?很抱歉我的基本问题,但我一个月前才开始认真使用 python。
    • @ElenaPhys,尝试改用df = pd.DataFrame({'feature': feature_names , 'importance': importances})d - 是您从 importancesfeature_names 创建的字典
    • @ElenaPhys,有帮助吗?
    • 如何设置绘图的大小?我阅读了 pandas 文档,但我只找到了调整条形的方法。
    • @ElenaPhys,当然,试试:.plot.bar(rot=0, figsize=(12, 10))。 Pandas 绘图函数继承 matplotlib 参数...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多