【问题标题】:for loop to plot the top n features importance in bokeh in python without explicitly typing the column namesfor循环在python中绘制散景中前n个特征的重要性,而无需显式输入列名
【发布时间】:2018-07-16 15:46:34
【问题描述】:

我想在散景中绘制RandomForestClassifier() 中的顶部 n 特征,而不在 y 变量中明确指定列名。

  1. 所以首先,它可以直接从随机分类器的顶部特征中获取列名和值,而不是在变量 y 中输入列名。

    y = df['new']
    x = df.drop('new', axis=1)
    rf = RandomForestClassifier()
    rf.fit(x,y)
    
    #Extract the top feature from above and plot in bokeh
    
    source = ColumnDataSource(df)
    
    p1 = figure(y_range=(0, 10))
    
    # below I would like it to use the top feature in RandomClassifier 
    # instead of explicitly writing the column name, horsePower,
    # from the top features column
    
    p1.line(
        x = 'x',
        y = 'horsePower', 
        source=source,
        legend = 'Car Blue',
        color = 'Blue'
     )
    
  2. 我们可以构建一个for 循环来绘制散景中的 n 个顶部特征,而不是仅指定第一个特征或第二个特征。我想它是接近这个的东西

    for i in range(5):
        p.line(x = 'x', y = ???? , source=source,) #top feature in randomClassifier
        p.circle(x = 'x', y = ???? , source=source, size = 10)
        row = [p]
    
    output_file('TopFeatures')
    show(p)
    

我已经从模型的 RandomForestClassifier 中提取了前 15 个特征,并使用

打印了前 15 个
 new_rf = pd.Series(rf.feature_importances_,index=x.columns).sort_values(ascending=False) 

print(new_rf[:15]) 

【问题讨论】:

    标签: python pandas plot bokeh


    【解决方案1】:

    简单地遍历熊猫系列的索引值,new_rf,因为它的索引是列名:

    # TOP 1 FEATURE
    p1.line(
        x = 'x',
        y = new_rf.index[0], 
        source = source,
        legend = 'Car Blue',
        color = 'Blue'
     )
    
    # TOP 5 FEATURES
    for i in new_rf[:5].index:
    
        output_file("TopFeatures_{}".format(i))
    
        p = figure(y_range=(0, 10))
        p.line(x = 'x', y = i, source = source)
        p.circle(x = 'x', y = i, source = source, size = 10)
    
        show(p)
    

    【讨论】:

    • 对不起,我有一个小问题。如何在同一个图中绘制前 5 个“new_rf”? x 轴必须有特征的名称,y 值是特征重要性。当我打印“new_rf”时,我得到 2 列,第一列是名称,第二列是正确的特征重要性值。它的类型是“pandas.core.series.Series”。
    • 查看散景的multi_line()。也许p.multi_line(df[col for col in df.columns if col in new_rf[:5].index])
    猜你喜欢
    • 2021-11-13
    • 2017-11-14
    • 1970-01-01
    • 2022-06-20
    • 2019-11-05
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多