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