-
Python 데이터분석 기초 64 - XGBoost로 분류 모델 작성, lightgbm로 분류 모델 작성Python 데이터 분석 2022. 11. 23. 10:57
XGBoost로 분류 모델 작성
breast_cancer dataset 사용
pip install xgboost
pip install lightgbm아나콘다에 install 한다.
# XGBoost로 분류 모델 작성 # breast_cancer dataset 사용 # pip install xgboost # pip install lightgbm import pandas as pd import numpy as np from sklearn.datasets import load_breast_cancer import xgboost as xgb from sklearn.model_selection import train_test_split from lightgbm import LGBMClassifier # xgboost 보다 성능이 우수하다. 대용량 처리에 효과적. 데이터가 적으면 과적합 발생 우려가 매우 높다. from xgboost import plot_importance import matplotlib.pyplot as plt dataset = load_breast_cancer() x_feature = dataset.data y_label = dataset.target cancer_df = pd.DataFrame(data=x_feature, columns=dataset.feature_names) print(cancer_df.head(2), cancer_df.shape) # (569, 30) print(dataset.target_names) # ['malignant':양성 'benign':음성] print(np.sum(y_label == 0)) # 양성 : 212 print(np.sum(y_label == 1)) # 음성 : 357 x_train, x_test, y_train, y_test = train_test_split(x_feature, y_label, test_size = 0.2, random_state = 12) print(x_train.shape, x_test.shape, y_train.shape, y_test.shape) # (455, 30) (114, 30) (455,) (114,) # model model = xgb.XGBClassifier(booster = 'gbtree', max_depth = 6, n_estimators = 500).fit(x_train, y_train) # 의사결정 기반(booster) # model = LGBMClassifier().fit(x_train, y_train) # print(model) pred = model.predict(x_test) print('예측값 :', pred[:10]) print('실제값 :', y_test[:10]) print('정확도 확인 방법 1') from sklearn import metrics acc = metrics.accuracy_score(y_test, pred) print('acc :', acc) print('정확도 확인 방법 2') cl_rep = metrics.classification_report(y_test, pred) print('classification_report : \n', cl_rep) # 중요 변수 시각화 fig, ax = plt.subplots(figsize=(10, 12)) plot_importance(model, ax = ax) plt.show() <console> mean radius mean texture ... worst symmetry worst fractal dimension 0 17.99 10.38 ... 0.4601 0.11890 1 20.57 17.77 ... 0.2750 0.08902 [2 rows x 30 columns] (569, 30) ['malignant' 'benign'] 212 357 (455, 30) (114, 30) (455,) (114,) 예측값 : [0 1 1 1 1 1 1 1 1 0] 실제값 : [0 1 1 1 1 1 0 1 1 0] 정확도 확인 방법 1 acc : 0.9473684210526315 정확도 확인 방법 2 classification_report : precision recall f1-score support 0 0.98 0.90 0.93 48 1 0.93 0.98 0.96 66 accuracy 0.95 114 macro avg 0.95 0.94 0.95 114 weighted avg 0.95 0.95 0.95 114
중요 변수 시각화 column 명이 f로 되어있는데 뒤의 숫자 순서대로 column 순서가 된다.
'Python 데이터 분석' 카테고리의 다른 글
XGBoost로 분류 모델 예시(kaggle.com이 제공하는 'glass datasets') (0) 2022.11.23 XGBoost로 분류 모델 예시(산탄데르 은행 고객 만족 여부 분류 모델) (0) 2022.11.23 Python 데이터분석 기초 63 - DecisionTreeRegressor, RandomForestRegressor (0) 2022.11.23 RandomForest 예제 2 - django를 활용(patient 데이터 사용) (0) 2022.11.22 RandomForest 예제 1 - Red Wine quality 데이터 (0) 2022.11.22