import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
credit_df = pd.read_csv('/content/drive/MyDrive/머신러닝과 딥러닝/data/credit.csv')
pd.set_option('display.max_columns',50)
credit_df.info()
lightGBM을 사용해보기 위해 데이터를 불러옵니다
컬럼은 50개까지 출력되도록 설정하고 구성을 확인해줍니다
# 불필요한 컬럼 삭제
credit_df.drop(['ID','Customer_ID','Name','SSN'], axis=1, inplace=True)
# Credit_Score 컬럼 내의 데이터 수정
credit_df['Credit_Score'] = credit_df['Credit_Score'].replace({'Poor':0,'Standard':1,'Good':2})
# _ 가 있는 데이터를 보유하고 있는 컬럼들의 데이터를 수정
for i in ['Age', 'Annual_Income','Num_of_Loan','Outstanding_Debt', 'Num_of_Delayed_Payment','Amount_invested_monthly']:
credit_df[i] = pd.to_numeric(credit_df[i].str.replace('_',''))
# Credit_History_Age의 데이터를 개월로 변경
# 22 Years and 1 Months -> 22 * 12 + 1
Test = []
for i in credit_df['Credit_History_Age']:
i = str(i)
if i == 'nan':
pass
else:
test=i.split()
test2=int(test[0])*12+int(test[3])
Test.append(test2)
credit_df['Credit_History_Age'] = credit_df['Credit_History_Age'].str.replace(' Months','')
credit_df['Credit_History_Age'] = pd.to_numeric(credit_df['Credit_History_Age'].str.split(' Years and ', expand=True)[0]) * 12 + pd.to_numeric(credit_df['Credit_History_Age'].str.split(' Years and ', expand=True)[1])
# Age 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[credit_df['Age'] >= 0]
credit_df = credit_df[credit_df['Age'] < 110]
# Num_Bank_Accounts 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[credit_df['Num_Bank_Accounts'] <= 10]
# Num_Credit_Card 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[credit_df['Num_Credit_Card'] <= 20]
# Interest_Rate 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[credit_df['Interest_Rate'] <= 40]
# Num_of_Loan 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[(credit_df['Num_of_Loan'] <= 10) & (credit_df['Num_of_Loan'] >= 0)]
# Delay_from_due_date 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[credit_df['Delay_from_due_date'] >= 0]
# Num_of_Delayed_Payment 컬럼 내의 정상적이지 않은 데이터 제외
credit_df = credit_df[(credit_df['Num_of_Delayed_Payment'] >= 0) &(credit_df['Num_of_Delayed_Payment'] <= 30)]
# Num_Credit_Inquiries 컬럼 내의 결측값을 0으로 변환
credit_df['Num_Credit_Inquiries'] = credit_df['Num_Credit_Inquiries'].fillna(0)
# credit_df 데이터 프레임 내의 모든 열에 대해 각 열의 결측값을 중간값으로 변환
credit_df = credit_df.fillna(credit_df.median())
# Type_of_Loan 컬럼 내의 데이터 수정 및 결측값을 No Loan으로 변환
credit_df['Type_of_Loan'] =credit_df['Type_of_Loan'].str.replace('and ','')
credit_df['Type_of_Loan'] =credit_df['Type_of_Loan'].fillna('No Loan')
2. lightGBM(LGBM)
Microsoft에서 개발한 Gradient Boosting Framework
리프 중심 히스토그램 기반 알고리즘
GBM(Gradient Boosting Model) : 모델1을 통해 y를 예측하고, 모델2에 데이터를 넣어 y를 예측, 모델3에 넣어 y를 예측하는 방식
작은 데이터셋에서도 높은 성능을 보이며, 특히 대용량 데이터셋에서 다른 Gradient Boosting 알고리즘보다 빠르게 학습
메모리 사용량이 상대적으로 적은편
적은 데이터셋을 사용할 경우 과적합 가능성이 매우 큼(일반적으로 데이터가 10,000개 이상은 사용해야 함)
조기 중단(early stopping)을 지원
2-1. 리프 중심 히스토그램 기반 알고리즘
트리를 균형적으로 분할하는 것이 아니라, 최대한 불균형하게 분할
특성들의 분포를 히스토그램으로 나타내고, 해당 히스토그램을 이용하여 빠르게 후보 분할 기준을 선택
후보 분할 기준 중에서 최적의 분할 기준을 선택하기 위해, 데이터 포인트들을 히스토그램에 올바르게 배치하고, 이용하여 최적의 분할 기준을 선택
from sklearn.model_selection import train_test_split
from lightgbm import LGBMClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score
X_train, X_test, y_train, y_test = train_test_split(credit_df.drop('Credit_Score', axis=1), credit_df['Credit_Score'], test_size=0.2, random_state=2023)
X_train.shape, y_train.shape
# 결과 : ((8003, 51), (8003,))
X_test.shape, y_test.shape
# 결과 : ((2001, 51), (2001,))
base_model = LGBMClassifier(random_state=2023)
base_model.fit(X_train, y_train)
pred = base_model.predict(X_test)
accuracy_score(y_test, pred)
# 결과 : 0.7251374312843578
confusion_matrix(y_test, pred)
# 결과 : array([[409, 144, 25], [154, 855, 108], [ 4, 115, 187]])
proba = base_model.predict_proba(X_test)
roc_auc_score(y_test, proba, multi_class='ovr')
# 결과 : 0.8932634160489487