【R言語】Borutaによるランダムフォレストの変数重要度をggplotの箱ひげ図でグラフ化する
Borutaによるランダムフォレストの変数重要度をggplotの箱ひげ図でグラフ化する
デフォルトのグラフよりきれいなグラフが描けるggplotで 変数重要度を可視化する。
library(Boruta) library(rFerns) library(tidyverse) library(plotly) #mlbenchのSonarで試す library(mlbench); data(Sonar) Boruta(Class~.,data=Sonar,doTrace=2,getImp=getImpFerns)->Bor.son #Imp値の箱ひげ図をggplotで描写する #Imp値の取得 df_pboruta <- as.data.frame(Bor.son$ImpHistory) #グラフを書きやすくするため縦長にする。gatherではなくて最新のpivot_longerを使う df_pboruta %>% tidyr::pivot_longer(col = everything(), names_to = "retumei", values_to = "Imp") -> df_pboruta_long [f:id:M_taka072:20200224124925j:plain]<figure class="figure-image figure-image-fotolife" title="imp_boxplot">[f:id:M_taka072:20200224124925j:plain]<figcaption>imp_boxplot</figcaption></figure> #最終的な有効性で色分けするためBor.son$finalDecisionからデータを取得 df_final <- as.data.frame(Bor.son$finalDecision) df_final2 <- as.data.frame(df_final) df_final2 %>% rownames_to_column("retumei") %>% rename("FD" = "Bor.son$finalDecision")-> df_final3 #df_final3をジョインさせる df_pboruta_long %>% left_join(df_final3,key="retumei") -> df_pboruta_long2 #グラフを書く df_pboruta_long2 %>% ggplot(aes(x= reorder(x = retumei, X = Imp, FUN = median),y=Imp,fill=FD))+ geom_boxplot()+ theme_bw()+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ->g1 ggplotly(g1)
こんな感じです。