일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 실기
- Kaggle
- 데이터 분석
- seaborn
- 파이썬
- sklearn
- 실습
- pandas
- python3
- 코딩테스트
- level 1
- 카카오
- 빅분기
- 튜닝
- SQL
- R
- 머신러닝
- Numpy
- level 2
- 프로그래머스
- Python
- 오라클
- 빅데이터 분석 기사
- Oracel
- 알고리즘
- matplotlib
- oracle
- Today
- Total
라일락 꽃이 피는 날
[빅분기 실기] 머신러닝 - 분류문제 본문
1. 분석 데이터 검토
# 행과 열 구조 확인
df.shape
# 목적변수 빈도 확인
df['Class'].value_counts()
2. 특성(x)과 레이블(y) 나누기
# 컬럼 이름으로 나누기
x = df[['컬럼명1', '컬럼명2', ...]]
# 컬럼 인덱스로 나누기
x = df[df.columns[1:10]]
# loc 함수로 나누기
x = df.loc[:, '컬럼명1':'컬럼명10']
# 목적변수
y = df[['Class']]
3. 범주 변수 변환
식별자 역할을 하는 범주 변수에 원 핫 인코딩(one-hot-encoding) 적용
하위 범주를 변수로 만들어 각 케이스가 그에 해당되면 '1', 아니면 '0' 입력
데이터셋을 훈련-테스트로 나누기 전에 수행해야 오류가 적음
# 범주형 변수
X1 = data[['컬럼명1', '컬럼명2']]
# 연속형 변수
XY = data[['컬럼명3', '컬럼명4', '컬럼명5', '컬럼명6']]
# 숫자 값을 문자 값으로 변환
X1['컬럼명1'] = X1['컬럼명1'].replace([1,2], ['male', 'female']
X1['컬럼명2'] = X1['컬럼명2'].replace([1,2,3,4,5], ['A', 'B', 'C', 'D', 'E'])
# 원 핫 인코딩으로 변환
X1_dum = pd.get_dummies(X1)
# 데이터셋 합치기
Fvote = pd.concat([X1_dum, XY], axis=1)
# 파일로 내보내기
Fvote.to_csv('파일명.csv', index=False, sep=',', encoding='utf-8')
4. train-test 데이터셋 나누기
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, stratify=y, random_state=42)
random_state : 동일하게 데이터를 나누어서 분석할 때마다 다른 결과가 나오는 것을 막음
stratify = y : 레이블 범주의 비율에 맞게 데이터 구분
5. 정규화
일반적으로 머신러닝이나 딥러닝에서는 Min-Max 방법을 더 선호한다.
Min-Max 는 0~1 사이의 한정된 범위인 반면 표준화는 이론상 무한대의 값이 나타날 수 있기 때문이다.
① Min-Max 정규화 : 최솟값(min)은 모두 0이고, 최댓값(max)은 모두 1이다.
from sklearn.preprocessing import MinMaxScaler
scaler_minmax = MinMaxScaler()
# 학습 데이터로 기준 적용
scaler_minmax.fit(X_train)
# 훈련 데이터 변환
X_scaled_minmax_train = scaler_minmax.transform(X_train)
# 테스트 데이터 변환
X_scaled_minmax_test = scaler_minmax.transform(X_tset)
pd.DataFrame(X_scaled_minmax_train).describe()
fit 은 train 데이터에만 하여 train 데이터 기준을 적용하고, test 데이터에는 fit 과정 없이 바로 transform 한다.
② Standard 표준화 : 모든 평균이 0이고, 표준 편차가 1이다.
from sklearn.preprocessing import StandardScaler
scaler_standard = StandardScaler()
scaler_standard.fit(X_train)
X_scaled_standard_train = scaler_standard.transform(X_train)
X_scaled_standard_test = scaler_standard.transform(X_test)
pd.DataFrame(X_scaled_standard_train).describe()
6. 모델 학습 : 모델 훈련 → 예측 → 정확도
로지스틱 회귀모델
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
# 모델 학습
model.fit(X_scaled_minmax_train, y_train)
# 모델 예측 (범주)
pred_train = model.predict(X_scaled_minmax_train)
pred_test = model.predict(X_scaled_minmax_test)
# 모델 예측 (확률)
prob_train = model.predict_proba(X_scaled_minmax_train)
prob_test = model.predict_proba(X_scaled_minmax_test)
# 정확도 확인
model.score(X_scaled_minmax_train, y_train)
model.score(X_scaled_minmax_test, y_test)
7. 모델 검증
① 랜덤 없는 교차검증 (cross val score)
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X_train, y_train, cv=5)
print('테스트셋 정확도: ', scores)
cv : 교차검증 하는 횟수
② 랜덤 있는 교차검증 (K-Fold)
훈련 데이터에서 그룹을 나눌 때부터 랜덤으로 섞어서 나눈다.
from sklearn.model_selection import KFold
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
score = cross_val_score(model, X_train, y_train, cv=kfold)
print('폴드의 정확도: ', score)
n_splits : 그룹 수
shuffle : 섞기 여부
③ 임의 분할 교차검증
훈련 데이터와 테스트 데이터를 구성할 때 다른 교차검증에 사용된 데이터도 랜덤으로 선택
일부 데이터는 훈련 데이터 또는 테스트 데이터 어디에든 선택되지 않을 수 있음
from sklearn.model_selection import ShuffleSplit
shuffle_split = ShuffleSplit(test_size=0.5, train_size=0.5, random_state =42)
score = cross_val_score(model, X_train, y_train, cv=shuffle_split)
print('교차검증 정확도: ', score)
8. 모델 평가
① 혼동 행렬 (confusion matrix) : 정분류와 오분류 확인
from sklearn.metrics import confusion_matrix
confusion_train = confusion_matrix(y_train, pred_train)
confusion_test = confusion_matrix(y_test, pred_test)
② 분류 예측 레포트 (classification report) : 정확도, 정밀도, 재현율, f1-score 확인
from sklearn.metrics import classification_report
cfreport_train = classification_report(y_train, pred_train)
cfreport_test = classification_report(y_test, pred_test)
③ ROC 지표 : 100%에 가까울수록 좋은 모델
from sklearn.metrics import roc_curve, auc
from sklearn import metrics
false_positive_rate, true_positive_rate, thresholds
= roc_curve(y_test, model.decision_function(X_scaled_minmax_test))
roc_auc = metrics.roc_auc_score(y_test, model.decision_function(X_scaled_minmax_test))
④ ROC Curve 그리기 : 아래 면적이 넓을수록 좋은 모델
import matplotlib.pyplot as plt
plt.title('Receiver Operating Characterisitc')
plt.xlabel('False Positive Rate(1 - Specificity)')
plt.ylabel('True Positive Rate(Sensitivity)')
plt.plot(false_positive_rate, true_positive_rate, 'b', label='Model (AUC=%0.2f)'% roc_auc)
plt.plot([0,1], [1,1], 'y--')
plt.plot([0,1], [0,1], 'r--')
plt.legend(loc='lower right')
plt.show()
9. 하이퍼파라미터 튜닝
① 그리드 탐색 (Grid Search)
분석자가 하이퍼파라미터의 특정 값을 지정하고, 각각 모델에 적용하여 모델적합도를 비교하는 방법
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100]}
# GridSearchCV(알고리즘모델, 설정한 그리드서치, cv(옵션), return_train_score(옵션))
grid_search = GridSearchCV(LogisticRegression(), param_grid, cv=5, return_train_score=True)
grid_search.fit(X_train, y_train)
return_train_score : 훈련데이터 정확도 결과 제시 여부 (default False)
print("Best Parameter: {}".format(grid_search.best_params_))
print("Best Cross-validity Score: {:.3f}".format(grid_search.best_score_))
grid_search.best_params_ : 정확도가 가장 높은 하이퍼파라미터
grid_search.best_score_ : 가장 높은 정확도
result_grid = pd.DataFrame(grid_search.cv_results_)
result_grid
grid_search.cv_results_ : 그리드서치 하이퍼파라미터별, cross validation별 상세 결과값
import matplotlib.pyplot as plt
plt.plot(result_grid['param_C'], result_grid['mean_train_score'], label="Train")
plt.plot(result_grid['param_C'], result_grid['mean_test_score'], label="Test")
plt.legend()
하이퍼파라미터값 별로 훈련 데이터와 테스트 데이터의 정확도를 그래프로 출력
② 랜덤 탐색 (Random Search)
범위를 정하고 그 안에서 무작위로 최적의 하이퍼파라미터 값을 찾는 방법
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_distribs = {'C': randint(low=0.001, high=100)}
random_search = RandomizedSearchCV(LogisticRegression(), param_distributions=param_distribs,
cv=5, n_iter=100, return_train_score=True)
random_search.fit(X_train, y_train_
n_iter : 랜덤하게 C값을 몇 번 뽑는가의 횟수 (default 10)
print("Best Parameter: {}".format(random_search.best_params_))
print("Best Cross-validity Score: {:.3f}".format(random_search.best_score_))
result_grid = pd.DataFrame(random_search.cv_results_)
import matplotlib.pyplot as plt
plt.plot(result_grid['param_C'], result_grid['mean_train_score'], label="Train")
plt.plot(result_grid['param_C'], result_grid['mean_test_score'], label="Test")
plt.legend()
10. 예측값 병합 및 저장
# 예측 범주 컬럼 추가
y_test[['y_pred']] = pred_test
# 예측 확률 컬럼 추가
y_test[['y_prob0', 'y_prob1']] = prob_test
# 데이터셋 가로 병합
Total_test = pd.concat([X_test, y_test], axis=1)
# csv 파일로 내보내기
Total_test.to_csv('classification_test.csv')
'데이터 분석 > 빅데이터 분석 기사' 카테고리의 다른 글
[빅분기 실기] 로지스틱 회귀 모델 (0) | 2022.06.16 |
---|---|
[빅분기 실기] 머신러닝 - 회귀문제 (0) | 2022.05.24 |
[빅분기 실기] 머신러닝 프로세스 (0) | 2022.05.22 |
[빅분기 실기] 데이터 정제 - 이상치, 결측치 처리 (0) | 2022.05.22 |
[빅분기 실기] 데이터 탐색 (0) | 2022.05.22 |