我在插入符号中使用了一个自定义模型,它基本上建立在香草"cforest“方法上。
为了构建我的模型,我为cforest模型获取了modelInfo:
newModel <- getModelInfo("cforest", regex=F)[[1]]我需要实现一个自定义的预测函数,所以我需要:
out$predict = function(modelFit, newdata, submodels = NULL) {
# new predict function which needs the tuned parameters
best.params <- modelFit$tuneValue
# rest of the code using best params
}新预测函数的内容本身是不相关的。重点是,我需要从预测函数中调优的值。
虽然代码在其他模型中运行得非常好,但这不能用于cforest,因为在本例中,modelFit是一个"RandomForest“S4对象,而我不能访问tuneValue。(准确的错误是"Error in modelFit$tuneValue : $ operator not defined for this S4 class")
我研究了"RandomForest“对象,它似乎不包含任何插槽中的调优值。
我的猜测是,由于它是一个S4对象,将调优值存储到$tuneValue中的插入符号代码在这种特殊情况下不起作用。
也许我可以在拟合过程中的某个时候手动保存调优值,但我不知道
1-我什么时候应该这样做(何时选择调优值?)
2-在预测期间,我应该把它们保存在哪里才能接触到它们?
有人知道我该怎么做吗?
下面是生成RandomForest S4对象的最小代码:
x <- matrix(rnorm(20*10), 20, 10)
y <- x %*% rnorm(10)
y <- factor(y<mean(y), levels=c(T,F), labels=c("high", "low"))
new_model <- getModelInfo("cforest", regex=F)[[1]]
fit <- train(x=x, y=y, method = new_model)
# this is a RandomForest S4 object
fit$finalModel发布于 2015-09-02 03:05:28
我花了一段时间才弄明白,但其实很简单。因为模型是一个S4对象,我想在其中添加信息.我构建了自己的S4对象,继承了这个模型!
为了做到这一点,我不得不更改"fit“函数。
# loading vanilla model
newModel <- getModelInfo("cforest", regex=F)[[1]]
# backing up old fit fun
newModel$old_fit <- out$fit
# editing fit function to wrap the S4 model into my custom S4 object
newModel$fit <- function(x, y, wts, param, lev, last, classProbs, ...) {
tmp <- newModel$old_fit(x, y, wts, param, lev, last, classProbs, ...)
if(isS4(tmp)) {
old_class <- as.character(class(tmp))
# creating custom class with the slots I need
setClass(".custom", slots=list(.threshold="numeric", .levels="character"), contains=old_class)
# instanciating the new class with values taken from the argument of fit()
tmp <- new(".custom", .threshold=param$threshold, .levels=lev, tmp)
}
tmp
}现在,模型对象一致地属于".custom“类,因此我可以这样做:
newModel$predict = function(modelFit, newdata, submodels = NULL) {
if(isS4(modelFit)){
if(class(modelFit)!=".custom")
error("predict() received a S4 object whose class was not '.custom'")
obsLevels <- modelFit@.levels
threshold <- modelFit@.threshold
} else {
obsLevels <- modelFit$obsLevels
threshold <- modelFit$tuneValue$threshold
}
# rest of the code
}这很好,现在我的自定义模型可以扩展任何插入符号模型,而不管它是依赖于S4对象,比如c林还是svm!
https://stackoverflow.com/questions/32343139
复制相似问题