gpt4 book ai didi

r - 在 rpart.plot 中格式化拆分标签

转载 作者:行者123 更新时间:2023-12-04 11:50:22 29 4
gpt4 key购买 nike

我正在用 rpart.plot::prp() 绘制一棵树,很像:

library("rpart.plot")
data("ptitanic")
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)
prp(tree, , fallen.leaves = FALSE, type=4, extra=1, varlen=0, faclen=0, yesno.yshift=-1)

enter image description here

即使某些变量是整数(agesibsp),rpart 也会创建一个看似任意的分割点,这会让观看者感到困惑。船上没有人有 2.5 个 sibling /配偶——逻辑分割是 sibsp >= 3

我在这个优秀的 tutorial 中查看了 split.fun?prp。除了使用正则表达式来捕获数字、正确格式化并在标签字符串中替换它之外,我想不出 prp 中的任何解决方案。

我正在考虑的一个变通方法是传递修改后的(类rpart 的对象),其中的内容已四舍五入。是否可以通过修改 tree$splits 来做到这一点?

还有其他想法吗?

最佳答案

1) 有序因子 我认为 age 作为连续变量是可以的,但要处理 sibspparch将它们变成有序因子:

data <- transform(data, sibsp = ordered(sibsp), parch = ordered(parch))
tree <- rpart(survived~., data=data, cp=.02)
prp(tree, , fallen.leaves = FALSE, type=4, extra=1, varlen=0, faclen=0, yesno.yshift=-1)

screenshot

2) split.fun 另一种方法是像这样指定我们自己的 split.fun:

# next 4 lines are same as in question
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)

split.labs <- function(x, labs, digits, varlen, faclen) {
sapply(labs, function(lab)
if (grepl(">=|<", lab)) {
rhs <- sub(".* ", "", lab)
lab <- sub(rhs, ceiling(as.numeric(rhs)), lab)
} else lab)
}
prp(tree, , fallen.leaves = FALSE, type=4, extra=1, varlen=0, faclen=0, yesno.yshift=-1,
split.fun = split.labs) # same as in question except for split.fun= arg

这给出:

screenshot

(2a) (2) 的变体提供了更多的控制,即可以精确指定要修改的变量,如下所示:

# next 4 lines are same as in question
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)

split.labs2 <- function(x, labs, digits, varlen, faclen) {
sapply(labs, function(lab)
if (grepl("age|sibsp|parch", lab)) {
rhs <- sub(".* ", "", lab);
lab <- sub(rhs, ceiling(as.numeric(rhs)), lab)
} else lab)
}

# similar to (2) except we use clip.right.labs = FALSE and split.labs2

prp(tree, type = 4, fallen.leaves = FALSE, extra=1, varlen=0, faclen=0,
yesno.yshift=-1, clip.right.labs = FALSE, split.fun = split.labs2)

screenshot

关于r - 在 rpart.plot 中格式化拆分标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35490949/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com