全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
2356 3
2014-12-18
#**************************
#return the rules of a tree
#**************************
getConds<-function(tree){
  #store all conditions into a list
  conds<-list()
  #start by the terminal nodes and find previous conditions
  id.leafs<-which(tree$status==-1)
          j<-0
          for(i in id.leafs){
                j<-j+1
                prevConds<-prevCond(tree,i)
                conds[[j]]<-prevConds$cond
                while(prevConds$id>1){
                  prevConds<-prevCond(tree,prevConds$id)
                  conds[[j]]<-paste(conds[[j]]," & ",prevConds$cond)
                  if(prevConds$id==1){
                        conds[[j]]<-paste(conds[[j]]," => ",tree$prediction[i])
        break()
      }
    }

  }

  return(conds)
}

#**************************
#find the previous conditions in the tree
#**************************
prevCond<-function(tree,i){
  if(i %in% tree$right_daughter){
                id<-which(tree$right_daughter==i)
                cond<-paste(tree$split_var[id],">",tree$split_point[id])
          }
          if(i %in% tree$left_daughter){
    id<-which(tree$left_daughter==i)
                cond<-paste(tree$split_var[id],"<",tree$split_point[id])
  }

  return(list(cond=cond,id=id))
}

#remove spaces in a word
collapse<-function(x){
  x<-sub(" ","_",x)

  return(x)
}


data(iris)
require(randomForest)
mod.rf <- randomForest(Species ~ ., data=iris)
tree<-getTree(mod.rf, k=1, labelVar=TRUE)
#rename the name of the column
colnames(tree)<-sapply(colnames(tree),collapse)
rules<-getConds(tree)
print(rules)


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-1-15 20:38:30
感谢分享
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-1-17 10:54:21
谢谢分享
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-7-15 17:13:34
菜鸟求教啊,这程序我复制过去没法运行,有哪位整理好没,跪求啊
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群