ともにゃん的データ分析ブログ

勉強したことの備忘録とかね

【R】ランダムフォレストを実行できるパッケージ{ranger}用の、変数の重要度を可視化する関数

タイトル通りの関数を作ったのでここに置いておきます。
可視化には{ggplot2}を使用しています。

# ranger_fitにrangerで構築したモデルを、topに表示したい変数の個数を指定します。
# topに値を指定しない場合は全変数の重要度を表示します。変数の数が多い時にご指定ください。
plotVarImp <- function(ranger_fit, top=NULL){
  library(ggplot2)
  
  pd <- data.frame(Variable = names(ranger_fit$variable.importance),
                   Importance = as.numeric(ranger_fit$variable.importance)) %>% 
    arrange(desc(Importance))
  
  if(is.null(top)){
    pd <- arrange(pd, Importance)
  } else {
    pd <- arrange(pd[1:top,], Importance)
  }
  p <- ggplot(pd, aes(x=factor(Variable, levels=unique(Variable)), y=Importance)) +
    geom_bar(stat="identity") +
    xlab("Variables") + 
    coord_flip()
  plot(p)
}