2017년 8월 9일 수요일

Refactoring Techniques

Refactoring Techniques


.Composing methods

..extract method, inline method, extract variable, inline temp, replace temp with query, split temporary variable, remove assignments to parameters, replace method with method object, substitute algorithm

.Moving Feature between

..move method, move field, extract class, inline class, hide delegate, remove middle man, introduce foreign method, introduce local extension

.Organizing Data

..selfencapsulate field, replace data value with object, change value to reference, change reference to value, replace array with object, duplicate observered data, change unidirectional association to bidirectional, change bidirectional association to unidirectional, replace magic number with symbolic constant, encapsulate field, encapsulate collection, replace type code with class, replace type code with subclasses, replace type code with state/strategy, replace subclass with fields

.Simplifying Conditional Expression

..decompose conditional, consolidate conditional expression, consolidate duplicate conditional fragments, remove control flag, replace nested conditional with guard clauses, replace condional with polymorphism, introduce null object, introduce assertion

.Simplifying Method Calls

..rename method, add parameter, remove parameter, seprate query from modifier, parameterize method, replace parameter with explicit methods, preserve whole object, replace parameter with method call, introduce parameter object, remove setting method, hide method, replace constructor with factory method, replace error code with excetpion, replace exception with test

.Dealing with Generalization

..pull up field, pull up method, pull up constructor body, push down method, push down field, extract subclass, extract superclass, extract interface, collapse hierarchy, form template method, replace inheritance with delegation, replace delegation with inferitance


.Big Refactorings(추가)

..Tease Apart Inheritance, Convert Procedural Design to Objects, Separate Domain from Presentation, Extract Hierarchy


reference :
(1) Refactoring techniques
https://refactoring.guru/refactoring/techniques
  Martin Fowler's refactoring 예시로 쓰였던 코드들을 가지고, refactoring techniques를 적용과정을 step by step 확인할 수 있다.
  각각의 technique에 대해 Why, Benefit, How로 정리되어 있으며, 가장 하단에 Live Example로 차근차근 볼 수 있다. (Internet Explorer에서는 안될 수도)


(2) 대규모 리팩토링 (Big Refactorings)
http://wiki.gurubee.net/pages/viewpage.action?pageId=1507354
 구루비에서 한글로 작성된 내용이다. 읽어보진 않았지만 다른 Refactoring technique에 대해서 다루고 있는 것 같다. Big Refactoring에 대한 내용까지 포함하고 있어서 추가했다.


Linux Performance 기초


Netflix Techblog

what do you check in the first minute?

https://medium.com/netflix-techblog/linux-performance-analysis-in-60-000-milliseconds-accc10403c55

Tutorials

https://medium.com/netflix-techblog/netflix-at-velocity-2015-linux-performance-tools-51964ddb81cf

2017년 5월 28일 일요일

[Time Series Analysis] Symbolic Aggregate Approximation (SAX) 이란?

[Time Series Analysis]
Symbolic Aggregate approXimation 또는 Symbolic ApproXimation을 줄여 SAX라 한다.

먼저 SAX에 대한 개괄적인 설명은 아래와 같다.
(느낌이 잘 오지 않는데, Creating SAX을 보면 이해가 될 것이다.)

  SAX는 시계열(time series) data에 대해 time window로 나누고, 차원 축소를 하여 나타내는 하나의 방법이다.
  클러스터링, 분류(classification), 인덱싱(index) 등의 고전적인 데이터 마이닝 기법에서, 잘 알려진 표현방법인 DWT(Discrete Wavelet Transform), DFT(Discrete Fourier Transform) 만큼 좋으면서, 저장 공간은 적게 필요로 하는 것이 바로 SAX 이다.
  게다가, 생물정보학 또는 텍스트마이닝 분야에서 쓰이는 풍부한 자료 구조를 활용 가능할 뿐 아니라, 현재 데이터 마이닝 작업과 관련된 많은 문제에 대한 솔루션을 제공한다. (그렇다고 한다.)



Creating SAX


- Time series 형태의 Input이 들어오면, 계단형의 데이터 형태로 단순화한다. 이것을 PAA로 변환한다고 표현한다. (Piecewise Aggregate Approximation)

- 시간에 따른 곡선형 표현에서 계단형 모습을 바뀌게 된 것(PPA)을 텍스트 형태로 다시 기호화 한다. ex)aabbbccb 이런 형태로 표현된 것을 SAX라 한다.

