首页 > 解决方案 > R:为什么插入符号中的 train() 函数返回空模型(调用:NULL)?

问题描述

例如,我使用 train 构建逻辑回归,如下所示:

library(caret)

n <- 1000
df <- data.frame(x1=runif(n, min=0, max=1),
                 x2=runif(n, min=0, max=1),
                 y = rep(c('N', 'Y'), n/2)[sample(n, n)])
lmFit <- train(y ~ ., data=df, method='glm', family = binomial)
summary(lmFit)

它会显示

Call:
NULL    
....

是否有设置让它显示正确的glm呼叫,而不是NULL?谢谢你。

标签: rr-caret

解决方案


我没有看到提供给摘要的这样一个设置,因为 summary.train 方法去除了调用值:

> class(lmFit)
[1] "train"         "train.formula"
> getAnywhere(summary.train)
A single object matching ‘summary.train’ was found
It was found in the following places
  registered S3 method for summary from namespace caret
  namespace:caret
with value

function (object, ...) 
summary(object$finalModel, ...)
<bytecode: 0x1bc4f820>
<environment: namespace:caret>

> names(lmFit)
 [1] "method"       "modelInfo"    "modelType"    "results"      "pred"         "bestTune"     "call"        
 [8] "dots"         "metric"       "control"      "finalModel"   "preProcess"   "trainingData" "resample"    
[15] "resampledCM"  "perfNames"    "maximize"     "yLimits"      "times"        "levels"       "terms"       
[22] "coefnames"    "xlevels"

您可以制作该函数的变体,使用 输出调用cat,或将其作为summary对象的一部分返回,或两者兼而有之。或者您可以将其添加到您的脚本中:

> lmFit$call
train.formula(form = y ~ ., data = df, method = "glm", family = binomial)

推荐阅读