Consolidation of party rules
A simple example
>library(partykit)
> partykit:::.list.rules.party(ctree(Petal.Length~.,data=iris))
2
"Petal.Width <= 0.6"
6
"Petal.Width > 0.6 & Sepal.Length <= 6.2 & Petal.Width <= 1.3 & Sepal.Length <= 5.5"
7
"Petal.Width > 0.6 & Sepal.Length <= 6.2 & Petal.Width <= 1.3 & Sepal.Length > 5.5"
....
For example, in the second rule, two occurrences Sepal.Length
can be combined intoSepal.Length<=5.5
So, is there a way to consolidate the rules?
source to share
In the tree graph below, on the way to node 6 (the node whose rules you referenced in your question), we only store the points with Petal.Width
> 0.6 at first. But even then, node 6 does not include all other points with Sepal.Length
<= 5.5, but only those that also have Petal.Width
<= 1.3. In other words, there is an intermediate decay Petal.Width
between the two splits Sepal.Length
, so the first time is Sepal.Length
not redundant.
m1 = ctree(Petal.Length~.,data=iris) plot(m1)
source to share
There's my more efficient way, but these functions might give you what you want:
consolidate_rules <- function(tree){
split.vars <- colnames(tree$node$info$criterion)
split <- partykit:::.list.rules.party(tree)
new.split <- c()
for(i.split in seq_along(split)) {
for (i.split.var in split.vars) {
x0 <- split[i.split]
x1 <- strsplit(x0, " & ")
x2 <- grep(i.split.var, x1[[1]], value = TRUE)
x3l <- strsplit(grep("<=", x2, value = TRUE), " <= ") # lower than
x3g <- strsplit(grep(">", x2, value = TRUE), " > ") # greater
x3e <- strsplit(grep(" %in% ", x2, value = TRUE), "%in%") # elements
x4 <- c()
if (length(x3e) != 0) {
b <- sapply(x3e, "[[", 2)
b1 <- gsub('"', '', b)
b2 <- gsub("[c( )]", "", b1)
b3 <- gsub("(NA,)|(,NA)", "", b2)
b4 <- unique(strsplit(paste0(b3, collapse = ","), ",")[[1]])
x4 <- paste0(i.split.var, ' %in% c("',
paste0(b4, collapse = '", "'),'")')
}
if (length(x3l) != 0) {
x4 <- paste0(i.split.var, " <= ",
min(as.numeric(sapply(x3l, "[[", 2))))
}
if (length(x3g) != 0) {
x4 <- paste0(x4, ifelse(length(x4) > 0 ," & ",""),
i.split.var, " > ",
max(as.numeric(sapply(x3g, "[[", 2))))
}
tmp <- paste0(if(!is.null(new.split[i.split]) &&
!is.na(new.split[i.split]) &
length(x4) >0) {" & "}, x4)
new.split[i.split] <-
paste0(if(!is.null(new.split[i.split]) &&
!is.na(new.split[i.split])) {new.split[i.split]},
tmp)
rm(x0, x1, x2, x3l, x3g, x3e, x4)
}
}
names(new.split) <- names(split)
return(new.split)
}
You can call the function with:
ct <- ctree(Petal.Length~.,data=iris)
consolidate_rules(ct)
For node 6, the result looks like this:
6
"Sepal.Length <= 5.5 & Petal.Width <= 1.3 & Petal.Width > 0.6"
The result is "just" a string of rules, I don't know if you can use it in the same way as an object .list.rules.party
. But I hope this miogt helps you.
source to share