intro to r & hadoop

50
© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted C03934969, January 2014 Introduction to R and Hadoop HP ES Korea 이이이

Upload: seong-bok-lee

Post on 17-Aug-2015

101 views

Category:

Technology


7 download

TRANSCRIPT

Page 1: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted

C03934969, January 2014

Introduction to R and Hadoop HP ES Korea이성복

Page 2: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted2

내용

빅데이터 분석을 위해 필요한 기술

R 을 알아보자

빅데이터 분석을 위해 R 과 Hadoop 을 어떻게…

R + Hadoop = RHadoop?

Page 3: Intro to r & hadoop

빅데이터 분석을 위해 필요한 기술

Page 4: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted4

빅데이터 분석을 위해 필요한 기술1. 빅 데이터 처리를 위한 분산처리 기술

2. 사용자 편이성이 극도로 향상된 dynamic visualization 소프트웨어

3. 통계분석엔진에 의한 분석 자동화

이 세 가지 기술에 접목할 수 있는 데이터 과학자들의 도구로 급 부상하고 있는 것이 바로 R 이다 .

Page 5: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted5

1.빅데이터 처리를 위한 분산처리 기술상상을 초월하는 규모와 구조화되어 있지 않은 데이터 분석을 위한 오픈소스 플랫폼인 하둡 (Hadoop) 은 페이스북 , 아마존 , 야후 , 트위터 등이 사용하며 각광을 받고 있다 . 또한 R 은 하둡 스트리밍 기술을 활용하여 분산 처리에 기반한 데이터 분석 엔진으로 활용되고 있다 . 특히 패키지 RHIPE(R and Hadoop Integrated Processing Environment) 가 소개되며 R 은 하둡에서 통계분석을 위한 엔진으로 자리 잡게 되었다 .

Page 6: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted6

2. dynamic visualization 소프트웨어빅데이터 시대에는 정보의 양이 워낙 많아 분석결과를 직관적으로 이해할 수 있는 환경이나 적절한 소프트웨어가 요구되고 있다 .

그러한 맥락에서 이차원 평면 상에서도 데이터의 다차원 구조를 이해할 수 있는 다이나믹 그래프 혹은 필터링 조건에 의해 데이터를 분석하는 데이터 시각화가 중요시되고 있다 .

그 원조는 구글의 Google Visualization Chart API 로 R에서 구글과 통신을 위한 몇가지 API 관련 패키지 설치 후 누구나 활용이 가능하다 . 그 외에 Spotfire, Qlik View 등의 상업용 자료 시각화 프로그램과 R 의 연동을 통해 고급분석이 가능하다 .

Page 7: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted7

3. 통계분석엔진에 의한 분석 자동화빅 데이터의 실시간 분석을 위해 기존에 생산되는 데이터를 데이터베이스에 기록하여 축적하는 소위 data-in-rest 방식뿐 아니라 , 관심있는 정보를 이벤트로 정의하여 데이터베이스 기록 전에 분석이나 의사결정에 활용하는 event-captured 혹은 data-in-motion 형태의 데이터를 분석하는 기술이 부상하고 있다 .

아울러 더욱 빠른 분석을 위해 메모리나 데이터베이스에서 직접 분석을 실시하는 in-memory 혹은 in-databse analytics 를 통해 고성능 컴퓨팅 (High Performance Computing, HPC) 이 새로운 트렌드

R 은 태생 자체가 HPC 에 상당히 유리한 아키텍처로 IBM, 테라데이터 등 빅 데이터에서의 고성능 분석을 추구하는 IT 업체들이 속속 R 을 분석 플랫폼을 채택하고 있다 . 고성능 컴퓨팅 기술과 시스템 상의 데이터 분석 엔진을 장착하여 빅 데이터의 분석 자동화가 이루어지고 있으며 , 대표적인 예로는 구글의 Google Prediction API 가 있다 . 이는 예측모형을 만들고 싶은 분석 데이터를 구글 서비스에 보낸 후 예측 모델을 자동으로 수행해 주는 서비스로 이 역시 R 에 필요한 패키지 설치 후 간단히 사용할 수 있다 .

Page 8: Intro to r & hadoop

R 을 알아보자

Page 9: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted9

R 이란 ?“R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by JohnChambers and colleagues. R can be considered as a different implementation of S. There are some important differences, but much code written for S runs unaltered under R.”

