効果を測る

R による並列プログラミング

Nabeel Imam

Data Scientist

おもちゃ例

numbers <- 1:1000000


# 逐次 sqroots <- lapply(numbers, sqrt)
# 並列 cl <- makeCluster(4) sqroots <- parLapply(cl, numbers, sqrt) stopCluster(my_cluster)

どちらが速いでしょうか?

R による並列プログラミング

性能のベンチマーク

平均実行時間を推定するため複数回実行します

library(microbenchmark)


microbenchmark( "Sequential" = lapply(numbers, sqrt),
"Parallel" = { cl <- makeCluster(4) parLapply(cl, numbers, sqrt) stopCluster(my_cluster) },
times = 10 )

 

 

Unit: milliseconds
      expr     min    mean     max neval
Sequential  633.96  838.09  993.59    10
  Parallel 1136.95 1247.29 1557.58    10
  • 単純な数値演算は並列化の恩恵が小さいことが多い
  • プロファイリングは行単位、ベンチマークは全体の実行時間を報告
R による並列プログラミング

言いにくい真実

sqroots <- sqrt(numbers)

居間のソファにゾウが座っていて、人々がその存在に気づいている。

R による並列プログラミング

ベクトル化

sqroots <- sqrt(numbers)
  • sqrt() のようなBase R関数はベクトル化されています。
  • 1つの関数を多くの入力に適用
  • 非常に高速だが単純な処理に限定
microbenchmark(
  "Vectorized" = sqrt(numbers),
  "Sequential" = lapply(numbers, sqrt),
  "Parallel" = {
    cl <- makeCluster(4)
    parLapply(cl, numbers, sqrt)
    stopCluster(my_cluster)
  },
  times = 10)
Unit: milliseconds
      expr       min      mean      max neval
Vectorized    2.3904    9.2071   66.303    10
Sequential  352.1166  771.7491 1004.753    10
  Parallel 1191.3176 1377.6926 1700.316    10
R による並列プログラミング

ブートストラップ

現在のデータから復元抽出でサンプリング

print(ls_df)
$`2001`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.3  2001
 2 Albania                        74.3  2001
 3 Algeria                        71.1  2001
...
$`2002`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.8  2002
 2 Albania                        74.6  2002
 3 Algeria                        71.6  2002
...
R による並列プログラミング

古典的な方法

df <- ls_df$`2001`


estimates <- rep(0, 10000)
for (i in 1:10000) { b <- sample(df$Life_expectancy, replace = T)
estimates[i] <- mean(b) }

2001年の世界平均寿命のブートストラップ推定のヒストグラム。典型的な釣鐘型の分布。

  • 分位点による信頼区間: quantile(estimates, c(0.025, 0.975))
R による並列プログラミング

朗報

ブートストラップは並列化可能です

estimates <- rep(0, 10000)

for (i in 1:10000) {

  b <- sample(df$Life_expectancy,
              replace = T)

  estimates[i] <- mean(b)
  }
boot_dist <- function (df) {

  estimates <- rep(0, 10000)

  for (i in 1:10000) {
    b <- sample(df$Life_expectancy, replace = T)
    estimates[i] <- mean(b)
  }

  return(estimates)
}


cl <- makeCluster(4) ls_dists <- parLapply(cl, ls_df, boot_dist) stopCluster(cl)
R による並列プログラミング

利点

microbenchmark(
  "lapply" = lapply(ls_df, boot_dist),
  "parLapply" = {
    cl <- makeCluster(4)
    parLapply(cl, ls_df, boot_dist)
    stopCluster(cl)
  },
  times = 10
)
Unit: seconds
     expr    min   mean    max neval
   lapply 3.6938 4.2184 4.5267    10
parLapply 1.9006 2.5166 2.7292    10

到達手順:

  • 既存コードをプロファイルし最遅部分を特定
  • その部分を並列化/最適化
  • ベンチマークして比較
R による並列プログラミング

Passons à la pratique !

R による並列プログラミング

Preparing Video For Download...