미래를 매핑하기

R의 병렬 프로그래밍

Nabeel Imam

Data Scientist

future 익히기

report <- "<important report text>"

task_future <- future({
  print("Hi, please find attached the report.")
  report
})
R의 병렬 프로그래밍

purrr로 매핑하기

library(purrr)


numbers <- 1:1000000 map(numbers, sqrt)
[[1]]
[1] 1

[[2]]
[1] 1.414214

[[3]]
[1] 1.732051

[[4]]
[1] 2
...
R의 병렬 프로그래밍

map의 변형

map_dbl(numbers, sqrt)
 [1]  1.000000  1.414214  1.732051 
 [4]  2.000000  2.236068  2.449490
 [7]  2.645751  2.828427  3.000000  
[10]  3.162278  3.316625  3.464102
[13]  3.605551  3.741657  3.872983
  ...
  • map + "_dbl" 접미사
    • 출력이 더블/소수일 때

 

  • 결과는 벡터로 반환
R의 병렬 프로그래밍

map의 변형

map_chr(numbers, sqrt)
 [1] "1.000000"  "1.414214"  "1.732051"
 [4] "2.000000"  "2.236068"  "2.449490"
 [7] "2.645751"  "2.828427"  "3.000000"
[10] "3.162278"  "3.316625"  "3.464102"
[13] "3.605551"  "3.741657"  "3.872983"
  ...
  • map + "_chr" 접미사
    • 출력이 문자일 때

 

  • 문자 벡터
R의 병렬 프로그래밍

map의 변형

함수

  • map()
  • map_chr()
  • map_dbl()
  • map_int()
  • map_lgl()

출력 형식

  • 벡터·데이터 프레임 등의 리스트
  • 문자(단일 값)
  • 더블/소수(단일 값)
  • 정수(단일 값)
  • 논리값(단일 값)
R의 병렬 프로그래밍

타입 지정

microbenchmark(
  "map" = map(numbers, sqrt),
  "map_dbl" = map_dbl(numbers, sqrt),
  "map_chr" = map_chr(numbers, sqrt),
  times = 10
)
Unit: milliseconds
     expr     min    mean     max neval
1     map  794.20 1254.46 1904.02    10
2 map_dbl  889.33 1067.41 1496.56    10
3 map_chr 1735.96 1934.97 2269.59    10
R의 병렬 프로그래밍

future + purrr = furrr

purrr

순차 실행

library(purrr)
map_dbl(1:1000000, sqrt)

furrr

순차 실행

library(furrr)
future_map_dbl(1:1000000, sqrt)
R의 병렬 프로그래밍

병렬로 사용하는 furrr

n_cores <- detectCore() - 2


plan(multisession, workers = n_cores)
future_map_dbl(1:1000000, sqrt) # Future enabled map_dbl()
plan(sequential)
   [1]  1.000000  1.414214  1.732051  2.000000  2.236068  2.449490  2.645751
   [8]  2.828427  3.000000  3.162278  3.316625  3.464102  3.605551  3.741657
  [15]  3.872983  4.000000  4.123106  4.242641  4.358899  4.472136  4.582576
R의 병렬 프로그래밍

future_map 패밀리

purrr 함수

  • map()
  • map_chr()
  • map_dbl()
  • map_int()
  • map_lgl()

future 지원 furrr 함수

  • future_map()
  • future_map_chr()
  • future_map_dbl()
  • future_map_int()
  • future_map_lgl()
R의 병렬 프로그래밍

furrr의 이점

  • 입력 input_list와 매핑할 함수 calculate()가 있을 때:
future_list <- lapply(input_list, function (x) future(calculate(x)))

result_list <- value(future_list) # 숫자형 벡터로 가공
library(furrr)

# 숫자형 벡터가 필요하므로 future_map_dbl() 사용
result_list <- future_map_dbl(input_list, calculate)
R의 병렬 프로그래밍

연습해 봅시다!

R의 병렬 프로그래밍

Preparing Video For Download...