R:如何正确创建rx_forest_model对象?

时间:2017-06-07 10:51:48

标签: sql-server r microsoft-r

我尝试使用R和SQL Server 2016进行流失分析。 我已将数据集上传到我的数据库中的本地SQL Server中,并完成了对此数据集的所有初步工作。 好吧,现在我有了这个函数trainModel(),我将用它来估计我的随机模型森林:

trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                                table = trainTable,
                                colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

return(rx_forest_model)
}

但是当我运行该函数时,我得到了错误的输出:

> system.time({
+   trainModel(sqlSettings, trainTable)
+ })
   user  system elapsed 
   0.29    0.07   58.18 
Warning message:
In tempGetNumObs(numObs) :
  Number of observations not available for this data source. 'numObs' set to 1e6.

对于此警告消息,函数trainModel()不会创建对象rx_forest_model

有没有人对如何解决这个问题有任何建议?

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我发现函数trainModel()无法正常运行的原因。 不是连接字符串问题,甚至不是数据源类型问题。 问题出在函数trainModel()的语法中。

足以从函数体中消除语句:

return(rx_forest_model)

通过这种方式,该函数返回相同的警告消息,但以正确的方式创建对象rx_forest_model

所以,正确的功能是:

trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString

trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
                            table = trainTable,
                            colInfo = cdrColInfo)

## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)

## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
                             data = trainDataSQL,
                             nTree = 8,
                             maxDepth = 16,
                             mTry = 2,
                             minBucket = 1,
                             replace = TRUE,
                             importance = TRUE,
                             seed = 8,
                             parms = list(loss = c(0, 4, 1, 0)))

}