PAA (Piecewise Aggregate Approximation)

Pros:
계산이 매우 빠르다.
다른 접근방법들만큼 효과적이다. (경험적으로)
임의의 길이에 대한 질의도 처리 가능하다.
Can support any Minkowski metric
Supports non Euclidean measures
간단! 명료!
Cons:
그려보면 알겠지만, 썩 만족스럽지 못한 형태로 보인다.


Symbolic ApproXimation

- PAA처럼 시계열 데이터를 조각으로 구분하여 표현한다.
- PAA에서는 표현한 측정치 대신 y축 또한 구간을 심볼로 표현한다. (텍스트 형태).

Symbol Mapping/SAX Computation.


PAA로 표현되는 y값에 대해 정규식을 통해 적절히 구간을 분류하여 구간별로 Symbol을 Mapping한다.

2017년 5월 3일 수요일

CentOS7 바뀐 기본 command (service, netstat, ifconfig

  바뀌거나 말거나 redirect 되어 있거나, yum install을 통해서 해결할 거라면 상관 없지만, deprecated된 데는 이유가 있을 테니 새로운 걸 사용해보려고 하면 찾아보기 귀찮기도 하고 헷갈린다. 그래도 왠지 그러고 싶다ㅋㅋㅋ

  개인적으로 자주 쓰는 명령어부터 하나씩 적어 놓으면 좋을 것 같다. 워낙 피상적으로만 쓰다보니 얼마나 될까 싶기도 하지만..


service postgresql status
  --> systemctl status postgresql

  : service가 systemctl(시스템 콘트롤러)가 되면서 동사가 들어간다고 생각하니 이해하기 편했다.

netstat -anop
  --> ss -anop

  : 내가 쓰던 옵션들은 ss에 다 살아있다.

ifconfig
  --> ip addr



Deprecated Linux networking commands and their replacements 관련 링크 :
  https://dougvitale.wordpress.com/2011/12/21/deprecated-linux-networking-commands-and-their-replacements/
  여기 들어가면 아래 command 관련해서 자세히 볼 수 있다.
  arp, ifconfig, iptunnel, iwconfig, nameif, netstat, route


2017년 5월 2일 화요일

PostgreSQL JDBC 버전 정책 변경 (9.4.xxxx to 42.x.x)


어떤 이유에서 PostgreSQL JDBC를 받으려고 하다가 버전이 갑자기 변경된 걸 보고 찾아보게 되었다. 왜 그럴까 궁금했다.

JDBC Release Notes를 보면, 2017-02-20부터 버전이 확 달라졌음을 알 수 있다.
Version 42.0.0 (2017-02-20)
Version 9.4.1212 (2016-11-02)

원문 내용 : https://jdbc.postgresql.org/documentation/faq.html
그에 대한 답변 중 일부만 간추리면 아래와 같다.

1. 새로운 버전 정책

  1.1 왜 9.4.xxxx 에서 42.x.x로 바뀌었는가?

    a) 해당 버전 PostgreSQL 서버의 버전 호환성 외의 기능만으로도 업데이트가 생기게 되어 더이상 서버의 릴리즈 스케줄과 같이 갈 필요가 없다.

    b) 서버 버전과 일치하는 JDBC를 써야할 것 같은 혼란에 빠진다. 예를 들면,  9.4.xxxx JDBC는 PostgreSQL 8.2 이상을 모두 지원한다.

    c) bug fixes, feature fixes를 구분하기 위해 Semantic Versioning이 더 적절했다.

  1.2 그럼 42라는 숫자는?

    그냥 랜덤이긴 한데, 당분간 서버 버전이랑 겹칠 일이 없을 만큼 큰 숫자기도 했다. 서버 42 버전은 2049년에나 나올 거니까.

    혹자는 42가 삶과 우주, 모든것에 대한 답이라고도 했고.
    (이런 농이 있는 줄 처음 알았네요. https://namu.wiki/w/42)

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월 9일 목요일

AllFusion ERwin Data Modeler 7

AllFusion ERwin Data Modeler 7 를 이용해서
Logical Model, Physical Model을 개발/관리


개발 DB는 PostgreSQL 이었는데, MySQL.erwin_fe-template으로 별문제가 없어서 그냥 쓰기로 했다.


Logical Model
Format > Display Level >







Physical Model