PyCaret 설치

!pip install pycaret

Google Colab 사용자의 경우 다음의 코드를 실행합니다.

from pycaret.utils import enable_colab

enable_colab()

필요한 모듈 import

import pandas as pd
import numpy as np
import seaborn as sns

pd.options.display.max_columns = None

실습을 위한 데이터셋 로드

from pycaret.datasets import get_data
dataset = get_data('diamond')
# 데이터셋 크기 출력
dataset.shape
train = dataset.sample(frac=0.8, random_state=123)
test = dataset.drop(train.index)
train.reset_index(inplace=True, drop=True)
test.reset_index(inplace=True, drop=True)

print('학습용 데이터셋: ' + str(train.shape))
print('예측용 데이터셋: ' + str(test.shape))

설정: setup()

머신러닝 예측 방식에 따라 다음 중 하나를 골라 import 합니다.

from pycaret.regression import *        # 회귀

setup 함수

  • data: 학습할 데이터셋을 지정합니다.
  • target: 예측할 대상(target) 컬럼을 지정합니다.
  • session_id: SEED 값을 지정합니다.
train.head(3)
clf = setup(data=train, 
            target='Price', 
            session_id=123, 
            verbose=False,
            ) 

데이터 전처리

문서 링크

remove_multicollinearity / multicollinearity_threshold

다중 공선성 문제가 발생할 수 있는 컬럼을 제거합니다.

clf = setup(data=train, 
            target='Price', 
            session_id=123, 
            remove_multicollinearity=True,      # collinearity 제거
            multicollinearity_threshold = 0.95, # collinearity 제거 임계치
            verbose=False,
            ) 

bin_numeric_features

binning을 적용할 컬럼을 선택합니다.

clf = setup(data=train, 
            target='Price', 
            session_id=123, 
            remove_multicollinearity=True,        # collinearity 제거
            multicollinearity_threshold=0.95,     # collinearity 제거 임계치
            bin_numeric_features=['Carat Weight'],
            verbose=False,
            ) 

transformation / transform_target

clf = setup(data=train, 
            target='Price', 
            session_id=123, 
            remove_multicollinearity=True,        # collinearity 제거
            multicollinearity_threshold=0.95,     # collinearity 제거 임계치
            bin_numeric_features=['Carat Weight'],
            normalize=True, 
            transformation=True, 
            transform_target=True, 
            verbose=False,
            ) 

모든 모델에 대한 학습 compare_models()

compare_models - sort: 정렬 기준이 되는 평가지표를 설정합니다. - n_select: 상위 N개의 알고리즘을 선택합니다. - fold: Cross Validation 평가 Fold의 개수를 지정합니다. - round: 결과를 소수 N째자리 까지 반올림하여 표기합니다.

best_models = compare_models(n_select=3, fold=5, round=2)

모델 블렌딩 blend_models

  • compare_models로 추출된 best 모델에 대하여 모델 블렌딩하여 성능 개선
  • Soft voting 방식으로 estimator_list에 적용된 모델을 앙상블
  • Voting Ensemble
blended_models = blend_models(best_models, fold=5)

단일 모델 생성 create_models() / 앙상블 ensemble_models()

단일 모델을 생성하기 위해서는 create_model로 생성할 수 있습니다.

models()
dt = create_model('dt')
ensembled_models = ensemble_model(dt, method='Bagging')
ensembled_models = ensemble_model(dt, method='Boosting')

모델 튜닝: tune_model()

lasso = create_model('lasso', fold=5)

RandomizedSearchCV를 활용하여 하이퍼 파라미터를 튜닝합니다.

  • n_iter에 횟수를 늘리거나 줄여서 시도할 횟수를 지정할 수 있습니다.
tuned_models = tune_model(dt, fold=5, n_iter=50, round=2)

모델 예측: predict_model()

  • Label에 예측된 결과를 확인할 수 있습니다.
  • Score에 예측된 결과의 확률 값을 확인할 수 있습니다.
prediction = predict_model(data=test, estimator=ensembled_models)

모델 분석: interpret_model()

특성 중요도 Feature Importances

각 특성별 종속변수(Y)에 미치는 영향도를 계산

plot_model(dt, plot='feature')