본문 바로가기
프로그래밍/머신러닝

결정 트리(Decision Tree)_파이썬으로 머신러닝 배우기

by 조크리 2021. 5. 3.
반응형

결정 트리(Decision Tree)

 

 

1. 결정 트리(Decision Tree)알아보기 

 

결정 트리는

데이터를 분석하여 이들 사이에 존재하는 패턴을 예측 가능한 규칙들의 조합으로 나타내며, 그 모양이 ‘나무’와 같다고 해서 의사결정나무라 불린다.

 

질문을 던져서 대상을 좁혀나가는 ‘스무고개’ 놀이와 비슷하다고 볼 수 있다. 

 

 

결정 트리(Decision Tree)는 분류와 회귀에 사용된다. 

 

분류 기준이 변수 값이 된다. 

 

성별 = 남자, 여자 

안경 = 썼다, 안썻다

일처리 = 천천히, 빠르게

 

등등이 있고 아래 그림처럼 분류 기준에 따라 나누어진다. 

출처 https://ratsgo.github.io/machine%20learning/2017/03/26/tree/

 

2. 정보 획득 이론

 

정보 획득 이론이란 

같은 성질의 것은 증가시키고 다른 성질의 것은 줄이는 것을 의미한다. 

 

엔트로피가 크면 이질성이 크다는 것을 의미하는데 엔트로피가 큰 분류 기준으로 먼저 분류하는 것이 매우 중요하다. 

 

출처 https://frontjang.info/entry/Entropy%EC%99%80-Information-Gain

 

3. 인자 조절

 

max_depth

splitter{'best', 'random'}, default = 'best'

max_features

int, float or {'auto', 'sqrt', 'log2'}, default = None

 

import matplotlib.pyplot as plot
import numpy as np
import math

x = np.random.rand(100,1)
x = x * 10 - 5

y = np.array([math.sin(i) for i in x])
y = y + np.random.randn(100)

from sklearn.tree import DecisionTreeRegressor
for i in range(1, 50, 1):
  model = DecisionTreeRegressor()
  model.fit(x, y)
  relation_square = model.score(x, y)
  print('결정계수 R : ', relation_square)

y_p = model.predict(x)

plot.scatter(x, y, marker = 'x')
plot.scatter(x, y_p, marker = 'o')
plot.show()

 

4. 수학으로 총점 예측

 

import matplotlib.pyplot as plot
import numpy as np
import math
import pandas as pd
import seaborn as sns
import openpyxl
plot.rcParams["font.family"] = 'Malgun gothic'

data = pd.read_excel('student.xlsx', header = 0)

newData = data[['kor', 'eng', 'math', 'social', 'science', 'total']]
#속성(변수)선택
x = newData[['math']]
y = newData[['total']]

from sklearn.tree import DecisionTreeRegressor
for i in range(1, 50, 1):
  model = DecisionTreeRegressor(max_depth = i)
  model.fit(x, y)
  relation_square = model.score(x, y)
  print('결정계수 R : ', relation_square)

y_p = model.predict(x)

plot.scatter(x, y, marker = 'x')
plot.scatter(x, y_p, marker = 'o')
plot.show()

 

max_depth가 1,2,3,4,5,6까지는 결정계수가 늘어나지만 7부터는 결정계수가 0.9005395로 같다. 

 

 

5. 국, 수, 사, 영어 점수로 총점 예측

 

import matplotlib.pyplot as plot
import numpy as np
import math
import pandas as pd
import seaborn as sns
import openpyxl
plot.rcParams["font.family"] = 'Malgun gothic'

data = pd.read_excel('student.xlsx', header = 0)

newData = data[['kor', 'eng', 'math', 'social', 'science', 'total']]
#속성(변수)선택
x = newData[['kor', 'eng', 'math', 'social']]
y = newData[['total']]

from sklearn.tree import DecisionTreeRegressor
for i in range(1, 50, 1):
  model = DecisionTreeRegressor(max_depth = i)
  model.fit(x, y)
  relation_square = model.score(x, y)
  print('결정계수 R : ', relation_square)

y_p = model.predict(x)

ax1 = sns.distplot(y, hist = False, label = 'y_실제')
ax2 = sns.distplot(y_p, hist = False, label = 'y_예측')

plot.show()

 

국, 수, 사, 영으로 총점을 예측할 때에는 max_depth가 1,2,3,4,5,6,7일때까지 쭉 늘어나다가

max_depth가8이 되자 결정계수가 1이 되었다. 

 

 

반응형