自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

提升R代碼運(yùn)算效率的11個(gè)實(shí)用方法

大數(shù)據(jù)
R 是一款優(yōu)秀的開源統(tǒng)計(jì)應(yīng)用語(yǔ)言,它直觀、易用、低成本,而且還有龐大的社區(qū)支持。但是當(dāng)我們利用R語(yǔ)言處理大型數(shù)據(jù)集時(shí),for循環(huán)語(yǔ)句的運(yùn)算效率總是非常低。本文將介紹幾種方法,幫助你以輕松地處理1億行以上的數(shù)據(jù)集。

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

[[162790]]

讓我們嘗試提升往數(shù)據(jù)框中添加一個(gè)新變量過程(該過程中包含循環(huán)和判斷語(yǔ)句)的運(yùn)算效率。下面的代碼輸出原始數(shù)據(jù)框:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5.使用 which()語(yǔ)句

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

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

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

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

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

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

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

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

8.利用Rcpp

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

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

下面是利用C++語(yǔ)言編寫的函數(shù)代碼,將其保存為“MyFunc.cpp”并利用sourceCpp進(jìn)行調(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. return out; 

9.利用并行運(yùn)算

并行運(yùn)算的代碼:

# parallel processing
library(foreach)
library(doSNOW)
cl <- makeCluster(4, type="SOCK") # for 4 cores machine
registerDoSNOW (cl)
condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
# parallelization with vectorization
system.time({
output <- foreach(i = 1:nrow(df), .combine=c) %dopar% {
if (condition[i]) {
return("greater_than_4")
} else {
return("lesser_than_4")
}
}
})
df$output <- output

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

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

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

data.table()是一個(gè)很好的例子,因?yàn)樗梢詼p少數(shù)據(jù)的內(nèi)存,這有助于加快運(yùn)算速率。

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

總結(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行每秒

責(zé)任編輯:Ophira 來源: 數(shù)據(jù)工匠
相關(guān)推薦

2024-09-24 16:00:00

Python腳本代碼

2025-03-03 00:15:00

JavaScript開發(fā)效率

2024-09-26 06:21:59

Python代碼

2020-07-28 09:30:12

開發(fā)技能代碼

2022-06-01 10:45:52

C語(yǔ)言代碼優(yōu)化

2024-10-15 10:11:04

2025-03-04 13:00:00

JavaScrip代碼語(yǔ)言

2024-02-04 13:36:00

2024-09-19 16:12:04

2024-10-09 12:18:38

2021-11-03 06:28:21

Python運(yùn)行速度開發(fā)

2022-04-29 08:15:40

Python技巧Max

2025-01-10 08:38:16

2024-03-06 09:05:02

KubernetesReadyNode

2020-04-20 17:43:28

Java代碼優(yōu)化開發(fā)

2020-07-08 17:06:00

Python開發(fā)工具

2022-05-27 08:40:27

java工具

2019-11-05 14:37:24

Java性能優(yōu)化編程語(yǔ)言

2014-02-04 19:48:07

重構(gòu)代碼質(zhì)量

2022-09-23 08:00:00

開發(fā)安全低代碼平臺(tái)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)