2017년 5월 1일 월요일

Hadoop(hdp) 클러스터 구성하기 using virtualbox (CentOS7)

0. Virtual Box 설치

https://www.virtualbox.org/wiki/Downloads

사용 버전 :
  VirtualBox 그래픽 사용자 인터페이스
  버전 5.1.22 r115126 (Qt5.6.2)

설치파일 : VirtualBox-5.1.22-115126-Win.exe

1. Virtual Box Image 생성


새로 만들기 (Redhat 64)
메모리  : 3333MB
디스크 용량 : 20GB

VM 네트워크 설정

  설정 > 네트워크 > 어댑터1
    - 다음에 연결됨 : NAT 네트워크
    - 이름 : NatNetwork (기본설정)

  그 외 설정에 대한 간략한 설명 링크 : http://frontjang.info/entry/VirtualBox의-NAT과-NAT-네트워크


2. CentOS 7 설치


설치 디스크 :
CentOS-7-x86_64-DVD-1611.iso


CentOS Install Options
  Keyboard Layout
    - Korean(101/104 key compatible)
    - English(US)

  Installation Destination
    - Automatic Partition

  Network & Host Name
    - enp0s3 enabled
    - hostname : node1, node2, node3


3. 네트워크 설정

node1, 2, 3에 대해서 아래와 같이 설정을 적용한다. IPADDR은 각자 다름.

command line : 

[root@node1 ~]# vi /etc/sysconfig/network-scripts/ifcfg-enp0s3

변경 내용 :
BOOTPROTO="static" #from dhcp
...(중략)
IPADDR="10.0.2.11" # (1), (2) 참고
PREFIX="24" # (1) 참고
GATEWAY="10.0.2.2" # (1) 참고
DNS1="168.126.63.1" # KT DNS Server 1
DNS2="168.126.63.2" # KT DNS Server 2

참고내용 :

(1) In NAT mode, the guest network interface is assigned to the IPv4 range 10.0.x.0/24 by default where x corresponds to the instance of the NAT interface +2. So x is 2 when there is only one NAT instance active. In that case the guest is assigned to the address 10.0.2.15, the gateway is set to 10.0.2.2 and the name server can be found at 10.0.2.3.


(2) examples
  node1 : 10.0.2.11
  node2 : 10.0.2.12
  node3 : 10.0.3.13

command line : 

[root@node1 ~]# systemctl restart network
[root@node1 ~]# ip addr
[root@node1 ~]# vi /etc/hosts

변경 내용 :
10.0.2.11 node1
10.0.2.12 node2
10.0.2.13 node3


  - 난 설정이 제대로 안 먹혀서 헤매다가 reboot 하고 나서 됐다..ㄷㄷ


4. host - guest 접속 설정

NAT Network만으로 사용하고자 한다면,
host에서 guest ip에 직접 접근할 수 없으므로, 포트포워딩 규칙을 이용해야 한다.

파일 > 환경설정 > 네트워크 > NAT 네트워크 > NatNetwork > 포트포워딩 > 규칙 추가

vm에 직접 접속하는 것보다 익숙한 shell client로 접속하려고 일단 22(ssh) 를 연결했다.























5. Ambari Server 설치