(http://www.r-project.org/about.html)

R 은 데이터 분석을 위한 통계와 그래픽스를 지원하는 오픈 소프트웨어 환경이다 .

데이터 분석을 위한 소프트웨어 프로그래밍 언어

통계학자들이 디자인한 , 통계학자들을 위한 개발 플랫폼

개발 환경 (Environment) 제공 데이터와 관련된 입출력 , 처리 , 관리 , 분석 ,

그래프 등 최신의 알고리즘과 라이브러리 제공

오픈소스 소프트웨어 프로젝트 Free, open, active

커뮤니티 수 천명의 기여자들 , 2 백만이 넘는 사용자들 각 업무 도메인과 관련된 리소스와 도움말 제공

Page 10: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted10

R 의 주 사용처Statistical Analysis & Modeling

• Classification

• Scoring

• Ranking

• Clustering

• Finding relationships

• Characterization

Common Uses• Interactive Data Analysis

• General Purpose Statistics

• Predictive Modeling

Page 11: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted11

지금 R 은… R 에 대한 관심의 증가

폭발적인 사용자 증가와 개발자의 확산으로 , 대학교육의 표준 툴로 자리 잡음

기업체에서의 R 의 활용 빅 데이터 기업의 분석 플랫폼 엔진으로 사용 중이며 , 유수기업에서 데이터 분석 tool 로 사용

중임 특히 , Google 과 Facebook 은 R 을 자사의 주된 분석 플랫폼으로 활용하고 있음

소프트웨어 Vendor 의 R 적용 Oracle, IBM 의 Netezza, SAP 의 HANA, Teradata 등에서 in-memory 혹은 in-database

분석 엔진으로 R 을 적용함

통계 소프트웨어 Vendor 의 R 적용 SAS 나 SPSS 등의 통계 소프트웨어에서 R 과의 연동을 통해 새로운 분석 방법을 제공

Page 12: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted12

R 의 특징 (1/2) 통계적 처리 , 데이터 시각화 , 데이터 분석을 위한 소프트웨어 프로그래밍 언어 In-Memory Computing

빠른 처리 속도 , H/W 메모리 크기에 영향을 받음

Object-oriented programming 데이터 , 함수가 object 로 관리되어 짐 : 클래스 (class) & 메소드 (method)

다양한 Package 최신의 알고리즘 및 방법론을 적용한 확장 팩 프로그래밍이 간단해 짐 다양한 함수 및 데이터 내장 , Help 의 Examples 바로 사용 가능

Visualization 분석에 통찰을 부여할 수 있는 그래픽에 대한 강력한 지원 Chart, Plot, MotionChart, Map 연계 등을 R 에서 바로 사용 가능

통계계산 최적화 사례 - 회귀분석 “행렬 /벡터 데이터 타입 지원”과“행렬 연산 지원”으로“복잡한 구조의 반복문 제거”“ 코드를 이해하가 쉬움”

Page 13: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted13

R 의 특징 (2/2) 시스템 통합의 용이성 : Application 이나 Platform 을 구축할 경우 분석 영역의 솔루션으로 R 을 사용하는 것이

용이하다• Language Interface : C, C++, FORTRAN, JAVA, Python, Tcl/tk, VB,Perl, Ruby • Application Interface : Excel, Google earth, ArcView, COM/DCOM, etc• DB Interface : ODBC (Oracle, Mysql, MS-SQL, PostgreSql, ...)• IDE : Rstudio, eclipse, emacs, Bluefish, Crimson Editor, ConTEXT, Vim, Jedit, Kate, TextMate, gedit,

SciTE, WinEdt

자료구조 _ 통계계산에 최적화 : 통계분석에 최적화된 자료구조 - matrix, vector 등• Data Objects• Vector : 벡터 연산을 위한 구조• Factor : 범주형 자료• Ordered factor : 순서 범주형 자료• Matrix : 행렬 연산을 위한 행렬

Like UNIX Command • “Bell Lab 시절 S Language 가 UNIX 의 특성을 많이 가져 옴 Command line interpreter(CLI)

Graphics : 다양한 그래프를 사용자가 세세하게 조정하여 그릴 수 있음• Graphics Devices : bmp, jpeg, png, tiff, pdf, postscript, SVG(R 2.14)• other Support : OpenGL, Spatial(Archview, googleMap) ,… • Low level Plot : points, lines, box, rect, polygon , text, title, mtext ,legend, axis, grid • High level Plot : plot, barplot, boxplot, pie, qqplot, … / trellis(lattice packages), rgl, sna, wordcloud, …

• List : 리스트 객체 , C 의 구조체와 유사• Data Frame : 다변량 데이터 구조 , DBMS 의 Table 과 유사한 구조• Array : 배열 연산을 위한 구조• Time Series : 시계열 데이터 분석을 위한 구조• Vectorize 연산 :Loop 문을 피하고 행렬이나 벡터 연산으로 계산 apply, lappy,

tapply, outer,

Page 14: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted14

R 의 장점 In-Memory 구조 연산수행 속도가 매우 빠름 대화식 프로그래밍 수행 대용량 데이터의 관리 , 처리 , 연산에 적합 ( 단 , 10GB 급 이상으로 넘어가면 성능 문제 발생 )

전세계 연구자의 개발 알고리즘 , 함수 활용 가능 패키지 형태로 제공 객체 지향 확장성 짱 무료 통계 패키지 저렴한 비용으로 구축 가능 성능 그래픽 기능 다양한 플랫폼 지원

Page 15: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted15

R 의 역사

• R 은 1993년 뉴질랜드 오클랜드대학의 통계학과 교수 2 명 (Ross Ihaka, Robert Gentleman) 에 의하여 개발

• 1976년 Bell Lab 의 John Chambers, Rick Becker, Allan Wilks 에 의하여 개발된 S Language 에 그 뿌리를 두고 있음

1976 1980 1988 1998

Version 4 Java

interface Class/Metho

d

Version 3

C-baseClass/

Method

Version 2 UNIX

Version 1 Fortran- based

1988 1993 2001 2008

StacSci InsightfulWith

MathSoft E-license

05/V.7/Big data 07/V.8/R package

TIBCO

1993 1997.4.1

1997.4.23 2000.11997.12.5

CRANMailing ListVersion

1.0GNU

ProjectRoss Ihaka

Robert Gentleman

Version 3.2.1

2015.6.18

John Chamber

Page 16: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted16

[참고 ] R 의 역사 – OS 와 System 관점

O/S

Analysis System

UNIX

The S system

태동 확산 전파

Bell Lab

BSD/System VHP, IBM, SUN

S-PLUS

Commercial

LINUXApplication

RPackages

GNU/Open Source

1976년 Bell Lab 태생 1988년 라이센스 양도 1993년도 오픈소스화

Page 17: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted17

R 의 철학R = Free Software = 무료 < 자유로움누구나 자유롭게 " 실행 , 복사 , 수정 , 배포 " 할 수 있고 , 누구도 그런 권리 를 제한하면 안 된다는 사용허가권 (License) 아래 소프트웨어를 배포

Richard Stallman

GNU

※ GNU(' 그누 ' 로 발음 ) 는 GNU 프로젝트를 통하여 개발한 유닉스 계열 컴퓨터 운영 체제이며 궁극적으로는 "완전한 유닉스 호환 소프트웨어 시스템 " 이 되는 것이 목표이다 .( 리처드 스톨만이 1983년에 GNU 개발을 처음 시작 )

분석의 자유 생각하는 분석 기법은 모두 지원한다 . (4,000 여 개 이상의 패키지 ) 최신 분석 기법의 제공 및 자유로운 분석 환경 제공

배포의 자유 자유로운 " 실행 , 복사 , 수정 , 배포"의 권리를 갖는 사용 허가권

비용의 자유 무료 소프트웨어 ( 단 , 소프트웨어 업체의 R 을 이용한 저작물은 비용 발생 가

능 )

Page 18: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted18

R Packages R 의 기능을 보완하는 확장 팩으로 ,

라이브러리 형태로 제공

이러한 패키지들은 새로운 통계분석 알고리즘이나 새로운 IT 기술의 응용에 관한 것을 포함

Software Vendor 에 의하여 Version Up이 되지 않는다는 것이 다른 통계분석 소프트웨어와의 차이임

CRAN Site 에 6,819 개 등록됨 (2015년 6 월 30일 기준 ) http://cran.r-project.org/web/packages/

Page 19: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted19

[참고 ] dplyr 패키지

dplyr 패키지는 Hadley Wickham 가 작성한 데이터 처리에 특화된 R 패키지입니다 . 이 분이 지금까지 작성한 유명한 R 패키지로는 ggplot2, plyr, reshape2 등이 있음 .

데이터 처리에 특화된 유용한 패키지로는 역시 Hadley Wickham 이 만든 plyr 이라는 패키지가 있었습니다 . 그러나 plyr 은 편리하긴 했지만 모든 함수가 R 로 작성되어서 처리 속도가 느리다는 단점이 있었습니다 .

이에 반해 dplyr 은 C++ 로 작성되어 불필요한 함수를 불러오지 않기 때문에 매우 빠른 처리 속도를 자랑합니다 .

dplyr 패키지는 데이터 프레임을 처리하는 함수군으로 구성되어 있습니다 .

그 밖에도 다음 형식의 데이터를 이용할 수 있습니다 .

data.table : data.table 패키지와 사용 각종 데이터베이스 : 현재 MySQL, PostgreSQL, SQLite, BigQuery 를 지원 데이터 큐브 : dplyr 패키지 내부에 실험적으로 내장됨

Page 20: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted20

CRAN (The Comprehensive R Archive Network)

R 프로그램과 패키지 등을 다운로드 받거나 패키지를 제출할 수 있는 mirror site

R 은 CRAN Site 를 통하여 자유롭게 다운로드 받아 설치할 수 있음 현재 48 개국에 98 개의 Mirror 사이트 운영 중

http://cran.r-project.org/

Korea :http://cran.nexr.com/

미러 사이트 (mirror site) : • 네트워크 트래픽을 줄이기 위하여 다른 컴퓨터 서버를

복사해 놓은 웹사이트 또는 컴퓨터 파일서버• FTP 서버로부터 다운로드 될 수 있는 파일들에 대해서도 미러파일을 만들 수 있음

Page 21: Intro to r & hadoop

빅데이터 분석을 위해 R 과 Hadoop 을 어떻게…

Page 22: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted22

Why Hadoop for Big Data Analysis? Hadoop has become the kernel of the distributed operating system for Big Data

대부분의 데이터 처리는 데이터 분석을 위한 기반 작업 이미 많은 업체에서 Hadoop 을 데이터 분석 및 처리 용도로 활용중 역시 Hadoop 이외의 다른 대안은 거의 없음

Page 23: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted23

빅데이터 분석에서 R 의 문제점메모리 한계 이슈

1) 모든 데이터를 메모리에 로딩 후 처리하는 작업 방식• ff, bigmemory, RevoScaleR

