AICE 대비 실습
① 라이브러리 임포트
import
② 데이터 셋 로딩
read_csv
③ 데이터 확인
head, tail, info, columns, values, describe, isnull, value_counts
④ 결측치 처리
drop, replace, fillna, median(중위값), mode(최빈값)
⑤ 라벨 인코딩, 원핫 인코딩
LabelEncoder(라벨 인코딩), pd.get_dummies(one-hot 인코딩)
⑥ x, y 데이터 분리
train_test_split
⑦ 데이터 정규분포화, 표준화
StandardScaler(평균과 표준편차), MinMaxScaler(최대와 최소)
⑧ 머신러닝 모델링과 모델 성능평가 및 그래프 시각화
sklearn(LogisticRegression, DecisionTree, RandomForest, ...), model.fit,
model.predict, metrics(classification_report, confusion_matrix)
시각화는 confusion_matrix를 변수로 저장해 sns.heatmap으로
⑨ 딥러닝 모델링과 모델 성능평가 및 그래프 시각화
tensorflow, keras, Sequential, Dense, Dropout, EarlyStopping, Modelcheckpoint등
시각화는 model.fit한 결과를 변수에 저장해 loss, val_loss등 확인
경고 메시지 무시
# 코드실행시 경고 메시지 무시
import warnings
warnings.filterwarnings(action='ignore')
seaborn설치
!pip install seaborn
import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# 고해상도 디스플레이 설정
%config InlineBackend.figure_format = 'retina'
# 폰트를 'Malgun Gothic'으로 설정
plt.rcParams['font.family'] = "Malgun Gothic"
# 마이너스 부호 깨짐 현상 해결
plt.rcParams["axes.unicode_minus"] = False
# Seaborn 시각화 패키지 임포트
import seaborn as sns
sns.set(font="Malgun Gothic", # 폰트 설정
rc={"axes.unicode_minus":False}, # 마이너스 부호 깨짐 현상 방지
style="white") # 테마
구글 드라이브 연결
from google.colab import drive
drive.mount('/content/drive')
데이터 셋 불러오기
df = pd.read_csv('/content/drive/MyDrive/5차미니프로젝트/AI 5차 미니프로젝트 1_2일차 실습자료/미니프로젝트 5차_2일차_실습파일/nav_data.csv', encoding = 'CP949')
df.head()
# 실주행시간과 평균시속 분포
plt.figure(figsize=(12, 6))
jg = sns.JointGrid(x=df['Speed_Per_Hour'], y=df['Time_Driving'], data=df)
jg.plot_joint(sns.regplot, order=2)
jg.plot_marginals(sns.distplot)

필요없는 변수 삭제
# 불필요한 열 삭제
columns = ['Time_Departure', 'Time_Arrival']
df_temp = df.drop(columns, axis=1)
라벨인코딩
# 범주형 데이터를 수치형 데이터로 변환(주소컬럼)
# Address1, Address2 컬럼에 대해 LabelEncoder를 적용
# LabelEncoder 임포트
from sklearn.preprocessing import LabelEncoder
# LabelEncoder
le = LabelEncoder()
df_temp['Address1'] = le.fit_transform(df_temp['Address1'])
df_temp['Address2'] = le.fit_transform(df_temp['Address2'])
원-핫 인코딩
# 원-핫 인코딩(weekday, hour, day, address1, address2, get_dummies 활용)
df_temp = pd.get_dummies(data=df_temp, columns=['Weekday', 'Hour', 'Day', 'Address1', 'Address2'], drop_first=True)
train_test_split
from sklearn.model_selection import train_test_split
X = df_temp.drop(columns=['Time_Driving']).values
y = df_temp['Time_Driving'].values
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# StandardScaler를 사용해 훈련데이터셋은 정규분포화, 검증데이터셋은 표준화
# 라이브러리 임포트
from sklearn.preprocessing import StandardScaler
# StandardScaler 적용
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
ML 모델링
# 머신러닝 모델링
# 1단계: 불러오기
from sklearn.tree import DecisionTreeRegressor
# 2단계: 선언하기
model = DecisionTreeRegressor(max_depth=5)
# 3단계: 학습하기
model.fit(x_train, y_train)
# 4단계: 예측하기
y_pred = model.predict(x_test)
# RMSE
from sklearn.metrics import mean_squared_error
MSE = mean_squared_error(y_test, y_pred)
print('MSE : ', np.sqrt(MSE))
# R-SQUARED
from sklearn.metrics import r2_score
# r-square 함수사용
print('R-squared : ', r2_score(y_test, y_pred))

DL 모델링
# 하이퍼파라미터 설정 : batch_size, epochs
batch_size = 1024
epochs = 30
# 라이브러리 임포트
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# Tensoflow의 Sequential() 함수 선언
# 결과 저장 : model
model = Sequential()
# model.add() 함수와 Dense() 함수 사용
# 첫번째 Hidden Layer 생성시 unit 64, activation='relu', input_shape=() 입력해야 함
model.add(Dense(128, activation='relu', input_shape=(117,)))
model.add(Dense(128, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1,activation='linear'))
# compile
model.compile(optimizer='adam', loss='mae',metrics=['mae'])
# EarlyStopping, ModelCheckpoint
es = EarlyStopping(monitor='val_loss', patience=4, mode='min', verbose=1)
mc = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
# 모델 훈련
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
callbacks=[es, mc],
validation_data=(x_test, y_test),
verbose=1)
# 훈련데이터셋과 검증데이터셋의 mae
plt.figure(figsize=(10,5))
plt.plot(history.history['loss'], 'b', label='mae')
plt.plot(history.history['val_loss'], 'y', label='val_mae')
plt.title('Training mae')
plt.xlabel('Epochs')
plt.ylabel('mae')
plt.legend()

from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
print('R2 score : ', r2_score(y_test, y_test_pred))
print('MSE : ', mean_squared_error(y_test, y_test_pred))
print('RMSE : ', mean_squared_error(y_test, y_test_pred, squared = False))
print('MAE : ', mean_absolute_error(y_test, y_test_pred))
