对于一个大学项目,我正在编写一个决策树算法。为此,我为数字变量编写了一个确定最佳拆分的函数。当我给它输入变量时,这个函数可以正常工作。拆分的选择基于基尼指数。
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]
所以它有效:
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