• GB 급 데이터 처리 가능 . 10GB 이상 데이터는 처리 가능하나 너무 느리다는 단점

2) 불필요한 데이터 저장으로 인한 메모리 부족 현상• gc(), rm()

3) 32 비트에서 표현 가능한 숫자만이 사용 , 2^31-1• R 2.15 부터 2^51 이상의 벡터 길이 사용 가능

4) No int64*• int64 package from Google

5) 메모리 단편화• 64bit 머신 사용

• 더 많은 메모리

Single Core 이슈

1) 멀티코어 CPU 에서 1코어만 사용한다 .

2) R 2.14 부터 parallel 패키지 기본 탑재

※ int64 = 64-bit integers

Page 24: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted24

Why R and Hadoop?R 은 빅데이터 처리 능력이 필요하며 , Hadoop 은 고급 분석 능력이 필요

Hadoop - a scalable infrastructure for processing massive amounts of data• Storage – HDFS, HBASE• Distributed Computing - MapReduce

R - a statistical programming languageNeed for more than counts and averagesAnalyze all of the data

Make it easy for the R programmer to interact with the Hadoop data stores and write MapReduce programs

Run R on a massively distributed system without having to understand the underlying infrastructure

Statisticians stay focused on the analysis Open source

Page 25: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted25

