35일차 머신러닝8

차지예·2025년 7월 3일

생성AI

목록 보기
29/56
post-thumbnail

신용카드 사용자 연체 예측

1. 데이터 탐색 및 가공

import pandas as pd
import numpy as np

# Google Drive 경로에서 데이터 로드
train = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/딥다이브/train.csv')
test  = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/딥다이브/test.csv')

# 데이터 미리보기
train.head()
  • train.csv : 모델 학습용
  • test.csv : 학습된 모델로 예측할 데이터

2. EDA (탐색적 데이터 분석)

# 기본 정보 확인
train.info()
print("train shape:", train.shape)

test.info()
print("test shape:", test.shape)
  • 각 컬럼의 데이터 타입, 결측치 유무, 샘플 수 등을 확인하여 데이터 구조를 파악합니다.

3. 결측치 확인 및 처리

# 결측치 개수 확인
print(train.isnull().sum())
print(test.isnull().sum())

# 결측치가 있는 'occyp_type' 컬럼은 제거
train = train.drop(['occyp_type'], axis=1)
test  = test.drop(['occyp_type'], axis=1)

# 제거 후 shape 재확인
print("after drop: train", train.shape, "test", test.shape)
  • occyp_type 컬럼의 결측치가 많아, 분석에서 제외했습니다.

4. Feature Engineering

4.1. 타깃 분리

# 예측 대상인 credit 컬럼 분리
target = train.pop('credit')

4.2. 범주형 변수 인코딩

# 문자열(object) 컬럼 확인
cols = train.select_dtypes(include='object').columns
print(cols)  # 예: ['gender', 'car', 'reality', …]

# Label encoding 적용
from sklearn.preprocessing import LabelEncoder

for col in cols:
    le = LabelEncoder()
    train[col] = le.fit_transform(train[col])
    test[col] = le.transform(test[col])

train.head()   

One-Hot Encoding대시 레이블 인코딩을 사용하여 모델 성능을 개선했습니다.


5. 모델링 및 하이퍼파라미터 튜닝

from sklearn.model_selection import train_test_split
from sklearn.ensemble      import RandomForestClassifier

# 학습/검증 데이터 분리
X_train, X_val, y_train, y_val = train_test_split(
    train, target, test_size=0.2, random_state=0
)

# RandomForest 모델 학습
rf = RandomForestClassifier(random_state=0)
rf.fit(X_train, y_train)

# 검증 세트 예측
pred  = rf.predict(X_val)
pred_proba = rf.predict_proba(X_val)  # ROC AUC 계산용

6. 평가 Metric 분석하기


# 기본 지표
accuracy  = accuracy_score(y_val, pred)
precision = precision_score(y_val, pred, average='weighted')
recall    = recall_score(y_val, pred, average='weighted')
f1        = f1_score(y_val, pred, average='weighted')


print(f"정확도 (Accuracy): {accuracy:.4f}")
print(f"정밀도 (Precision): {precision:.4f}")
print(f"재현율 (Recall): {recall:.4f}")
print(f"F1 점수 (F1 Score): {f1:.4f}")

  • Accuracy
  • Precision (가중 평균)
  • Recall (가중 평균)
  • F1 Score (가중 평균)

결론 및 다음 단계

  • 현재는 RandomForest로 기본 성능을 확인했습니다.
  • 다른 모델 (LogisticRegression, GradientBoosting 등)과 하이퍼파라미터 튜닝을 통해 성능을 향상시킬 수 있습니다.
  • Feature Engineering 단계에서 새로운 파생 feature 추가, 이상치 처리, 스케일링 등을 시도해 볼 생각이다

구체적인 코드는 깃허브

0개의 댓글