how to get all terminal nodes - weight & response prediction 'ctree' in r

你说的曾经没有我的故事 提交于 2019-12-04 14:13:12

The Binary tree is a big S4 object, so sometimes it is difficult to extract the data.

But the plot method for BinaryTree object, hase an optional panel function of the form function(node) plotting the terminal nodes. So when you plot you can get all the informations about this node.

here I use the plot function, to extract the information and even better I usee the gridExtra and package to change the form of the terminal node as a table

library(party)
library(gridExtra)
set.seed(100)
lls <- data.frame(N = gl(3, 50, labels = c("A", "B", "C")), 
                  a = rnorm(150) + rep(c(1, 0,150)),
                  b = runif(150))
pond= sample(1:5,150,replace=TRUE)
tt <- ctree(formula=N~a+b, data=lls,weights = pond)
output.df <- data.frame()
innerWeights <- function(node){

 dat <- data.frame (x=node$nodeID,
                    y=sum(node$weights),
                    z=paste(round(node$prediction,2),collapse='  '))
  grid.table(dat,
             cols = c('ID','Weights','Prediction'),
             h.even.alpha=1, 
             h.odd.alpha=1,  
             v.even.alpha=0.5, 
             v.odd.alpha=1)
   output.df <<- rbind(output.df,dat)  # note the use of <<-

}

plot(tt, type='simple', terminal_panel = innerWeights)


data
  ID Weights       Prediction
1  4      24  0.42  0.5  0.08
2  5      17 0.06  0.24  0.71
3  6      24    0.08  0  0.92
4  7     388 0.37  0.37  0.26

Here's what I found , it works fine with a bit extra information. But I just want to post it here just in case someone need them in the future.

y <- do.call(rbind, nodes(tt, unique(where(tt))))
write.table(y, 'clipboard', sep='\t') 

@agstudy , let me know what you think.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!