빅데이터 분석을 위해 필요한 요소 ?

• SAS, SPSS 의 대안

• 오픈 소스 , 최신 기술 적용

Hadoop

RR +

Hadoop

• 대용량 데이터를 위한 파일 시스템

• 분산 컴퓨팅 프레임워크

• 검증된 기술

• R 의 분석능력과 Visualization 능력

• Hadoop 의 대용량 데이터 처리 능력

Page 26: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted26

R 과 Hadoop 을 엮는 5 가지 방법1. RHadoop – RHadoop is a great open source solution for R and Hadoop provided by

Revolution Analytics. RHadoop is bundled with four main R packages to manage and analyze the data with Hadoop framework.

2. RHIPE – RHIPE is the R and Hadoop Integrated Programming Environment specially designed with Divide and Recombine (D&R) techniques to analyze the large datasets.

3. ORCH – ORCH is Oracle R connector for Hadoop. ORCH can be used on the Oracle Big Data Appliance or on non-Oracle Hadoop clusters.

4. HadoopStreaming – Hadoopstreaming utilities as R scripts which is R packages available at CRAN. This R package is developed by David S. Rosenberg with the consideration of making this Hadoop Streaming more easy as possible for R users.

5. Hadoop Streaming – Hadoop Streamingis Hadoop utility which allows users to develop and run MapReduce program in language other than java. Hadoop Streaming is a utility which allows users to create and run jobs with any executables (e.g. shell utilities) as the mapper and/or the reducer.

