R 中的 S4 对象创建

S4 object creation in R

我正忙于比较 R 中不同的机器学习技术。 是这样的:我以自动化的方式制作了几个功能 能够创建不同的预测模型(例如:逻辑回归、随机森林、神经网络、混合集成等)、预测、混淆矩阵、多个统计数据(例如 AUC 和 Fscore)和不同的图。

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

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

我应该如何编程这样的class?我如何定义每个模型可以是某种不同的类型(我假设我创建的所有模型都是 S3 对象,那么我如何在我的 S4 class 中定义它?

最终结果应该能够做这样的事情:modelList[i]@plot 应该例如召唤所请求的情节。 names(modelList[i]) 应该给出所用模型的名称(如果这不可能,modelList[i]@name 就可以)。此外,应该可以 select 根据参数(例如 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)
  }
)

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

```

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

```

由于在返回的对象中没有共同的 class,使用 S3 可能更有意义,它的语法不那么严格,并且允许您分配各种 class 输出到相同的字段名称。你的问题实际上很难回答,因为 R 的无数 OO 系统有很多不同的方法。

使用 setOldClass() 将每个 S3 class 升级为 S4 等价物

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

使用setClassUnion()在层次结构中插入一个公共基础class

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)。