[SQL Server][R Language]資料科學用戶端(四)遠端分佈運算Distributed Computing In SQL 2016

當我們在執行大量資料分析時,資料科學用戶端的本機記憶體及CPU運算能力可能會不足,另外如果也希望資料庫的資料不要走出家門太久,這時候就可以考慮在遠端的SQL Server上執行分佈運算Distributed Computing。

 

在RevoScaleR套件中支援分佈運算的函式有以下:

  • rxSummary
  • rxLinMod
  • rxLogit
  • rxGlm
  • rxCovCor (and its convenience functions, rxCov, rxCor, and rxSSCP)
  • rxCube and rxCrossTabs
  • rxKmeans
  • rxDTree
  • rxDForest
  • rxBTrees
  • rxNaiveBayes
  • rxExec

 

ScaleR的分佈運算的關鍵就是和遠端伺服器建立運算熱線Compute ContextsMSDN文章中指出共有4種分類,每一種都有其支援的特定資料來源:

  • RxLocalSeq(預設)     
  • RxHadoopMR  
  • RxInTeraData   
  • RxInSqlServer(只能在一個資料庫節點執行,只能使用RxSqlServerData Type)

https://msdn.microsoft.com/en-us/microsoft-r/scaler-distributed-computing

 

因為我們主要還是以本機和SQL Server作資料分析,先練習RxLocalSeq及RxInSqlServer(R Service)這2種Compute Contexts。

但測試前,要先準備RDB的資料庫(版本為SQL Server 2016 EE),並將信用卡詐欺交易資料表ccFraudSmall建立好1萬筆範例資料,可以參考之前這篇完成前置準備

 

1.建立一個R的函式

FnLogitRx2 <- function() {
    #設定連線字串
    sqlConnString <- "driver={SQL Server};server=IP;database=RDB;uid={帳號};pwd={密碼}"
    #取得Microsoft R 所含的範例資料(信用卡詐欺交易資料)
    FraudDF <- RxSqlServerData(sqlQuery = "select * from ccFraudSmall", connectionString = sqlConnString)
    #回傳模型
    return(summary(rxLogit(fraudRisk ~ state + gender + cardholder + balance + numTrans + numIntlTrans + creditLine, data = FraudDF)))
}

 

2.執行本機運算

#----------------------------------------------------------- 
#(A)執行本機運算 local computing
#----------------------------------------------------------- 
rxOptions(numCoresToUse = 1)
rxSetComputeContext("local")
st <- Sys.time();
sqlServerExecLocal <- rxExec(FnLogitRx2)
ed <- Sys.time();
#計算執行時間
timelocal <- ed - st
timelocal

 

3.準備分佈運算連線參數

#----------------------------------------------------------- 
#準備ComputeContext參數
#----------------------------------------------------------- 
#是否等待回傳
sqlWait <- TRUE
#結果寫到Console
sqlConsoleOutput <- FALSE
sqlConnString <- "driver={SQL Server};server=IP;database=RDB;uid={帳號};pwd={密碼}"
#注意參數區分大小寫(先關閉trace)
DistributedCompute <- RxInSqlServer(connectionString = sqlConnString, wait = sqlWait, consoleOutput = sqlConsoleOutput,
    traceEnabled = FALSE, traceLevel = 7)

 

4.執行分佈運算      

#----------------------------------------------------------- 
#(B)執行分佈運算 distributed computing
#----------------------------------------------------------- 
rxOptions(numCoresToUse = 4)
rxSetComputeContext("DistributedCompute")
st <- Sys.time();
sqlServerExecDist <- rxExec(FnLogitRx2)
ed <- Sys.time();
#計算執行時間
timeDisb <- ed - st
timeDisb

#比較時間
cbind(timelocal, timeDisb)

 

 

本機運算9秒,分佈運算3秒,雖然分佈運算如預期的比本機快,但兩者都比預期(2秒內)來的慢! 上一篇的測試結果是取得1萬筆訓練資料約1.5秒,訓練出模型約0.2秒。

這篇先筆記在SQL Server執行分佈運算的作法,效能問題再另案調查。

 

 

參考:

Getting Started with SQL Server R Services

Free eBooks from Microsoft Press

mva學院推薦 Data Science with Microsoft SQL Server 2016