Page 27: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted27

[참고 ] RHIPE 에 대해 좀 더…Rhipe : R and Hadoop Integrated Programming Environment

R 과 Hadoop 을 연동하여 MapReduce 기능을 R콘솔에서 사용 가능하게 하는 인터페이스와 HDFS 에 분산 저장되어 있는 파일에 액세스 기능을 제공하는 R 패키지

R 패키지는 R 콘솔이나 코드에서 바로 하둡의 map/reduce 코드를 작성할 수 있는 인터페이스를 제공

하둡이 기본적으로 제공하는 HDFS 에 빅 데이터를 저장하고 분석할 수 있는 저장공간도 제공 R 에서 제공하는 자료구조 타입을 HDFS 에 저장할 수 있으며 Rhipe 로 저장한 데이터들은 구글

프로토콜 버퍼를 사용하는 다른 개발언어에서 읽어 들일 수 있음 .( 다른 언어로 저장된 데이터를 Rhipe에서 읽어 들이는 것도 가능 )

map/reduce 수행시 status 는 보고 싶을 때 바로 콘솔에서 확인할 수 있어 디버깅에 더 효과적입니다 .( 하둡의 경우는 자세한 내용을 보기 위해 별도의 웹 브라우저를 사용 )

Google 에서 제공하는 Google protocol buffer 를 이용하여 Hadoop 과 통신 . 즉 , HDFS 에 저장된 데이터를 R 로 읽어오거나 R 에서 생성한 자료를 HDFS 에 저장하는 기능 또는 R 에서 작성된 map 과 reduce 프로그램을 Hadoop 에서 실행토록 하는 역할을 담당한다 .(R 과 Hadoop의 연동을 위한 별도의 I/F 불필요 ) Rhipe 를 이용하여 자료분석을 하기 위해서는 먼저 rhinit() 함수를 실행하여 Rhipe 와 Hadoop 을 연결

rhinit() 함수의 실행결과가 TRUE 값이면 정상적인 연동이 되었음을 의미 Rhipe 와 Hadoop 이 정상 연결이 되면 , Rhipe 에서 제공하는 HDFS 및 MapReduce 관련 함수들을 이용하여

Hadoop 의 여러 가지 기능들을 제어

Page 28: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted28

[참고 ] RHIPE 에 대해 좀 더…HDFS 관련 함수 일반적인 R 에서 제공하는 파일 관련 함수를 통해서는 HDFS 에 저장된 파일에 접근하는 것이 불가능 하다 . HDFS 파일에 접근하기 위해서는 Rhipe 에서 제공하는 함수를 사용해야 하며 , HDFS 관련 함수 를 이용하면 HDFS 에 저장된 sequence, map 또는 text 형식의 파일에 대한 접근이 가능하다 .

아래 표는 Rhipe 에서 제공하는 HDFS 관련 함수와 그에 대한 설명을 요약한 표이다 .

MapReduce 의 실행 Rhipe 를 통하여 map 과 reduce 를 실행하기 위해서는 map expression 작성 , reduce expression 작성 , MapReduce 실행에 필요한 정보가 담긴 R 오브젝트 생성 , 마지막으로 MapReduce 실행과 같은 총 4 단 계의 과정을 거친다 .

아래의 표는 MapReduce 실행 단계별 관련 R코드를 정리한 표이다 .

Page 29: Intro to r & hadoop

R + Hadoop = RHadoop?

Page 30: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted30

R + Hadoop = Data Analytics Heaven

RHadoop is a small, open-source package developed by Revolution Analytics that binds R to Hadoop and allows for the representation of MapReduce algorithms using R - allowing data scientists access to Hadoop’s scalability from their favorite language, R.  It allows users to write general MapReduce programs, offering the full power and ecosystem of an existing, established programming language.  

저렴한 비용으로 ‘빅데이터’를 다루는 데 가장 많이 사용되는 기술

통계 연산과 그래픽을 위한 프로그램 언어이자 소프트웨어 개발 환경

Put the two together to

provide easy to use R interfaces for the distributed computing Hadoop environment and you have one king-hell data crunching tool for serious data analytics.  

Page 31: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted31

RHadoop 의 구성Hadoop 에서 데이터를 관리하고 분석하는 RHadoop 은 아래와 같은 세 개의 패키지로 구성됨 :

rmrrhbaserhdfs

HDFS 의 파일관리This is an R package for providing all Hadoop HDFS access to R. All distributed files can be managed with R functions.