(참고 : https://docs.hortonworks.com/HDPDocuments/Ambari-2.1.0.0/bk_Installing_HDP_AMB/content/_download_the_ambari_repo_lnx7.html)

Ambari 서버가 될 노드에서 아래 순서로 진행한다.

1. root 로그인

2. Donwload Ambari reository
(CentOS7 을 minimal로 설치해서, wget이 없었다. yum install wget)

[root@node1 ~]# wget -nv http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.1.0/ambari.repo -O /etc/yum.repos.d/ambari.repo

3. yum install ambari-server


Set Up the Amabari Sever

https://docs.hortonworks.com/HDPDocuments/Ambari-2.1.0.0/bk_Installing_HDP_AMB/content/_set_up_the_ambari_server.html


DB 준비

ambari 및 service의 metadata 저장소로 PostgreSQL을 쓸 것이다.

  PostgreSQL 설치
    ...

  jdbc 연결
    ambari-server setup --jdbc-db=postgres --jdbc-driver=/path/to/your/postgres/driver.jar

  hive metadata table 생성
    create user hive with password 'hive';
    create database hive owner = hive;

  설정 변경 (pg_hba.conf)

    파일 내용 :
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all   postgres                                     peer
# IPv4 local connections:
host    all   postgres             127.0.0.1/32            ident
# IPv6 local connections:
host    all   postgres             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            ident
#host    replication     postgres        ::1/128                 ident
local  all  ambari,mapred,hive md5
host  all   ambari,mapred,hive 0.0.0.0/0  md5
host  all   ambari,mapred,hive ::/0 md5
  설정 변경 후 PostgreSQL 재시작
    systemctl restart postgresql

ntpd 설치

https://www.cmsfactory.net/node/11424


Start the Amabri Server

[root@node1 ~]# ambari-server start


 Connect to Ambari (http://node01:8080)

host PC에서 chrome을 쓰는게 편할 것 같아서, node01에 대해 port 8080만 위에서 한 것처럼 포트포워딩을 연결했다. 이런 식으로 많이 쓰일 것 같으면, NAT Network 외에 네트워크 어댑터가 추가하는 게 나을 것 같은데, 아직 모르겠으니 그냥 두는 걸로..

Installing, Configuring, and Deploying a HDP Cluster

https://docs.hortonworks.com/HDPDocuments/Ambari-2.1.0.0/bk_Installing_HDP_AMB/content/ch_Deploy_and_Configure_a_HDP_Cluster.html



설치된 모습..

  나중에라도 서비스들을 추가할 수 있어서 일단 몇 개만 깔았다.
























2017년 4월 20일 목요일

[Machine Learning] 4. Supervised Learning - Classification

Classification

  - Predictive modeling for categorical or discrete values (or class)
  - 각 케이스에 해당하는 그룹을 판별한다.
      . 광고 메일에 대한 반응(답장 여부)
      . 어떤 수술 방법에 대해 적합한 환자인지
      . 신용 평가가 좋은지 나쁜지(또는 등급)
  - training data로 model을 생성하고, 예측에 대한 평가는 그 외의 data로 수행한다.
      . 주로 training data/testing data를 구분하여 수행한다.
  - Classification models
      . Decision Trees
      . Neural Networks
      . Support Vector Machine
      . Discriminant Analysis
      . Logistic regression
      . K-nearest neighbor


이번 글에서는 Logistic regression에 대해 주로 다룰 것이다.
(후에 Decision Tree, Neural Network, Support Vector Machine을 다룰 예정)


Logistic Regression

식을 쓰려다가 막막해서 wiki를 찾아봤는데, 설명이 잘 되어 있다.
(우씨 떄려칠까 그냥)

https://ko.wikipedia.org/wiki/%EB%A1%9C%EC%A7%80%EC%8A%A4%ED%8B%B1_%ED%9A%8C%EA%B7%80

wiki page에서 4. 모델 피팅 내용 전까지 보면 된다.
이후에 모델 피팅 방법으로 wiki에 제시된 것과 다르게, Gradient descent method를 통해 계산할 것이다. (컴퓨터가)


R 코드 예시 :
> testdata = read.table('buytest.txt',sep='\t',header=T)
> lgstResult = glm(RESPOND~X1+X2+X3+X4+X5+X6+X7+X8+X9+X10,
             family=binomial(), data=testdata)


Logistic Regression도 마찬가지로 이전 글(http://justkook.blogspot.kr/2017/04/machine-learning-3-supervised-learning.html)에서 설명한 것처럼 한번만 수행하는 것이 아니라, 가장 적합한 모델을 생성하기 위해서 X Variable을 선택하는 방법이 필요하다.
(Backward Elimination, Forward Selection, Stepwise Selection)


Model Comparison

문제는 Logistic regression은 Linear Regression과 다르게, R-square 또는 p-value가 없어서 모델을 비교하는 다른 방법이 필요하다.

그렇기 때문에 data를 3가지로 분류해서 사용한다.
  - Training data : Regression Model 생성 시 활용
  - Validation data : Model Comparison 에 활용
  - Testing data : 선택된 모델(final model)에 대한 검증 시 활용

Training Dataset을 정할 때 유의할 점이 있다.
  - 전체 data set을 대표할 수 있도록 random sample
  - 매우 희귀한 reponse를 찾는 모델을 다룰 경우, 충분한 관측치가 포함되어야 한다.
      . stratified sampling : random sample로 불충분한 경우에는 일정 비율을 맞춰 데이터를 샘플링 하기도 한다.

Model Comparison in Classification
  - Accuracy
  - Lift chart
  - Profit chart
  - ROC curve (AUROC)
  - K-S statistics


Confusion Matrix

                       predicted class
                         0              1
actual  0    True Negative   False Positive
class    1   False Negative   True Positive


  - Accuracy = true positive / actual positive
  - Error = 1- accuracy
  - Sensitivity = true positive / (false positive + true positive)
  - Specificity = true negative / (true negative + false positive)


Lift Chart
  - Cumulative table


Profit Chart
  : 해당 차트를 통해, cut-off value를 선택

ROC Curve
  - ROC stands for Receiver Operating Characteristic

Graph of ROC
y = True positives
x = False Positives ( 1 - Specificity )

, 그리고 AUROC (Area Under ROC)
AUROC는 linear regression에서의 r-square와 비슷한 값으로
회귀식 에 대한 신뢰도라고 생각할 수 있다.

[Machine Learning] 3. Supervised Learning - Regression

빅데이터에서의 Regression 회귀분석에 주로 쓰이는 기호/용어가 있다.

y = Θ0 + Θ1X1 + ... + ΘpXp
  = ΘTX + ε

... (기호 못 쓰겠다.. gg)
(Θ는 회귀계수를 나타내는 vector (1xN matrix)
(ΘT는 theta transpose)

회귀식은 hypothesis라 하여 아래와 같이 나타낸다.
hΘ(x) = ΘTX

Cost function = mean squared error
J(Θ) = 1/2m x Σ( hΘ(x) - yi )^2
Find Θ which minimizes J(Θ)

비용함수 J(Θ)의 최소값을 찾기 위한 방법에는 크게 2가지가 있다.
1. Normal Equation : 미분해서 0이 되는 값 구하기
2. Gradient descent method

가장 큰 차이점은 Normal Equation의 경우 시간복잡도가 O(p^3)
Gradient descent method가 O(p^2)이다.
데이터가 크면 선택의 여지 없이 Gradient descent method를 써야할 것이다.


Linear Regression
p-value를 통해 유효한 feature 및 그에 대응하는 Coefficients 를 통해 선형 회귀식을 도출한다.

여러가지 Variable 중 선택하는 방법엔 크게 4가지가 있다.

  - All Subsets
      : 모든 경우의 수(2^k) 수행해보기
  - Backward Elimination
      : 모든 변수를 포함한 회귀식을 수행한 뒤, 원하는 유효 수준(p-value)기 되지 않는 변수를 하나씩 삭제한다.
  - Forward Selection
      : Backward와 반대로 변수를 하나씩 넣어보고 가장 유효한(작은 p-value) 변수를 하나씩 추가한다.
  - Stepwise Selection
      : Forward Selection, Backward Elimination을 한번씩 수행한다.

계산 비용은 예측 가능한대로다.
All Subsets > Stepwise > Forward > Backward

일반적으로 Stepwise를 쓰나, 계산이 많은 경우 Backward를 수행한다.




[Machine Learning] 2. Pre-processing (Preparation)

Big Data Analytics에 있어서, 상당 부분 시간이 소요되는 부분은
사실 분석보다는 분석을 위한 준비 단계(데이터 수집+데이터 정제)이다.








참조 :


최근 관련 시장을 보면, Paxata, Datameer, Alteryx와 같은 툴 뿐 아니라, IT 기업에서 다양한 가치와 경험을 내걸고 출시하고 있는 솔루션들이 많다. 
 ex. ETL(AWS Glue), Data Preparation(Google DataPrep)


Data Preparation이라는 무슨 작업일까?

data 정제 및 분석에 알맞은 형태로 변환이라는 넓은 범위에서 보면 상당히 다양하다.

 - missing value 제거 
 - 데이터 추가 (ex. Timestamp field)
 - type 확인하기 (ex. number, string, categories, etc)
 - replace values
 - split values with delimiter
 - data scaling : 분석 모델에 따라 필요한 경우가 많다. 
     (ex. log(x), sqrt(x), 1/x, x^2, exp(x), 표준화(X-μ/σ)
 - dummy variables(indicator variable) 
     . 범주형 data에 대해 필드를 추가하여 0 or 1로 나타냄.


Machine Learning Series에서는 이 정도로만 다루고 넘어가도록 하자.

[Machine Learning] 1. Introduction

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[Machine Learning Series]
1. Introduction (4/20 upload)
2. Preprocessing (4/20 upload)
3. Supervised Learning - Regression (4/20 upload)
4. Supervised Learning - Classification (4/20 upload)
5. Supervised Learning - Neural Network
6. Supervised Learning - Decision Trees
7 Supervised Learning - Support Vector Machine
8. Unsupervised Learning - Clustering
9. Association Analysis - Text Mining
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Machine Learning

What is machine learning?
내가 좋아하는 단어를 포함하는 정의로 하면,
예제 데이터 혹은 과거 데이터를 이용하여, 요구 성능을 최적화하는 것! 
Optimize a performance criterion using example data or past experience.


분석 프로세스
Selection : 다양한 source로부터 data를 수집
Pre-processing : data 클린징
Transformation : 분석을 위한 format으로 데이터를 변경
Machine Learning/Data Mining
Interpretation/Evaluation : 의미 있는 결과를 도출


Machine Learning Tasks
 - Association Analysis 
     : 연관성 분석 (ex. 목요일 밤, 마트에서 맥주를 사고 나면, 기저귀를 같이 산다.)

 - Supervised Learning
     : training/sample data에 y값에 대한 결과가 존재
     . Classification 
         : 분류 (ex. 스팸인지 아닌지, 신용등급 평가)
     . Regression/Prediction
         : 분류를 포함한 다양한 회귀분석 기법 (ex. 중고차의 가격 예측)

 - Unsupervised Learning
    : y가 없는 data에 대한 분석
     . Clustering
       
 - Reinforcement Learning
     . Decision making
 - Deep Learning

2017년 3월 10일 금요일