반응형

@notepad_jj2

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


 

분석
In [55]:
#라이브러리 불러오기 
import pandas as pd 
import os
import numpy as np

#폰트 깨짐 방지 라이브러리
from matplotlib import font_manager, rc

#Train, Test split
from sklearn.model_selection import train_test_split

#DecisionTree 라이브러리
from sklearn.tree import DecisionTreeClassifier

#랜덤포레스트 라이브러리
from sklearn.ensemble import RandomForestClassifier

#SVM 라이브러리
from sklearn.svm import SVC

#KNN 라이브러리
from sklearn.neighbors import KNeighborsClassifier

#AdaBoost 라이브러리
from sklearn.ensemble import AdaBoostClassifier

#시각화 라이브러리
import matplotlib.pyplot as plt
import seaborn as sns

import warnings
warnings.filterwarnings('ignore')
In [56]:
#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 [57]:
최종데이터 = pd.read_csv('C:/Users/User/Desktop/바탕화면/AI data/AI_철새도래지_최종데이터.csv', encoding='euc-kr')
In [58]:
#데이터프레임 더미화
최종데이터 = pd.get_dummies(최종데이터)
In [59]:
최종데이터
Out[59]:
발생여부 발생연도 발생월 평균기온 최저기온 최고기온 평균풍속 평균상대습도 일교차 철새도래지거리 ... 도_세종특별자치시 도_울산광역시 도_인천광역시 도_전라남도 도_전라북도 도_제주도 도_충청남도 도_충청북도 축종_닭 축종_오리
0 1 2018 3 5.6 -2.9 14.4 1.5 58.8 17.3 8.58 ... 0 0 0 0 0 0 1 0 1 0
1 1 2018 3 5.5 -0.3 9.4 3.5 67.6 9.7 8.97 ... 0 0 0 0 0 0 0 0 1 0
2 1 2018 3 4.8 -1.0 10.3 2.7 57.5 11.3 1.37 ... 0 0 0 0 0 0 0 0 1 0
3 1 2018 3 12.2 7.8 14.8 0.8 90.8 7.0 22.03 ... 0 0 0 0 0 0 0 1 0 1
4 1 2018 2 -5.8 -14.6 3.2 0.8 55.3 17.8 3.02 ... 0 0 0 0 0 0 1 0 1 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
5514 0 2017 4 15.9 9.2 23.2 3.9 62.6 14.0 17.99 ... 0 0 0 0 0 0 0 0 1 0
5515 0 2012 7 24.1 20.8 28.3 2.4 83.9 7.5 27.53 ... 0 0 0 0 0 0 0 0 1 0
5516 0 2014 1 -0.2 -6.4 5.7 2.8 48.4 12.1 41.31 ... 0 0 0 0 0 0 0 0 1 0
5517 0 2014 6 21.7 16.3 29.2 1.8 71.9 12.9 23.23 ... 0 0 0 0 0 0 0 0 1 0
5518 0 2012 9 20.8 18.7 23.9 5.9 80.6 5.2 15.72 ... 0 0 0 0 0 0 0 0 1 0

5519 rows × 28 columns

In [60]:
최종데이터.columns
Out[60]:
Index(['발생여부', '발생연도', '발생월', '평균기온', '최저기온', '최고기온', '평균풍속', '평균상대습도', '일교차',
       '철새도래지거리', '도_강원도', '도_경기도', '도_경상남도', '도_경상북도', '도_광주광역시', '도_대구광역시',
       '도_부산광역시', '도_서울특별시', '도_세종특별자치시', '도_울산광역시', '도_인천광역시', '도_전라남도',
       '도_전라북도', '도_제주도', '도_충청남도', '도_충청북도', '축종_닭', '축종_오리'],
      dtype='object')
In [61]:
#반응변수
최종데이터_Target = 최종데이터['발생여부']

#설명변수 -> stepwise로 변수 선별
최종데이터_Data = 최종데이터[['평균기온','평균풍속','축종_닭','평균상대습도','철새도래지거리']]
In [62]:
#Train, Test Split
#Train : Test = 0.8 : 0.2
X_train, X_test, Y_train, Y_test = train_test_split(최종데이터_Data, 최종데이터_Target, test_size = 0.2, random_state = 10, shuffle = True) 
In [63]:
#실제값
실제값 = list(Y_test)
In [64]:
#Random Forest 모델링

RF = RandomForestClassifier()
RF.fit(X_train, Y_train)
print("Test Set Score : {:.2f}".format(RF.score(X_test, Y_test)))
RF_Prediction = RF.predict(X_test)
RF_Score = RF.score(X_test, Y_test)
Test Set Score : 0.89
In [65]:
#Random Forest 실제값/예측값 그래프

fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(실제값[:200], marker='o', color='blue', label='실제값')
chart.plot(RF_Prediction[:200], marker='^', color='red', label='예측값')
chart.set_title('Random Forest 예측 결과', size=30)
plt.xlabel('횟수', size=20)
plt.ylabel('발생여부', size=20)
plt.legend(loc = 'best')
Out[65]:
<matplotlib.legend.Legend at 0x14b336c8640>
In [66]:
#SVM 모델링

SVM = SVC(kernel = 'rbf', C=8, gamma=0.1)
SVM.fit(X_train, Y_train)
print("Test Set Score : {:.2f}".format(SVM.score(X_test, Y_test)))
SVM_Prediction = SVM.predict(X_test)
SVM_Score = SVM.score(X_test, Y_test)
Test Set Score : 0.85
In [67]:
#SVM 실제값/예측값 그래프

fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(실제값[:200], marker='o', color='blue', label='실제값')
chart.plot(SVM_Prediction[:200], marker='^', color='red', label='예측값')
chart.set_title('SVM 예측 결과', size=30)
plt.xlabel('횟수', size=20)
plt.ylabel('발생여부', size=20)
plt.legend(loc = 'best')
Out[67]:
<matplotlib.legend.Legend at 0x14b3372c670>
In [68]:
#KNN 모델링

KNN = KNeighborsClassifier(n_neighbors = 3)
KNN.fit(X_train, Y_train)
print("Test Set Score : {:.2f}".format(KNN.score(X_test, Y_test)))
KNN_Prediction = KNN.predict(X_test)
KNN_Score = KNN.score(X_test, Y_test)
Test Set Score : 0.85
In [69]:
#KNN 실제값/예측값 그래프

fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(실제값[:200], marker='o', color='blue', label='실제값')
chart.plot(KNN_Prediction[:200], marker='^', color='red', label='예측값')
chart.set_title('KNN 예측 결과', size=30)
plt.xlabel('횟수', size=20)
plt.ylabel('발생여부', size=20)
plt.legend(loc = 'best')
Out[69]:
<matplotlib.legend.Legend at 0x14b34a00910>
In [70]:
#AdaBoost 모델링

AdaBoost = AdaBoostClassifier()
AdaBoost.fit(X_train, Y_train)
print("Test Set Score : {:.2f}".format(AdaBoost.score(X_test, Y_test)))
AdaBoost_Prediction = AdaBoost.predict(X_test)
AdaBoost_Score = AdaBoost.score(X_test, Y_test)
Test Set Score : 0.87
In [71]:
#AdaBoost 실제값/예측값 그래프

fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(실제값[:200], marker='o', color='blue', label='실제값')
chart.plot(AdaBoost_Prediction[:200], marker='^', color='red', label='예측값')
chart.set_title('AdaBoost 예측 결과', size=30)
plt.xlabel('횟수', size=20)
plt.ylabel('발생여부', size=20)
plt.legend(loc = 'best')
Out[71]:
<matplotlib.legend.Legend at 0x14b34a68af0>
In [72]:
#DecisionTree 모델링

DecisionTree = DecisionTreeClassifier(random_state=200)
DecisionTree.fit(X_train, Y_train)
print("Test Set Score : {:.2f}".format(DecisionTree.score(X_test, Y_test)))
DecisionTree_Prediction = DecisionTree.predict(X_test)
DecisionTree_Score = DecisionTree.score(X_test, Y_test)
Test Set Score : 0.84
In [73]:
fig = plt.figure( figsize = (12, 4))
chart = fig.add_subplot(1,1,1)
chart.plot(실제값[:200], marker='o', color='blue', label='실제값')
chart.plot(DecisionTree_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[73]:
<matplotlib.legend.Legend at 0x14b34ad1cd0>
In [84]:
Model_Name = ['Random Forest','SVM','KNN','AdaBoost','Decision Tree']
Model_Score = [RF_Score, SVM_Score, KNN_Score, AdaBoost_Score, DecisionTree_Score] 
plt.figure(figsize = (15,10)) 
plt.title("머신러닝 모델 정확도", size = 50)
plt.xlabel("모델 이름", size = 35) 
plt.ylabel("정확도", size = 35) 
plt.xticks(size = 20) 
plt.yticks(size = 20) 
sns.barplot(Model_Name, Model_Score) 
#plt.bar(Model_Name, Model_Score) residuals.describe()
Out[84]:
<matplotlib.axes._subplots.AxesSubplot at 0x14b34d82610>
In [ ]:
 
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기