본문 바로가기
파이썬/머신러닝-지도학습

파이썬 머신러닝 지도학습 - 앙상블 - XGBoost (분류, 회귀)

by 큰고양2 2023. 9. 17.

XGBoost

부스팅 기반의 알고리즘으로 그라디언트 부스팅 방식을 사용

결측치를 자체적으로 처리 할 수 있음

반복 실행시간에 따른 정확도를 확인하여 조기 중단이 가능

 

 

모델링

#분류
from xgboost import XGBClassifier
#회귀
from xgboost import XGBRegressor

코드로 임포트 한 다음

#분류
model = XGBClassifier(n_estimators= , max_depth= )
#회귀
model = XGBRegressor(n_estimators= , max_depth= )

로 모델을 선언한다

각각 파라미터는

  1. max_depth: 트리의 최대 깊이를 지정 (기본값 = 6)
  2. n_estimators : 만들어질 decision tree의 수 , (기본값=100)

이다 만약 기본 설정을 그대로 쓸 생각이라면 그냥 함수명()으로 선언해도 된다

학습 및 예측

model.fit(x_train, y_train)

fit매소드로 학습을 시킬 수 있다

이후

y_pred = model.predict(x_test)

코드를 사용하여 완성된 모델에 x_test를 넣어 예측값을 생성 할 수 있다

 

평가

from sklearn.metrics import *

코드로 평가 함수들을 임포트 한 다음

https://bigcat5312.tistory.com/77

 

머신러닝 지도학습 - 회귀와 분류, 분석도구

회귀(Regression) 이미 결과값이 있는 데이터를 사용하여 연관성을 찾아 연속적인 숫자를 예측해 내는 것 ex) 집값 분석도구 평가도구 LinearRegression KNeighborsRegressor DecisionTreeRegressor RandomForestRegressor XG

bigcat5312.tistory.com

게시글을 참고하여 원하는 평가함수(y_test , y_pred)를 사용해 평가 할 수 있다

 

변수 중요도 시각화

plt.figure(figsize=(6, 8))
plt.barh(list(x), model.feature_importances_)
plt.ylabel('Features')
plt.xlabel('Importances')
plt.show()

정렬해서 보기

df = pd.DataFrame()
df['feature'] = list(x)
df['importance'] = model.feature_importances_
df.sort_values(by = 'importance', ascending= True, inplace=True)

plt.barh(y= 'feature', width = 'importance', data = df)
plt.show()