화요일!
Logistic Regression을 활용해 머신러닝 진행 시 주의사항을 알아본다.
앞으로 우리는 Classification(이항분류)의 Metrics로 Accuracy를 사용할 예정이다.
모델 평가 전 고려해야 하는 것들
1. learning rate(학습률) : loss 값을 보면서 학습률을 조정해야 함. 보통 1의 마이너스 4승으로 잡음
학습률이 너무 크다면 global minima(W')를 찾을 수 없게 됨 → OverShooting 발생
학습률이 아주 작다면 local minima 찾게 됨
2. Normalization(정규화) :
MinMax Scaling - 0 ~ 1. 이상치에 민감함
Standardization - 표준화, Z-Score. 상대적으로 이상치에 둔감함, 모든 칼럼에 대한 scale이 동일하지 않음
3. 과적합 :
Under-fitting(과소 적합) - 데이터 양이 적거나, 학습 양이 적은 것
Over-fitting(과대 적합) - Model이 Training Data Set에 너무 잘 맞춰져, 오히려 Test Data Set에 대해서는 정확도가 떨어짐. 반복 학습의 횟수(epoch)를 제한해야 함
- 1. 많은 Training Data를 사용해 학습. 가진 Data가 적다면 데이터 증식(Augmentation), 하지만 Resource를 많이 사용하고 학습시간이 상당히 길어짐
- 2. 데이터 분석을 통해 종속변수와 상관관계가 적거나 중복된 feature(독립변수)를 삭제함으로써 개수를 줄임
- 3. 규제(Regularization. L1 - Lasso Regression, L2 - Ridge Regression)를 통해 loss 값을 인위적으로 크게 하여 Weight(W)의 값이 너무 크지 않도록 조절
- 4. Deep Learning에서는 Dropout이라는 방법을 이용
4. 데이터의 불균형(비대칭)을 어떻게 해소할 것인가?
class(분류. 0과 1)에 속한 데이터의 개수에 차이가 있을 때 → Imbalanced Data Problem
Over-Sampling - 데이터가 부족하고 편향되어 있을 때 소수의 데이터를 복제함 → SMOTE 기법
Under-Sampling - Data 개수가 충분히 많다면 개수를 맞추어 나머지를 버림. 데이터가 많은 경우가 흔치 않고, 정상적인 데이터를 잃어버릴 수 있기 때문에 사용을 지양함
5. K-Fold Cross Validation(vs. Hold-out Validation) : Original Data Set을 Training, Validation, Test Data Set으로 나눌 때 편리성과 데이터의 비대칭을 방지하기 위해 Sklearn을 사용함. 하지만 시간이 오래 걸림
Binary Classification의 대표적인 2개의 예제(위스콘신 유방암 데이터, Titanic)를 구현해보자
1. Binary Classification - 위스콘신 유방암 데이터 by Sklearn
import numpy as np
from sklearn import linear_model
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score # cross validation
import warnings
warnings.filterwarnings('ignore')
# from sklearn.preprocessing import MinMaxScaler
# from scipy import stats
# import matplotlib.pyplot as plt
cancer = load_breast_cancer()
# print(type(cancer))
# <class 'sklearn.utils.Bunch'>. Sklearn이 데이터를 표현하기 위해 사용하는 자료구조. Python의 Dict와 유사함
# print(cancer) # data이 독립변수, target이 종속변수
# print(cancer.data.shape, cancer.target.shape) # (569, 30) (569,)
# print(np.unique(cancer.target, return_counts=True)) # return_counts=True 값이 몇 개가 있는지
# (array([0, 1]), array([212, 357], dtype=int64))
# print(cancer.DESCR) # 유방암 데이터에 대한 상세 내용
# Missing Attribute Values: None 결측치 없음
# Class Distribution: 212 - Malignant(악성), 357 - Benign(정상)
# Data Set
x_data = cancer.data
t_data = cancer.target
# print(type(x_data), x_data.shape) # <class 'numpy.ndarray'> (569, 30)
# print(type(t_data), t_data.shape) # <class 'numpy.ndarray'> (569,)
# Hold-out Validation을 위해, Train과 Validation Data Set으로 분리.default는 75% : 25%
train_x_data, test_x_data, train_t_data, test_t_data = \
train_test_split(x_data, t_data, test_size=0.2, random_state=2, stratify=t_data)
# stratify는 class의 비율에 맞게 데이터를 나눠줌
# print(train_x_data.shape, train_t_data.shape) # (455, 30) (455,)
# print(np.unique(train_t_data, return_counts=True)) # (array([0, 1]), array([170, 285], dtype=int64))
# Model 생성
model = linear_model.LogisticRegression()
# K-Flod Cross Validation
test_score = cross_val_score(model, x_data, t_data, scoring='accuracy', cv=5)
# scoring은 metric 종류, cv은 몇 번 검증할지
# print(test_score)
print(test_score.mean()) # 0.9490451793199813%
# Hold-out Validation
model.fit(train_x_data, train_t_data)
test_score = model.score(test_x_data, test_t_data)
print(test_score) # 0.956140350877193
2. Binary Classification - 위스콘신 유방암 데이터 by Tensorflow
import tensorflow as tf
# Placeholder
X = tf.placeholder(shape=[None,30], dtype=tf.float32)
T = tf.placeholder(shape=[None,1], dtype=tf.float32)
# Weight, bias
W = tf.Variable(tf.random.normal([30,1]))
b = tf.Variable(tf.random.normal([1]))
# Hypothesis, model, predict model, Logistic Regression Model
logit = tf.matmul(X,W) + b
H = tf.sigmoid(logit)
# cross entropy(loss func)
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logit, labels=T))
# train
train = tf.train.GradientDescentOptimizer(learning_rate=1e-4).minimize(loss)
# Session & 초기화
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# 반복 학습
# 전체 데이터를 이용해서 1번 학습하는 것을 1 epoch이라 함
for step in range(100000):
_, loss_val = sess.run([train, loss], feed_dict={X: train_x_data, T: train_t_data.reshape(-1,1)})
if step % 10000 == 0:
print('loss value : {}'.format(loss_val))
# Accuracy 측정
# validation data(test_x_data, test_t_data)를 이용해서 정확도를 측정
predict = tf.cast(H >= 0.5, dtype=tf.float32) # True -> 1.0, False -> 0.0
correct = tf.equal(predict, T) # equal은 predict와 T가 같은지 비교. boolean으로 나옮(True, False, Flase, True...)
accuracy = tf.reduce_mean(tf.cast(correct, dtype=tf.float32)) # correct를 실수로 바꿔서 평균을 구함(cross entropy)
accuracy_val = sess.run(accuracy, feed_dict={X: test_x_data, T: test_t_data.reshape(-1,1)})
print('Accuracy : {}'.format(accuracy_val)) # Accuracy : 0.9122806787490845
추가 수행평가~
캐글 타이타닉 예제를 Tensorflow로 구현해 캐글에 제출 후 화면 캡처해서 올리기!
1. 3/15 화 | 2. 3/16 수 | 3. 3/17 목 | 4. 3/18 금 | 5. 3/21 월 |
ML 환경 설정 (아나콘다, 주피터 노트북), Pandas, Numpy, ndarray |
ML Numpy, 행렬곱연산, 전치행렬, iterator, axis, Pandas, Series, DataFrame |
ML Pandas, DataFrame, 함수들 |
ML Pandas, 데이터 분석, 데이터 전처리 |
ML Pandas, 데이터 전처리, 수행평가 |
6. 3/22 화 | 7. 3/23 수 | 8. 3/24 목 | 9. 3/25 금 | 10. 3/28 월 |
ML 데이터 시각화, Matplotlib, 기술통계 |
ML 기술통계 |
ML 기술통계, 머신러닝 |
ML 미분, Regression |
ML 머신러닝 기법들, Regression |
11. 3/29 화 | 12. 3/30 수 | 13. 3/31 목 | 14. 4/1 금 | 15. 4/4 월 |
ML Regression 구현 (Python, Scikit-Learn) |
ML Outlier, Z-score, MinMaxScaler, 다변수 |
ML Tensorflow, Classification |
ML Classification, Logistic Regression |
ML 평가지표(Metrics) |
16. 4/5 화 | 17. 4/6 수 | 18. 4/7 목 | 19. 4/8 금 | 20. 4/11 월 |
ML 평가 시 주의사항 (Over-fitting, Regularization, Over-Sampling) |
* 이해가 잘 안 가는 개념이나 구조를 공부하고 넘어가자!