Decision Tree Model

2021. 10. 15. 22:56머신러닝

반응형

지난 포스팅(https://direction-f.tistory.com/98)에서 Regression Tree와 Classification Tree에 대한 개념을 정리하였는데, 이 개념을 바탕으로 현재 가장 활발하게 적용되고 있는 알고리즘은 CART(Classification And Regression Tree)알고리즘입니다.

CART알고리즘의 대표적인 특징은 Binary 노드로 분기된다는 것이고, 이 알고리즘은 차후 Random Forest나 Bagging/Bossting을 적용한 알고리즘에도 활용됩니다. 

지난 포스팅에서 정리했던것과 같이 Regression Tree는 실제값과 예측값이 최소화 되도록, Classfication Tree는 불순도를 최소화하도록 구역을 나누되, Classification Tree같은 경우 주로 Gini index를 주요 지표로 활용합니다. 또한 기본적으로 Geedy algorithm을 적용하여 Parameter를 최적화합니다.

먼저 Python을 활용하여 Classfication Tree를 추정해보겠습니다. 데이터는 Car Evaluation Data Set을 이용하였습니다 (https://www.kaggle.com/elikplim/car-evaluation-data-set)

import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OrdinalEncoder
import category_encoders as ce
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.datasets import make_regression
import os

## Data Load
df = pd.read_csv("car_evaluation.csv", header = None)
df.columns = ["price", "maintenance_cost", "num_door", "num_person","lug_boot","safety","class_unacc"]
df.head()
'''
   price maintenance_cost num_door num_person lug_boot safety class_unacc
0  vhigh            vhigh        2          2    small    low       unacc
1  vhigh            vhigh        2          2    small    med       unacc
2  vhigh            vhigh        2          2    small   high       unacc
3  vhigh            vhigh        2          2      med    low       unacc
4  vhigh            vhigh        2          2      med    med       unacc
'''

## Split Data Set(data/target, train/test)
X = df.drop(["class_unacc"], axis=1)
y = df["class_unacc"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 777)
X_train.shape, X_test.shape

위에서 확인할 수 있는 것처럼 데이터가 vhigh처럼 String으로 입력되어 있습니다. 이 것을 수치형변수로 변환을 해준 후 Fitting을 시키겠습니다.

## Encoding
encoder = ce.OrdinalEncoder(cols=["price", "maintenance_cost", "num_door", "num_person","lug_boot","safety"])

X_train_ord = encoder.fit_transform(X_train)
X_test_ord = encoder.transform(X_test)

# fit the model
tree_clf_gini = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=7)
tree_clf_gini.fit(X_train_ord, y_train)

## prediction
tree_clf_gini.classes_
tree_clf_gini.predict_proba(X_test_ord)
y_pred = tree_clf_gini.predict(X_test_ord)

print("accuracy:{}".format(accuracy_score(y_test, y_pred))) ## accuracy:0.840630472854641

## visualization
tree.plot_tree(tree_clf_gini.fit(X_train_ord, y_train))
plt.show()

sklearn에서 제공하는 주요 파라미터는 아래와 같습니다.

  • max_dapth : Tree가 가질 수 있는 최대 깊이
  • min_samples_split : 노드가 분할을 수행하기 위해 가져야하는 최소 샘플수
  • min_samples_leaf: 리프 노드가 가져야하는 최소 샘플수
  • max_leaf_nodes : 리프 노드의 최대 수

이제 Regression Tree를 적합해보겠습니다.

## Regression Tree
## Data Loading

X, y = make_regression(n_samples=1000, n_features=3, bias=0, noise=0, random_state=0)
X.shape
y.shape

## Fitting & Prediction

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 777)
tree_reg = DecisionTreeRegressor(max_depth = 2)
tree_reg.fit(X_train, y_train)

y_pred = tree_reg.predict(X_test)
print("MSE:{}".format(mean_squared_error(y_test, y_pred))) ##  MSE:7618.768019021607

## visualization
tree.plot_tree(tree_reg.fit(X_train, y_train))
plt.show()

반응형

'머신러닝' 카테고리의 다른 글

Decision Tree - Boosting  (1) 2022.01.02
Decision Tree - Bagging  (0) 2021.10.19
Tree-Based Model  (0) 2021.10.06
Generalized Additive Models(GAM)  (0) 2021.08.15
모델 평가 및 선정 > Bootstrap Method  (0) 2021.06.28