99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀11個方法教你如何提升R語言代碼運算效率
11個方法教你如何提升R語言代碼運算效率
2016-10-09
收藏

11個方法教你如何提升R語言代碼運算效率

眾所周知,當我們利用R語言處理大型數(shù)據(jù)集時,for循環(huán)語句的運算效率非常低。有許多種方法可以提升你的代碼運算效率,但或許你更想了解運算效率能得到多大的提升。本文將介紹幾種適用于大數(shù)據(jù)領(lǐng)域的方法,包括簡單的邏輯調(diào)整設(shè)計、并行處理和Rcpp的運用,利用這些方法你可以輕松地處理1億行以上的數(shù)據(jù)集。

讓我們嘗試提升往數(shù)據(jù)框中添加一個新變量過程(該過程中包含循環(huán)和判斷語句)的運算效率。

下面的代碼輸出原始數(shù)據(jù)框:

  1. # Create the data frame
  2. col1 <- runif (12^5, 0, 2)
  3. col2 <- rnorm (12^5, 0, 2)
  4. col3 <- rpois (12^5, 3)
  5. col4 <- rchisq (12^5, 2)
  6. df <- data.frame (col1, col2, col3, col4)

逐行判斷該數(shù)據(jù)框(df)的總和是否大于4,如果該條件滿足,則對應(yīng)的新變量數(shù)值為’greaterthan4’,否則賦值為’lesserthan4’。

  1. # Original R code: Before vectorization and pre-allocation
  2. system.time({
  3. for (i in 1:nrow(df)) { # for every row
  4. if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) { # check if > 4
  5. df[i, 5] <- "greater_than_4" # assign 5th column
  6. } else {
  7. df[i, 5] <- "lesser_than_4" # assign 5th column
  8. }
  9. }
  10. })

本文中所有的計算都在配置了2.6Ghz處理器和8GB內(nèi)存的MAC OS X中運行。

1.向量化處理和預(yù)設(shè)數(shù)據(jù)庫結(jié)構(gòu)

循環(huán)運算前,記得預(yù)先設(shè)置好數(shù)據(jù)結(jié)構(gòu)和輸出變量的長度和類型,千萬別在循環(huán)過程中漸進性地增加數(shù)據(jù)長度。接下來,我們將探究向量化處理是如何提高處理數(shù)據(jù)的運算速度。

  1. # after vectorization and pre-allocation
  2. output <- character (nrow(df)) # initialize output vector
  3. system.time({
  4. for (i in 1:nrow(df)) {
  5. if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) {
  6. output[i] <- "greater_than_4"
  7. } else {
  8. output[i] <- "lesser_than_4"
  9. }
  10. }
  11. df$output})

2.將條件語句的判斷條件移至循環(huán)外

將條件判斷語句移至循環(huán)外可以提升代碼的運算速度,接下來本文將利用包含100,000行數(shù)據(jù)至1,000,000行數(shù)據(jù)的數(shù)據(jù)集進行測試:

  1. # after vectorization and pre-allocation, taking the condition checking outside the loop.
  2. output <- character (nrow(df))
  3. condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4  # condition check outside the loop
  4. system.time({
  5. for (i in 1:nrow(df)) {
  6. if (condition[i]) {
  7. output[i] <- "greater_than_4"
  8. } else {
  9. output[i] <- "lesser_than_4"
  10. }
  11. }
  12. df$output <- output
  13. })

3.只在條件語句為真時執(zhí)行循環(huán)過程

另一種優(yōu)化方法是預(yù)先將輸出變量賦值為條件語句不滿足時的取值,然后只在條件語句為真時執(zhí)行循環(huán)過程。此時,運算速度的提升程度取決于條件狀態(tài)中真值的比例。

本部分的測試將和case(2)部分進行比較,和預(yù)想的結(jié)果一致,該方法確實提升了運算效率。

  1. output <- c(rep("lesser_than_4", nrow(df)))
  2. condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  3. system.time({
  4. for (i in (1:nrow(df))[condition]) {  # run loop only for true conditions
  5. if (condition[i]) {
  6. output[i] <- "greater_than_4"
  7. }
  8. }
  9. df$output
  10. })

4.盡可能地使用 ifelse()語句

利用ifelse()語句可以使你的代碼更加簡便。ifelse()的句法格式類似于if()函數(shù),但其運算速度卻有了巨大的提升。即使是在沒有預(yù)設(shè)數(shù)據(jù)結(jié)構(gòu)且沒有簡化條件語句的情況下,其運算效率仍高于上述的兩種方法。

  1. system.time({
  2. output <- ifelse ((df$col1 + df$col2 + df$col3 + df$col4) > 4, "greater_than_4", "lesser_than_4")
  3. df$output <- output
  4. })

5.使用 which()語句