MR 인터페이스This is an R package for providing Hadoop MapReduce interfaces to R. With the help of this package, the Mapper and Reducer can easily be developed.

Hbase 데이터베이스 관리This is an R package for handling data at HBase distributed database through R.

Page 32: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted32

R Client

RMap

or Redu

ce

Job Tracker

Task Node

HDFS

HBASE

Avro(Thrift)

RHadoop 의 아키텍처rhdfs = R + HDFS

functions providing file management of the HDFS from within R

rmr = R + MapReduce

functions providing Hadoop MapReduce functionality in R

rhbase = R + Hbase

functions providing database management for the HBase distributed database from within R

rhdfs

rmr

rhbase

avro 

read and write files in avro formatplyrmr

higher level plyr-like data processing for structured data, powered by rmr

Page 33: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted33

[참고 ] 데이터 직렬화와 Apache Avro

데이터 직렬화란 ?메모리 버퍼 , 파일 , 혹은 네트워크를 통해서 전송되고 저장하는 데이터를 이용할 수 있는 상태로 재 구성하는 것

Apache Avro 직렬화를 위한 압축 이진 데이터 교환 형식을 제공  JSON을 사용하여 언어 상호 운용성을 따르는 언어 중립적 스키마를 정의 한 언어로 직렬화된 데이터는 다른 언어로 읽을 수 있음 (현재 C, C++, C#, Java, PHP, Python 및 Ruby 가 지원 )

Avro 시스템에서 직렬화된 개체의 표현은 스키마 및 실제 값 부분으로 구성 . Avro 스키마는 JSON 을 사용하여 직렬화된 데이터의 언어 독립적 데이터 모델을 설명 데이터의 이진 표현 옆에 표시

스키마를 이진 표현과 구분하면 값별로 오버헤드가 발생하지 않고 각 개체를 쓸 수 있으므로 직렬화는 빨라지고 표현이 차지하는 공간은 줄어듬

Hadoop 과 Avro Avro 는 Hadoop MapReduce 작업 내에서 복잡한 데이터 구조를 나타내는 편리한 방법을 제공 . Avro 파일 (Avro 개체 컨테이너 파일 ) 의 형식은 분산 MapReduce 프로그래밍 모델을 지원하도록 설계 .

분산을 가능하게 하는 기술 : 파일이 “분할 가능 " 하여 파일의 임의 지점을 찾고 특정 블록부터 읽기 시작할 수 있다

Page 34: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted34

rhdfs Manipulate HDFS directly from R

Access HDFS from R Read from HDFS to R

dataframe Write from R dataframe to

HDFS Mimic as much of the HDFS Java

API as possible

Examples:

• Read a HDFS text file into a data frame.

• Serialize/Deserialize a model to HDFS

• Write an HDFS file to local storage

• rhdfs/pkg/inst/unitTests rhdfs/pkg/inst/examples

주요 기능

File Manipulations hdfs.copy, hdfs.move, hdfs.rename, hdfs.delete, hdfs.rm, hdfs.del, hdfs.chown, hdfs.put, hdfs.get

File Read/Write hdfs.file, hdfs.write, hdfs.close, hdfs.flush, hdfs.read, hdfs.seek, hdfs.tell, hdfs.line.reader, hdfs.read.text.file

Directory hdfs.dircreate, hdfs.mkdir

Utility hdfs.ls, hdfs.list.files, hdfs.file.info, hdfs.exists

Initialization hdfs.init, hdfs.defaults

Page 35: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted35

rhbase Manipulate HBASE tables and their

content : Access and change data within HBase

Uses Thrift C++ API as the mechanism to communicate to HBASE

Examples• Create a data frame from a collection

of rows and columns in an HBASE table• Update an HBASE table with values

from a data frame• rhbase/pkg/inst/unitTests

주요 기능

Table Manipulation hb.new.table, hb.delete.table, hb.describe.table, hb.set.table.mode, hb.regions.table

Row Read/Write hb.insert, hb.get, hb.delete, hb.insert.data.frame, hb.get.data.frame, hb.scan

Utility hb.list.tables

Initialization hb.defaults, hb.init

Page 36: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted36

rmr2 Enables writing MapReduce jobs

using R (Writing MapReduce programs in R )

Ability to parallelize algorithms Ability to use big data sets without

needing to sample data Mapreduce(input, output, map,

reduce, … ) Reduces takes a key and a

collection of values which could be vector, list, data frame or matrix

rmr 의 MapReduce 기능

mapreduce (input, output, map, reduce, …) <<샘플 코드 – Word Count>>

wc.map = function(., lines) { keyval( unlist(! strsplit( x = lines, split = pattern)), 1)}wc.reduce = function(word, counts ) {! keyval(word, sum(counts))}! mapreduce( Input = input , output = output, input.format = "text", map = wc.map, reduce = wc.reduce, combine = T)}

