brunch

You can make anything
by writing

C.S.Lewis

by 데이터파머 DataFarmer Oct 01. 2021

기계학습_앙상블 모델 학습 (ensemble)

Random Forest, adaboost, xgboost, light

이번에는 기계학습 공부를 위해 BBB (Blood Brain Basrrier) 데이터 세트 Random Forest, adaboost, xgboost, light GBM 방법으로 앙상블 학습 분석을 해보았다.


지난 회귀분석은 10년전에도 실험데이터 분석을 위해 쓰기도 했었고, 자동차 연비에 어떠한 요소가 영향은 주는지 비교 분석했던 지난 브런치 글에도 사용했었지만, 이번 앙상블 분석은 사용한바가 없는 분석이다.


바이오 전공자로 앙상블 하면 Protein, RNA, DNA 등 염기 서열을 분석하기 위해 사용한 것이었다.

앙상블 Genome 브라우저


기계학습에서 앙상블은 어떤 데이터의 값을 예측한다고 할 때, 하나의 모델이 아닌 여러 개의 모델을 조화롭게 학습시켜 그 모델들의 예측 결과들을 이용하여 더 정확한 예측값을 구할때 사용한다. 앙상블 학습은 여러 개의 결정 트리(Decision Tree)를 결합하여 하나의 결정 트리보다 더 좋은 성능을 내는 머신러닝 기법이다.


앙상블 학습의 핵심은 여러 개의 약 분류기 (Weak Classifier)를 결합하여 강 분류기(Strong Classifier)를 만드는 것이다. 그리하여 모델의 정확성이 향상된다. 앙상블 학습법에는 두 가지가 있는데 1) 배깅(Bagging)과 부스팅(Boosting)이다.


기계학습에서 앙상블 분류


글을 적어 놓고도 어렵다. 그래서 일단 무작정 예제를 보면서 중간중간 구글링을 통해 수많은 정보와 예제코드들을 통해서 코드를 작성해보았다. 중간중간 왜 저런 결과가 나오는건지 이해하면서 갔지만, 어느 순간부터는 이게 의미가 없어졌다. 그냥 손이 가는대로, 눈이 가는대로만 갔다.


누군가 얼마전에 내가 기타연주 하는 영상을 보고 이런 말을 했었다.

'처음엔 운지를 하나하나 보면서 따라가려 했지만, 어느 지점 이후에는 그냥 마음을 놔버리고 연주를 감상했다'라고..


그 사람은 감상을 했다고 하지만, 나는 어느 지점에서 관망을 해버렸다.


여튼 작성한 코드는 아래에 남겨 두고, 나중에 다시금 보게된다면 더 많은 이해를 할 수 있으리라!!!



앙상블 학습을 위한 분석 소스 코드


1.  Random Forest

## Setup

# Importing Required Libraries

import pandas as pd

from sklearn.ensemble import RandomForestClassifier  # Import Random Forest Classifier

from sklearn.model_selection import train_test_split  # Import train_test_split function

from sklearn import metrics  #Import scikit-learn metrics module for accuracy calculation


# data loading

X_train  = pd.read_csv("X_train.csv")

y_train  = pd.read_csv("y_train.csv")

X_external  = pd.read_csv("X_external.csv")

y_external  = pd.read_csv("y_external.csv")

X_train.head()

# Feature Selection

X = X_train # Features

y = y_train['BBclass'] # Target variable


# Splitting Data

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test


## Building Decision Tree Model

# Create Decision Tree classifer object

rf = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=1234)

# Train Decision Tree Classifer

rf = rf.fit(X_train, y_train)


#Predict the response for test dataset

y_pred = rf.predict(X_test)

##--- Evaluating Model

print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

print(f'Out-of-bag score estimate: {rf.oob_score_:.3}')


## Variable Importances

# Get numerical feature importances

importances = list(rf.feature_importances_)

# List of tuples with variable and importance

feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(X, importances)]

# Sort the feature importances by most important first

feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)

# Print out the feature and importances

[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances];


## Visualizations

# Import matplotlib for plotting and use magic command for Jupyter Notebooks

import matplotlib.pyplot as plt

#matplotlib inline

# Set the style

plt.style.use('fivethirtyeight')

# list of x locations for plotting

x_values = list(range(len(importances)))

# Make a bar chart

plt.figure(figsize=(50,10))

plt.bar(x_values, importances, orientation = 'vertical')

# Tick labels for x axis

plt.xticks(x_values, X, rotation='vertical')

# Axis labels and title

plt.ylabel('Importance'); plt.xlabel('Variable')

plt.title('Variable Importances')

plt.ylim(0,0.02)



2.  AdaBoos

##--- AdaBoost for Classification ---##

# evaluate adaboost algorithm for classification

from numpy import mean

from numpy import std

from sklearn.datasets import make_classification

from sklearn.model_selection import cross_val_score

from sklearn.model_selection import RepeatedStratifiedKFold

from sklearn.ensemble import AdaBoostClassifier

# define dataset

X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=6)

# define the model

model = AdaBoostClassifier()

# evaluate the model

cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)

n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')

# report performance

print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))

#Accuracy: 0.806 (0.041)

# fit the model on the whole dataset

model.fit(X, y)

# make a single prediction

row = [[-3.47224758,1.95378146,0.04875169,-0.91592588,-3.54022468,1.96405547,-7.72564954,-2.64787168,-1.81726906,-1.67104974,2.33762043,-4.30273117,0.4839841,-1.28253034,-10.6704077,-0.7641103,-3.58493721,2.07283886,0.08385173,0.91461126]]

yhat = model.predict(row)

print('Predicted Class: %d' % yhat[0])


3. xgboost

!pip install xgboost

# xgboost for classification

from numpy import asarray

from numpy import mean

from numpy import std

from sklearn.datasets import make_classification

from xgboost import XGBClassifier

from sklearn.model_selection import cross_val_score

from sklearn.model_selection import RepeatedStratifiedKFold

from matplotlib import pyplot

# define dataset

X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)

# evaluate the model

model = XGBClassifier()

cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)

n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')

print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))

# fit the model on the whole dataset

model = XGBClassifier()

model.fit(X, y)

# make a single prediction

row = [2.56999479, -0.13019997, 3.16075093, -4.35936352, -1.61271951, -1.39352057, -2.48924933, -1.93094078, 3.26130366, 2.05692145]

row = asarray(row).reshape((1, len(row)))

yhat = model.predict(row)

print('Prediction: %d' % yhat[0])


4. ligh GBM

!pip install lightgbm

##--- Light GBM for classification ---##

from numpy import mean

from numpy import std

from sklearn.datasets import make_classification

from lightgbm import LGBMClassifier

from sklearn.model_selection import cross_val_score

from sklearn.model_selection import RepeatedStratifiedKFold

from matplotlib import pyplot

# define dataset

X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)

# evaluate the model

model = LGBMClassifier()

cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)

n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')

print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))

# fit the model on the whole dataset

model = LGBMClassifier()

model.fit(X, y)

# make a single prediction

row = [[2.56999479, -0.13019997, 3.16075093, -4.35936352, -1.61271951, -1.39352057, -2.48924933, -1.93094078, 3.26130366, 2.05692145]]

yhat = model.predict(row)

print('Prediction: %d' % yhat[0])


매거진의 이전글 기계학습 Machine Learning 기초 분석
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari