반응형

@notepad_jj2

츄르사려고 코딩하는 코집사입니다.


 

Decision Tree
In [1]:
#라이브러리 불러오기 
import pandas as pd 
import os
import numpy as np

#랜덤포레스트 라이브러리
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
import warnings

import pydotplus
from IPython.display import Image
from sklearn import tree

import statsmodels.api as sm

import matplotlib.pyplot as plt

warnings.filterwarnings('ignore')
In [2]:
from matplotlib import font_manager, rc

#plot 한글 깨짐
plt.rc('font', family='Malgun Gothic')

#막대그래프 한글 깨짐
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
In [5]:
최종데이터 = pd.read_csv('C:/Users/User/Desktop/바탕화면/AI data/AI_철새도래지_최종데이터.csv', encoding='euc-kr')
In [6]:
최종데이터
Out[6]:
발생여부 발생연도 발생월 축종 평균기온 최저기온 최고기온 평균풍속 평균상대습도 일교차 철새도래지거리
0 1 충청남도 2018 3 5.6 -2.9 14.4 1.5 58.8 17.3 8.58
1 1 경기도 2018 3 5.5 -0.3 9.4 3.5 67.6 9.7 8.97
2 1 경기도 2018 3 4.8 -1.0 10.3 2.7 57.5 11.3 1.37
3 1 충청북도 2018 3 오리 12.2 7.8 14.8 0.8 90.8 7.0 22.03
4 1 충청남도 2018 2 -5.8 -14.6 3.2 0.8 55.3 17.8 3.02
... ... ... ... ... ... ... ... ... ... ... ... ...
5514 0 경상북도 2017 4 15.9 9.2 23.2 3.9 62.6 14.0 17.99
5515 0 경상북도 2012 7 24.1 20.8 28.3 2.4 83.9 7.5 27.53
5516 0 경상북도 2014 1 -0.2 -6.4 5.7 2.8 48.4 12.1 41.31
5517 0 경상북도 2014 6 21.7 16.3 29.2 1.8 71.9 12.9 23.23
5518 0 경상북도 2012 9 20.8 18.7 23.9 5.9 80.6 5.2 15.72

5519 rows × 12 columns

In [9]:
variables = 최종데이터.columns[5:12].tolist() ## 설명 변수 리스트
 
y = 최종데이터['발생여부'] ## 반응 변수
selected_variables = variables ## 초기에는 모든 변수가 선택된 상태
sl_remove = 0.05
 
sv_per_step = [] ## 각 스텝별로 선택된 변수들
adjusted_r_squared = [] ## 각 스텝별 수정된 결정계수
steps = [] ## 스텝
step = 0
while len(variables) > 0:
    X = sm.add_constant(최종데이터[selected_variables])
    p_vals = sm.OLS(y,X).fit().pvalues[1:]
    max_pval = p_vals.max() ## 최대 p-value
    if max_pval >= sl_remove: ## 최대 p-value값이 기준값보다 크거나 같으면 제외
        remove_variable = p_vals.idxmax()
        selected_variables.remove(remove_variable)
        
        step += 1
        steps.append(step)
        adj_r_squared = sm.OLS(y,sm.add_constant(최종데이터[selected_variables])).fit().rsquared_adj
        adjusted_r_squared.append(adj_r_squared)
        sv_per_step.append(selected_variables.copy())
    else:
        break
In [10]:
selected_variables
Out[10]:
['평균기온', '평균풍속', '평균상대습도', '철새도래지거리']
In [11]:
최종데이터_Target = 최종데이터['발생여부']
In [12]:
최종데이터_Data = 최종데이터[['평균기온','평균풍속','평균상대습도','철새도래지거리']]
In [13]:
Decision_Tree = DecisionTreeClassifier(random_state=200)
In [14]:
X_train, X_test, y_train, y_test = train_test_split(최종데이터_Data, 최종데이터_Target, test_size=0.2, random_state=10, shuffle = True)
In [15]:
Decision_Tree.fit(X_train, y_train)
Out[15]:
DecisionTreeClassifier(random_state=200)
In [16]:
np.where(np.isnan(y_train))
Out[16]:
(array([], dtype=int64),)
In [21]:
print("Test Set Score : {:.2f}".format(Decision_Tree.score(X_test, y_test)))
Test Set Score : 0.83
In [18]:
Decision_Tree_Prediction = Decision_Tree.predict(X_test)
In [19]:
a = list(y_test)
In [20]:
fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(a[:200], marker='o', color='blue', label='실제값')
chart.plot(Decision_Tree_Prediction[:200], marker='^', color='red', label='예측값')
chart.set_title('Decision Tree 예측 결과', size=30)
plt.xlabel('횟수', size=20)
plt.ylabel('발생여부', size=20)
plt.legend(loc = 'best')
Out[20]:
<matplotlib.legend.Legend at 0x241b5458b80>
In [ ]:
 
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기