Page 37: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted37 37

A way to access big data sets A simple way to write parallel

programs – everyone will have to

Very R-like, building on the functional characteristics of R

Just a library 

For Programmers,

Much simpler than writing Java Not as simple as Hive, Pig at

what they do, but more general Great for prototyping, can

transition to production -- optimize instead of rewriting! Lower risk, always executable.

For MapReduce Developers

rmr for,

Page 38: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted38

Rhadoop 과 Graph engineThere are two basic types of graph engines:1) Graph databases providing real-time, traversal-based algorithms over linked-list

graphs represented on a single-server (vendors include Neo4j, OrientDB, DEX, and InfiniteGraph).

2) Batch-processing using vertex-centric message passing within a graph represented across a cluster of machines. (Hama, Golden Orb, Giraph, and Pregel).

With Hadoop, the results presented are via Hadoop (HDFS + MapReduce). Moreover, instead of developing the MapReduce algorithms in Java, the R programming language is used. 

A multi-machine graph engine is required. While Hadoop is not a graph engine, a graph can be represented in its distributed HDFS file system and processed using its distributed processing MapReduce framework. 

The graph generated previously is loaded up in R and a count of its vertices and edges is conducted. Next, the graph is represented as an edge list. An edge list (for a single-relational graph) is a list of pairs, where each pair is ordered and denotes the tail vertex id and the head vertex id of the edge. The edge list can be pushed to HDFS using RHadoop.

Page 39: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted39

RHadoop 의 장점과 한계

기존의 데이터 분석가도 Big Data 처리 가능

분석결과 향상

- 간단한 모델 + 대용량 데이터

- 복잡한 모델 + 적은 데이터

벤더 종속성 탈피

장점 한계

Requires installation of R on all TaskTracker nodes

Does not automatically parallelize algorithms

Different slot/memory configuration recommended to leave memory and CPU resources for R.

Page 40: Intro to r & hadoop

R 설치와 실습

Page 41: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted41

설치하기R 설치http://cran.nexr.com/( 한국 CRAN)

R Studio 설치https://www.rstudio.com/

• R 을 위한 통합개발환경 (IDE)• R 을 사용하기 위한 다양한 기능과 편의성 제공 : 코드

직접실행 , 구문강조 , 괄호 자동입력지원 , 명령어 완성 , 다양한 단축키 , 데이터 보기 및 가져오기 , 그래픽 조작 , 프로젝트 관리 , 버전 관리 등

Page 42: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted42

실습

Page 43: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted43

[참고 ] KNUG 소개KRUG (Korean R Users Group)

GNU 의 철학에 입각하여 , R 을 한국어 사용자가 올바르고 쉽게 사용 될 수 있도록 문서를 번역하고 지식과 기술을

공유하는 사용자 모임 2007 년 1 월부터 공식적으로 활동한 비영리 모임

Offline 활동 : Meetup 을 통한 기술교류http://www.openstatistics.nethttp://www.r-project.kr/

대외협력 : 문서 /White paper/Blog 의 번역 / 배포 권리

Online 활동 : 문서번역 , 기술공유 , Q&AR User Conference 개최

Page 44: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted44

R 프로젝트 공식 사이트- http://www.r-project.org

한국 R 사용자 그룹 사이트 (KRUG)

- http://www.r-project.kr (facebook: KRUG) - http://ihelp.r-forge.r-project.org/

한국의 CRAN 제공기관 - NexR: http://cran.nexr.com/ - 중앙대학교 :

http://biostat.cau.ac.kr/CRAN/ - 다음 (Daum): http://ftp.daum.net/CRAN/ –

RTechCenter

RHadoop Open source project:

- https://github.com/RevolutionAnalytics/RHadoop/wiki

ResourcesR 참고 사이트

- http://www.r-bloggers.com- http://stackoverflow.com- http://stats.stackexchange.com- http://www.inside-r.org/- http://www.r-statistics.com/- http://support.rstudio.org/- http://quora.com

Revolution R Enterprise:

- bit.ly/Enterprise-R

Cloudera CDH:

- http://www.cloudera.com/hadoop/

Page 45: Intro to r & hadoop

[참고 ]

