【发布时间】:2014-06-18 17:27:00
【问题描述】:
我想修改函数party/varimp。
函数运行时间很长,我想在主循环中打印进度。
在 R 中调用函数后,我从函数中获取了代码;我编辑了代码并粘贴在 R 中以覆盖包原始代码。
我的新代码是(唯一的修改是底部标记为“MY EDIT”的一小部分):
varimp <- function (object, mincriterion = 0, conditional = FALSE, threshold = 0.2,
nperm = 1, OOB = TRUE, pre1.0_0 = conditional)
{
response <- object@responses
if (length(response@variables) == 1 && inherits(response@variables[[1]],
"Surv"))
return(varimpsurv(object, mincriterion, conditional,
threshold, nperm, OOB, pre1.0_0))
input <- object@data@get("input")
xnames <- colnames(input)
inp <- initVariableFrame(input, trafo = NULL)
y <- object@responses@variables[[1]]
if (length(response@variables) != 1)
stop("cannot compute variable importance measure for multivariate response")
if (conditional || pre1.0_0) {
if (!all(complete.cases(inp@variables)))
stop("cannot compute variable importance measure with missing values")
}
CLASS <- all(response@is_nominal)
ORDERED <- all(response@is_ordinal)
if (CLASS) {
error <- function(x, oob) mean((levels(y)[sapply(x, which.max)] !=
y)[oob])
}
else {
if (ORDERED) {
error <- function(x, oob) mean((sapply(x, which.max) !=
y)[oob])
}
else {
error <- function(x, oob) mean((unlist(x) - y)[oob]^2)
}
}
w <- object@initweights
if (max(abs(w - 1)) > sqrt(.Machine$double.eps))
warning(sQuote("varimp"), " with non-unity weights might give misleading results")
perror <- matrix(0, nrow = nperm * length(object@ensemble),
ncol = length(xnames))
colnames(perror) <- xnames
for (b in 1:length(object@ensemble)) {
tree <- object@ensemble[[b]]
if (OOB) {
oob <- object@weights[[b]] == 0
}
else {
oob <- rep(TRUE, length(y))
}
p <- .Call("R_predict", tree, inp, mincriterion, -1L,
PACKAGE = "party")
eoob <- error(p, oob)
for (j in unique(varIDs(tree))) {
for (per in 1:nperm) {
if (conditional || pre1.0_0) {
tmp <- inp
ccl <- create_cond_list(conditional, threshold,
xnames[j], input)
if (is.null(ccl)) {
perm <- sample(which(oob))
}
else {
perm <- conditional_perm(ccl, xnames, input,
tree, oob)
}
tmp@variables[[j]][which(oob)] <- tmp@variables[[j]][perm]
p <- .Call("R_predict", tree, tmp, mincriterion,
-1L, PACKAGE = "party")
}
else {
p <- .Call("R_predict", tree, inp, mincriterion,
as.integer(j), PACKAGE = "party")
}
perror[(per + (b - 1) * nperm), j] <- (error(p,
oob) - eoob)
}
}
######################
# MY EDIT
print(b)
flush.console()
######################
}
perror <- as.data.frame(perror)
return(MeanDecreaseAccuracy = colMeans(perror))
}
但是在使用的时候,我现在得到一个错误:
> data.cforest.varimp <- varimp(data.cforest, conditional = TRUE)
Error in unique(varIDs(tree)) : could not find function "varIDs"
此错误出现在我没有修改的部分代码中,所以我不明白。
问题出在我的新代码上,还是我尝试修改现有包的方式上?
【问题讨论】:
-
可能是因为
varIDs未导出。你可以试试this。 -
请耐心等待-您可能会发现,在执行
party:::varIDs之后,会弹出一些其他未导出的函数。 :-( -
@joran 非常感谢。如果你想把它作为答案,我会接受并删除我的。
-
不需要...继续接受你的。
-
我从没用过派对套餐,但该死听起来是不是很有趣。
标签: r