对于一个大学项目,我正在编写决策树算法。为此,我为数字变量编写了一个确定最佳分割的函数。当我给它输入变量时,此函数可以正常工作。分割的选择基于基尼系数。
gini.index <- function(input){
l <- length(input)
som <- sum(input)
probability <- 1 - som/l
gini <- probability * (1-probability)
gini
}
impurity.reduction <- function(y, yl,yr){
pi.l <- length(yl)/length(y)
pi.r <- length(yr)/length(y)
imp.red <- gini.index(y) - (pi.l * gini.index(yl) + pi.r * gini.index(yr))
imp.red
}
best.split.point <- function(x,y){
if (length(x) == length(y)){
#bekijk mogelijke numerieke waarden om op te splitten
x.sorted <- sort(unique(x))
x.sorted.length <- length(x.sorted)
splitpoints <- (x.sorted[1:(x.sorted.length-1)]+x.sorted[2:x.sorted.length])/2
splitpoints
#creer een lege vector om in de for loop alle impurity reduction waarden per split op te kunnen slaan
puur <- vector()
#bekijk voor ieder splitpoint wat de impurity reduction is
for (i in 1:length(splitpoints)) {
y1 <- y[x < splitpoints[i]]
y2 <- y[x >= splitpoints[i]]
puur <- c(puur,impurity.reduction(y,y1,y2))
}
splitpoints[puur == max(puur)]
}
else {
return("Variables X & Y need to be of the same length")
}
}
当我尝试使用以下命令找出对数据集中的每个单独列进行最佳拆分的功能时,会出现以下错误:
sapply(credit.dat, best.split.point(credit.dat, y))
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'Variables X & Y need to be of the same length' of mode 'function' was not found
其他一些帖子表明,这可能是由于我的功能命名(我已经更改)引起的。我认为错误可能与我的功能组成有关。你们中的一位可以帮助我找出导致此错误的原因吗?
可在此处获得信用数据集:http://www.cs.uu.nl/docs/vakken/mdm/credit.txt y变量是信用数据集的第六列,因此:
credit.dat <- read.csv("http://www.cs.uu.nl/docs/vakken/mdm/credit.txt")
y <- credit.dat[, 6]
答案 0 :(得分:0)
因此有效:
credit.dat <- read.csv("http://www.cs.uu.nl/docs/vakken/mdm/credit.txt")
y <- credit.dat[, 6]
sapply(credit.dat, FUN=best.split.point, y=y)
# > sapply(credit.dat, best.split.point, y=y)
# age married house income gender class
# 32.5 0.5 0.5 36.0 0.5 0.5