Page 46: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted46

Options for R on Hadoop

Page 47: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted47

Options for R on Hadoop

SQL Access from R

RODBC/RJDBC

Broad access to Hive and HDFS

RHive

Tight integration with core Hadoop components

RHadoop

Focus

Integration Ease

Benefits

Limitations

Low impact on existing R scripts leveraging other DB packages

Not required to install Hadoop configuration/binaries on client machines

Install Hortonworks Hive ODBC driver

Install Hive Libraries

Parallelism limited to Hive Result set size

Wide range of features expressed through HQL

- rhive-apply R Distributed apply function using HQL

Requires Hadoop binaries, libraries, and configuration files on client machines

Uses Java DFS Client and HiveServer

Requires heavy client deployment

Dependent on HiveServer, and can’t be used with HiveServer2

Ability to run R on a massively distributed system

Ability to work with full data sets instead of sample sets

Additional Information

https://github.com/RevolutionAnalytics/RHadoop/wiki

Page 48: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted48

R 과 MapReduce 의 통합 방법 (1/2)R+Streaming RHIPE RHadoop

라이선스 GPL-2 와 GPL-3 의 혼합이며 이것이 Apache 2.0 라이선스 조건인 Hadoop 에 이 통합됨

Apache 2.0 Apache 2.0

설치복잡성 용이함 . • R 패키지를 각각의 DataNode

에 설치하지만 패키지는 Yum 으로 설치

※ Yum 은 Yellow dog Updater, Modified 의 약자로 RPM 기반의 시스템을 위한 자동 업데이터 겸 패키지 설치 / 제거 도구

가능 다소 복잡 .• Rhipe 를 R 과 함께 DataN-

ode 에 설치 . • 단 , 이를 위해서 Protocol Buf-

fer 를 build 해야 함 .

비교적 용이 . • R 을 각각의 DataNode 에

설치 . • 단 , RHadoop 은 R 이외 일부

패키지를 먼저 설치해야 하지만 (= 의존성 있음 ) CRAN 에서 이용가능 .

클라이언트 측에서의 R 과의 통합

클라이언트 통합 없음 . • Hadoop 명령어를 통해

streaming job 을 수행하면서 map 측과 reduce 측의 script 를 지정함 .

높은 통합 . • Rhipe 는 R 의 library 로서

해당 함수 호출 시 MapReduce job 수행을 담당함 .

• 사용자로서는 native 형태의 R map 과 reduce 함수를 R 로 작성하기만 하면 Rhipe 가 이들을 transport 하고 in-voke 시켜줌 .

높은 통합 . RHadoop 그자체가 R 의 li-brary 로서 사용자는 자신의 map 과 reduce 함수를 R 로 작성

Page 49: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted49

R 과 MapReduce 의 통합 방법 (2/2)R+Streaming RHIPE RHadoop

사용된 기술 • Streaming • (Streaming 이 아니라 ) Java 로 구현된 자신의 map, re-duce 를 수행함 .

• 이들 Java 함수는 map, re-duce 입력을 Protocol Buf-fers encoded 형태로 Rhipe C 실행파일에 streaming 입력하며 Rhipe C 실행파일은 자체 내장된 R 을 통해 사용자의 map, reduce 함수를 수행

• RHadoop 이 Hadoop 과 streaming 위에서 단순하면서도 경량의 wrapper 로서 동작 .

• 따라서 독자적인 MapReduce 코드를 가지지 않으며 간단한 wrapper R 스크립트를 가짐 . Streaming 에서 wrapper R 스크립트를 호출하며 이것이 다시 사용자의 map, reduce 함수를 호출

주로 쓰이는 경우 • MapReduce 함수에 대해 정교한 조절작업이 필요한 경우 ( 예 : partitioning, 정렬 ) 하는 경우

• R 을 떠나지 않고도 R 과 MapReduce 를 이용하고자 할 경우

• R 을 떠나지 않고도 R-MapReduce 를 이용하고자 할 경우

• 또한 기존의 MapReduce 의 입출력 관련 Format class 를 이용하고자

주의할 점 • 기존 R 스크립트에서 직접 in-voke 시키기가 어려움

• Protocol Buffers encoded 데이터에 대해서는 독자적인 형식의 입출력 포맷이 필요함 .

• Unique key 에 대한 reducer 값을 모두 간직하기 위해서 많은 메모리가 필요 .

• 값은 reducer 함수에 스트림 전달되지 않음

Page 50: Intro to r & hadoop

© Copyright 2014 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. HP Restricted

C03934969, January 2014

Thank you