|
1 2 3 4 5 6 7 8 9 10 11 12 | from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline pipe_lr = make_pipeline(StandardScaler(), PCA(n_components=2), LogisticRegression()) pipe_lr.fit(X_train, y_train) y_pred = pipe_lr.predict(X_test) test_acc = pipe_lr.score(X_test, y_test) | cs |
2. k-겹 교차 검증을 사용한 모델 성능 평가
2.1. 홀드 아웃 방법
<모델선택에 홀드아웃 방법 사용하는 가장 좋은 방법>
훈련 데이터셋(여러 가지 모델 훈련 하는 데 사용), 검증 데이터셋(모델 선택에 사용), 테스트 데이터셋 세 개의 부분으로 나눈다!
---> 훈련과 모델 선택 단계에서 모델이 만나지 못한 테스트 데이터셋을 분리했기 때문에 새로운 데이터에 대한 일반화 능력을 덜 편향되게 추정할 수 있는 장점이 있음.
---> 훈련 데이터를 훈련 데이터셋과 검증 데이터셋으로 나누는 방법에 따라 성능 추정이 민감할 수 있다는 것이 단점임.
2.2. k-겹 교차 검증
① k-겹 교차검증
<k값>
② 계층적 k-겹 교차검증
--> k-겹 교차검증이 클래스 비율이 동등하지 않을 때 사용
--> 각 폴드에서 클래스 비율이 전체 훈련 데이터셋에 잇는 클래스 비율을 대표하도록 유지.
1 2 3 4 5 6 7 8 9 10 11 | from sklearn.model_selection import cross_validate scores = cross_validate(estimator=pipe_lr, X=X_train, y=y_train, scoring=['accuracy'], cv=10, n_jobs=-1) print('CV 정확도 점수: %s' % scores['test_accuracy']) print('CV 정확도: %.3f +/- %.3f' % (np.mean(scores['test_accuracy']), np.std(scores['test_accuracy']))) | cs |
3. 학습 곡선과 검증 곡선을 사용한 알고리즘 디버깅
3.1. 학습 곡선으로 편향과 분산 문제 분석
훈련 정확도와 교차 검증 정확도가 모두 낮음 ==> 과소적합 <과소적합 해결방법> 1. 모델의 파리미터 개수를 늘린다. 2. 추가적인 특성을 수집하거나 만든다. 3. 서포트 벡터 머신(SVM)이나 로지스틱 회귀 분류기에서 규제 강도를 줄인다. | |
훈련 정확도와 교차 검증 정확도 사이에 큰 차이가 있음 ==> 과대적합 <과대적합 해결방법> 1. 더 많은 훈련 데이터를 모은다. 2. 모델 복잡도를 낮춘다. 3. 규제를 증가시킨다. --> 규제가 없는 모델에서는 특성 선택이나 특성추출을 통해 특성 개수를 줄여 과대적합을 감소시킨다. | |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve pipe_lr = make_pipeline(StandardScaler(), LogisticRegression(penalty='l2', max_iter=10000)) train_sizes, train_scores, test_scores =\ learning_curve(estimator=pipe_lr, X=X_train, y=y_train, train_sizes=np.linspace(0.1, 1.0, 10), cv=10, n_jobs=1) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(train_sizes, train_mean, color='blue', marker='o', markersize=5, label='Training accuracy') plt.fill_between(train_sizes, train_mean + train_std, train_mean - train_std, alpha=0.15, color='blue') plt.plot(train_sizes, test_mean, color='green', linestyle='--', marker='s', markersize=5, label='Validation accuracy') plt.fill_between(train_sizes, test_mean + test_std, test_mean - test_std, alpha=0.15, color='green') plt.grid() plt.xlabel('Number of training examples') plt.ylabel('Accuracy') plt.legend(loc='lower right') plt.ylim([0.8, 1.03]) plt.tight_layout() # plt.savefig('figures/06_05.png', dpi=300) plt.show() | cs |
3.2. 검증 곡선으로 과대적합과 과소적합 조사
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 32 33 34 35 36 37 38 39 40 41 42 43 44 | from sklearn.model_selection import validation_curve param_range = [0.001, 0.01, 0.1, 1.0, 10.0, 100.0] train_scores, test_scores = validation_curve( estimator=pipe_lr, X=X_train, y=y_train, param_name='logisticregression__C', param_range=param_range, cv=10) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='blue', marker='o', markersize=5, label='Training accuracy') plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, alpha=0.15, color='blue') plt.plot(param_range, test_mean, color='green', linestyle='--', marker='s', markersize=5, label='Validation accuracy') plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, alpha=0.15, color='green') plt.grid() plt.xscale('log') plt.legend(loc='lower right') plt.xlabel('Parameter C') plt.ylabel('Accuracy') plt.ylim([0.8, 1.0]) plt.tight_layout() # plt.savefig('figures/06_06.png', dpi=300) plt.show() | cs |
4. 그리드 서치를 사용한 머신 러닝 모델 세부 튜닝
<머신러닝 종류>
① 훈련 데이터에서 학습되는 파라미터(ex 로지스틱 회귀의 가중치)
② 별도로 최적화되는 학습 알고리즘의 파라미터(= 모델 파리미터, 하이퍼파리미터, ex 로지스틱 회귀의 규제 매개변수)
4.1. 그리드 서치를 사용한 하이퍼파라미터 튜닝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC pipe_svc = make_pipeline(StandardScaler(), SVC(random_state=1)) param_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0] param_grid = [{'svc__C': param_range, 'svc__kernel': ['linear']}, {'svc__C': param_range, 'svc__gamma': param_range, 'svc__kernel': ['rbf']}] gs = GridSearchCV(estimator=pipe_svc, param_grid=param_grid, scoring='accuracy', refit=True, cv=10) gs = gs.fit(X_train, y_train) print(gs.best_score_) print(gs.best_params_) | cs |
4.2. 랜덤 서치로 하이퍼파라미터 설정을 더 넓게 탐색하기
<그리드 서치> - 완전탐색 - 하이퍼파라미터 그리드 실정이 크면 그리드 서치 비용이 많이 소요됨 -사용자가 지정한 이산적인 옵션만 탐색하르모 탐색 공간이 너무 듬성듬성하면 좋은 하이퍼파라미터 설정을 놓칠 수 있음. | <랜덤 서치> - 공간에 대해 완전 탐색 수행하지 않음 - 비율과 시간 측면에서 더 효율적으로 넓은 범위의 하이퍼파라미터 값을 탐색할 수 있음. |
랜덤 탐색을 사용하여 SVM 튜닝
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 | import scipy.stats from sklearn.model_selection import RandomizedSearchCV param_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0] param_range = scipy.stats.loguniform(0.0001, 1000.0) np.random.seed(1) pipe_svc = make_pipeline( StandardScaler(), SVC(random_state=1)) param_grid = [{'svc__C': param_range, 'svc__kernel': ['linear']}, {'svc__C': param_range, 'svc__gamma': param_range, 'svc__kernel': ['rbf']}] # RandomizedSearchCV 객체 생성 rs = RandomizedSearchCV(estimator=pipe_svc, param_distributions=param_grid, scoring='accuracy', refit=True, n_iter=20, cv=10, random_state=1, n_jobs=-1) rs = rs.fit(X_train, y_train) | cs |
4.3. SH 방식을 사용한 자원 효율적인 하이퍼파라미터 탐색
4.4. 중첩 교차 검증을 사용한 알고리즘 선택
5. 여러 가지 성능 평가 지표
5.1. 오차행렬
--> 사이킷런 ConfusionMatrixDisplay 클래스를 사용하면 오차 행렬을 쉽게 그릴 수 있음.
5.2. 분류 모델의 정밀도와 재현율 최적화
예측오차 | |
정확도 |
거짓 양성 비율(FPR) | |
진짜 양성 비율(TPR) |
재현율(REC) : 관련된 샘플(양성)을 얼마나 많이(진짜 양성으로)감지했는지 정량화 | |
정밀도(PRE) : 예측된 샘플(진짜 양성과 거짓 양성의 합) 중 실제로 관련된 샘플(진짜 양성)의 수를 정량화 |
5.5. 불균형한 클래스 다루기
--> 한 개 또는 여러 개의 클래스 샘플이 데이터셋에 너무 많을 때 클래스 불균형이 일어남.
불균형한 클래스 다루는 방법