R中的S4对象创建

时间:2016-02-27 09:59:06

标签: r object s4

我正在忙着比较R中不同的机器学习技巧。 情况就是这样:我以自动方式制作了几个函数 能够创建每个不同的预测模型(例如:逻辑回归,随机森林,神经网络,混合集合等),预测,混淆矩阵,几个统计(例如AUC和Fscore),以及不同的图。

现在我想在R中创建一个S4(或S3?)对象列表,其中每个对象包含模型,预测,图,混淆矩阵,auc和fscore。

这个想法是每个函数都创建这样的对象,然后将它附加到return语句中的对象列表中。

我应该如何编写这样的课程?我怎样才能定义每个模型可以有不同的类型(我想我创建的所有模型都是S3对象,那么如何在我的S4类中定义它?

最终结果应该能够做到这样的事情:modelList [i] @plot应该例如召唤所请求的情节。和名称(modelList [i])应该给出使用模型的名称(如果这不可能,modelList [i] @name将会这样做)。此外,应该可以根据参数(例如AUC)从列表中选择最佳模型。 我没有创建这样的对象的经验,所以这是我现在的代码/想法:

 modelObject <- setClass(
  # Set the name for the class
  "modelObject",

  # Define the slots
  slots = c(
    modelName = "character"
    model = #should contain a glm, neural network, random forest , etc model
    predictions = #should contain a matrix or dataframe of custid and prediction
    rocCurve = #when summoned, the ROC curve should be plotted
    plotX = #when summoned, plot X should be plotted
    AUC = "numeric" #contains the value of the AUC
    confusionMatrix = "matrix" #prints the confusion matrix in the console
    statX = "numeric"#contains statistic X about the confusion matrix e.g. Fscore
  ),
  # Set the default values for the slots. (optional)
  prototype=list(
    # I guess i can assign NULL to each variable of the S4 object
  ),

  # Make a function that can test to see if the data is consistent.
  # This is not called if you have an initialize function defined!
  validity=function(object)
  {
    #not really an idea how to handle this
    }
    return(TRUE)
  }
)

2 个答案:

答案 0 :(得分:3)

使用setOldClass()将每个S3类提升为S4等效

setOldClass("lm")
setOldClass(c("glm", "lm"))
setOldClass(c("nnet.formula", "nnet"))
setOldClass("xx")

使用setClassUnion()在层次结构中插入公共基类

setClassUnion("lmORnnetORxx", c("lm", "nnet", "xx"))

.ModelObject <- setClass("ModelObject", slots=c(model="lmORnnetORxx"))

setMethod("show", "ModelObject", function(object) {
    cat("model class: ", class(object@model), "\n")
})

行动中:

> library(nnet)
> x <- y <- 1:10
> .ModelObject(model=lm(x~y))
model class:  lm 
> .ModelObject(model=glm(x~y))
model class:  glm lm 
> .ModelObject(model=nnet(x~y, size=10, trace=FALSE))
model class:  nnet.formula nnet 

我认为您还希望实现一个Models对象,其中包含一个列表,其中所有元素都是ModelObject;约束将由有效性方法强加(见?setValidity)。

答案 1 :(得分:1)

我会做的是,对于modelObject课程中您想要的每个插槽,确定预期值的范围。例如,您的model槽必须支持模型训练函数可以返回的所有可能的对象类(例如lm(),glm(),nnet()等)。在示例中,您会看到返回以下对象:

```

x <- y <- 1:10
class(lm(x~y))
class(glm(x~y))
class(nnet(x~y, size=10))

```

由于返回的对象中没有公共类,因此使用S3的语法更为严格,并且允许您将各种类别的输出分配给相同的字段名称。考虑到R的无数OO系统采用了许多不同的方法,你的问题实际上很难回答。

相关问题