利用which()語句來篩選數(shù)據(jù)集,我們可以達到Rcpp三分之一的運算速率。

  1. # Thanks to Gabe Becker
  2. system.time({
  3. want = which(rowSums(df) > 4)
  4. output = rep("less than 4", times = nrow(df))
  5. output[want] = "greater than 4"
  6. })
  7. # nrow = 3 Million rows (approx)
  8. user  system elapsed
  9. 0.396   0.074   0.481

6.利用apply族函數(shù)來替代for循環(huán)語句

本部分將利用apply()函數(shù)來計算上文所提到的案例,并將其與向量化的循環(huán)語句進行對比。該方法的運算效率優(yōu)于原始方法,但劣于ifelse()和將條件語句置于循環(huán)外端的方法。該方法非常有用,但是當你面對復(fù)雜的情形時,你需要靈活運用該函數(shù)。

  1. # apply family
  2. system.time({
  3. myfunc <- function(x) {
  4. if ((x['col1'] + x['col2'] + x['col3'] + x['col4']) > 4) {
  5. "greater_than_4"
  6. } else {
  7. "lesser_than_4"
  8. }
  9. }
  10. output <- apply(df[, c(1:4)], 1, FUN=myfunc)  # apply 'myfunc' on every row
  11. df$output <- output
  12. })

7.利用compiler包中的字節(jié)碼編譯函數(shù)cmpfun()

這可能不是說明字節(jié)碼編譯有效性的最好例子,但是對于更復(fù)雜的函數(shù)而言,字節(jié)碼編譯將會表現(xiàn)地十分優(yōu)異,因此我們應(yīng)當了解下該函數(shù)。

  1. # byte code compilation
  2. library(compiler)
  3. myFuncCmp <- cmpfun(myfunc)
  4. system.time({
  5. output <- apply(df[, c (1:4)], 1, FUN=myFuncCmp)
  6. })

8.利用Rcpp

截至目前,我們已經(jīng)測試了好幾種提升運算效率的方法,其中最佳的方法是利用ifelse()函數(shù)。如果我們將數(shù)據(jù)量增大十倍,運算效率將會變成啥樣的呢?接下來我們將利用Rcpp來實現(xiàn)該運算過程,并將其與ifelse()進行比較。

  1. library(Rcpp)
  2. sourceCpp("MyFunc.cpp")
  3. system.time (output <- myFunc(df)) # see Rcpp function below

下面是利用C++語言編寫的函數(shù)代碼,將其保存為“MyFunc.cpp”并利用sourceCpp進行調(diào)用。

  1. // Source for MyFunc.cpp
  2. #include 
  3. using namespace Rcpp;
  4. // [[Rcpp::export]]
  5. CharacterVector myFunc(DataFrame x) {
  6. NumericVector col1 = as(x["col1"]);
  7. NumericVector col2 = as(x["col2"]);
  8. NumericVector col3 = as(x["col3"]);
  9. NumericVector col4 = as(x["col4"]);
  10. int n = col1.size();
  11. CharacterVector out(n);
  12. for (int i=0; i 4){
  13. out[i] = "greater_than_4";
  14. } else {
  15. out[i] = "lesser_than_4";
  16. }
  17. }
  18. return out;
  19. }

9.利用并行運算

并行運算的代碼:

  1. # parallel processing
  2. library(foreach)
  3. library(doSNOW)
  4. cl <- makeCluster(4, type="SOCK") # for 4 cores machine
  5. registerDoSNOW (cl)
  6. condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
  7. # parallelization with vectorization
  8. system.time({
  9. output <- foreach(i = 1:nrow(df), .combine=c) %dopar% {
  10. if (condition[i]) {
  11. return("greater_than_4")
  12. } else {
  13. return("lesser_than_4")
  14. }
  15. }
  16. })
  17. df$output <- output

10.盡早地移除變量并恢復(fù)內(nèi)存容量

在進行冗長的循環(huán)計算前,盡早地將不需要的變量移除掉。在每次循環(huán)迭代運算結(jié)束時利用gc()函數(shù)恢復(fù)內(nèi)存也可以提升運算速率。

11.利用內(nèi)存較小的數(shù)據(jù)結(jié)構(gòu)

data.table()是一個很好的例子,因為它可以減少數(shù)據(jù)的內(nèi)存,這有助于加快運算速率。

  1. dt <- data.table(df)  # create the data.table
  2. system.time({
  3. for (i in 1:nrow (dt)) {
  4. if ((dt[i, col1] + dt[i, col2] + dt[i, col3] + dt[i, col4]) > 4) {
  5. dt[i, col5:="greater_than_4"]  # assign the output as 5th column
  6. } else {
  7. dt[i, col5:="lesser_than_4"]  # assign the output as 5th column
  8. }
  9. }
  10. })

總結(jié)

方法:速度, nrow(df)/time_taken = n 行每秒

1.原始方法:1X, 856.2255行每秒(正則化為1)

2.向量化方法:738X, 631578行每秒

3.只考慮真值情況:1002X,857142.9行每秒

4.ifelse:1752X,1500000行每秒

5.which:8806X,7540364行每秒

6.Rcpp:13476X,11538462行每秒


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }