首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当模型对象是tuneValue对象时从模型对象访问S4 -插入符号,自定义模型

当模型对象是tuneValue对象时从模型对象访问S4 -插入符号,自定义模型
EN

Stack Overflow用户
提问于 2015-09-02 01:04:17
回答 1查看 163关注 0票数 0

我在插入符号中使用了一个自定义模型,它基本上建立在香草"cforest“方法上。

为了构建我的模型,我为cforest模型获取了modelInfo:

代码语言:javascript
复制
newModel <- getModelInfo("cforest", regex=F)[[1]]

我需要实现一个自定义的预测函数,所以我需要:

代码语言:javascript
复制
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对象的最小代码:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-02 03:05:28

我花了一段时间才弄明白,但其实很简单。因为模型是一个S4对象,我想在其中添加信息.我构建了自己的S4对象,继承了这个模型!

为了做到这一点,我不得不更改"fit“函数。

代码语言:javascript
复制
# 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“类,因此我可以这样做:

代码语言:javascript
复制
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!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32343139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档