머신 러닝 (23) Adaboost Classfication
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report
print("Loading Pima Indians Diabetes Dataset...")
pima = fetch_openml(name='diabetes', version=1, as_frame=True)
X = pima.data
y = pima.target.map({'tested_negative': 0, 'tested_positive': 1}).astype(int)
print(f"데이터 크기: {X.shape}")
print(f"피처 목록: {list(X.columns)}")
print(f"\n클래스 분포:\n{y.value_counts()}")
# 데이터 샘플
print("\n데이터 샘플:")
print(X.head())
print("\n기술 통계:")
print(X.describe())
# 데이터 분리 (stratify로 클래스 비율 유지)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"Train: {X_train.shape}, Test: {X_test.shape}")
print(f"\nTrain 클래스 분포:\n{y_train.value_counts()}")
# AdaBoost Classifier
# estimator: max_depth=1인 Decision Tree (Decision Stump)
ada_clf = AdaBoostClassifier(
estimator=DecisionTreeClassifier(max_depth=1),
random_state=42
)
# 하이퍼파라미터 그리드
param_grid = {
'n_estimators': [50, 100, 200],
'learning_rate': [0.01, 0.1, 1.0, 1.5]
}
print("파라미터 그리드:")
for param, values in param_grid.items():
print(f" {param}: {values}")
total_combinations = 1
for values in param_grid.values():
total_combinations *= len(values)
print(f"\n총 조합 수: {total_combinations}개")
# GridSearchCV
print("\nTuning AdaBoost Classifier...")
print("(교차검증 수행 중...)\n")
grid_clf = GridSearchCV(
ada_clf, #AdaBoost Model or Pipeline
param_grid,
cv=StratifiedKFold(5),
scoring='accuracy',
n_jobs=-1,
verbose=5
)
grid_clf.fit(X_train, y_train)
print("\nGridSearchCV 완료!")
# 최적 모델 추출
best_clf = grid_clf.best_estimator_
print("[최적화 결과]")
print(f"Best Accuracy (Train CV): {grid_clf.best_score_:.4f}")
print(f"\nBest Parameters:")
for param, value in grid_clf.best_params_.items():
print(f" {param}: {value}")
# 상위 5개 결과
cv_results = pd.DataFrame(grid_clf.cv_results_)
top_results = cv_results.nlargest(5, 'mean_test_score')[[
'param_n_estimators',
'param_learning_rate',
'mean_test_score',
'std_test_score'
]]
print("\n상위 5개 파라미터 조합:")
print(top_results.to_string(index=False))
# 테스트 데이터 예측
y_pred = best_clf.predict(X_test)
test_accuracy = accuracy_score(y_test, y_pred)
print(f"Test Accuracy: {test_accuracy:.4f}")
print("\n--- Classification Report ---")
print(classification_report(y_test, y_pred))
from sklearn.metrics import confusion_matrix
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6, 4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['No Diabetes', 'Diabetes'],
yticklabels=['No Diabetes', 'Diabetes'])
plt.title('Confusion Matrix')
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.tight_layout()
plt.show()
# 피처 중요도 추출
importances = best_clf.feature_importances_
feature_names = X.columns
indices = np.argsort(importances)[::-1]
# 중요도 정렬
importance_df = pd.DataFrame({
'Feature': feature_names[indices],
'Importance': importances[indices]
})
print("\n피처 중요도 순위:")
print(importance_df.to_string(index=False))
# 피처 중요도 시각화
plt.figure(figsize=(6, 4))
sns.barplot(x=importances[indices], y=feature_names[indices], palette='viridis')
plt.title("Feature Importances (AdaBoost Classifier)")
plt.xlabel("Importance")
plt.ylabel("Features")
plt.tight_layout()
plt.show()
from sklearn.ensemble import RandomForestClassifier
# Random Forest
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
rf_clf.fit(X_train, y_train)
y_pred_rf = rf_clf.predict(X_test)
accuracy_rf = accuracy_score(y_test, y_pred_rf)
# 비교
print("\n앙상블 모델 비교:")
print(f"AdaBoost: Accuracy = {test_accuracy:.4f}")
print(f"Random Forest: Accuracy = {accuracy_rf:.4f}")
print(f"\n차이: {test_accuracy - accuracy_rf:+.4f}")
# learning_rate별 성능
learning_rates = [0.01, 0.1, 0.5, 1.0, 1.5, 2.0]
scores = []
best_n_estimators = grid_clf.best_params_['n_estimators']
for lr in learning_rates:
ada = AdaBoostClassifier(
estimator=DecisionTreeClassifier(max_depth=1),
n_estimators=best_n_estimators,
learning_rate=lr,
random_state=42
)
ada.fit(X_train, y_train)
score = ada.score(X_test, y_test)
scores.append(score)
# 시각화
plt.figure(figsize=(10, 6))
plt.plot(learning_rates, scores, marker='o', linewidth=2, markersize=10)
plt.xlabel('Learning Rate')
plt.ylabel('Test Accuracy')
plt.title(f'Learning Rate vs Accuracy (n_estimators={best_n_estimators})')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
print("\nLearning Rate별 성능:")
for lr, score in zip(learning_rates, scores):
print(f" LR={lr:.2f}: {score:.4f}")
# n_estimators별 성능
n_estimators_range = range(10, 210, 10)
train_scores = []
test_scores = []
best_lr = grid_clf.best_params_['learning_rate']
for n_est in n_estimators_range:
ada = AdaBoostClassifier(
estimator=DecisionTreeClassifier(max_depth=1),
n_estimators=n_est,
learning_rate=best_lr,
random_state=42
)
ada.fit(X_train, y_train)
train_scores.append(ada.score(X_train, y_train))
test_scores.append(ada.score(X_test, y_test))
# 시각화
plt.figure(figsize=(6, 4))
plt.plot(n_estimators_range, train_scores, label='Training Score', marker='o')
plt.plot(n_estimators_range, test_scores, label='Test Score', marker='s')
plt.xlabel('Number of Estimators')
plt.ylabel('Accuracy')
plt.title(f'Number of Estimators vs Accuracy (learning_rate={best_lr})')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
댓글
댓글 쓰기