머신 러닝 (9) 분류 데이터 증강

 import numpy as np

import pandas as pd
import matplotlib.pyplot as plt
import koreanize_matplotlib
import seaborn as sns
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from imblearn.over_sampling import SMOTE
import warnings
warnings.filterwarnings('ignore')

pima_columns = ['pregnancies', 'glucose', 'blood_pressure', 'skin_thickness', 'insulin', 'bmi', 'diabetes_pedigree_function', 'age', 'outcome']
pima_data_url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv'
df = pd.read_csv(pima_data_url, names=pima_columns)

# 타겟 변수(outcome)의 클래스 불균형 확인
print(df['outcome'].value_counts())
print(df['outcome'].value_counts(normalize=True))

# 시각화(SMOTE 적용 전 클래스 분포)
plt.figure(figsize=(3, 3))
sns.countplot(x='outcome', data=df, palette='pastel')
plt.title('SMOTE 적용 전 클래스 분포')
plt.show()

# Feature(X)와 Target(y) 분리
X = df.drop('outcome', axis=1)
y = df['outcome']

# 학습용/테스트용 데이터 분할 (8:2)
# stratify=y: 타겟 변수의 클래스 비율을 유지하며 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

print(f"학습 데이터: {X_train.shape}")
print(f"테스트 데이터: {X_test.shape}")

smote = SMOTE(random_state=42)

# 학습 데이터에만 SMOTE 적용
X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)

# 결과 확인
print("\n[SMOTE 적용 전 학습 데이터 분포]")
print(y_train.value_counts())

print("\n[SMOTE 적용 후 학습 데이터 분포]")
print(y_train_resampled.value_counts())

# 4-1. 원본 데이터로 학습한 모델
model_orig = LogisticRegression(max_iter=1000, random_state=42)
model_orig.fit(X_train, y_train)
y_pred_orig = model_orig.predict(X_test)

# 4-2. SMOTE 데이터로 학습한 모델
model_smote = LogisticRegression(max_iter=1000, random_state=42)
model_smote.fit(X_train_resampled, y_train_resampled)
y_pred_smote = model_smote.predict(X_test)

# 평가 결과 출력
print("\n[1] 원본 데이터 학습 결과")
print(classification_report(y_test, y_pred_orig))

print("\n[2] SMOTE 적용 데이터 학습 결과")
print(classification_report(y_test, y_pred_smote))

댓글

이 블로그의 인기 게시물

베이스 캠프에서 (1)

베이스 캠프에서 (2)

Database 분석 (4)