1. 라이브러리 임포트 및 데이터 로드
판다스를 불러오고 CSV 데이터를 읽어오는 기본 코드입니다.
import pandas as pd
# 데이터 읽어오기
df = pd.read_csv('data_file.csv') # 파일명은 문제에 따라 다름
2. 데이터 시각화 및 전처리
특정 컬럼의 분포 확인 및 이상치/결측치 처리 코드입니다
import seaborn as sns
import matplotlib.pyplot as plt
# 카운트 플롯 그리기
sns.count_count(data=df, x='Address1')
plt.show()
# 특정 조건의 행 삭제 (예: 주소에 '-'가 있는 행 제외)
df = df[df['Address1'] != '-']
# 상관관계 구하기
df.corr()
# 불필요한 컬럼 삭제
df_temp = df.drop(columns=['RID'])
# 결측치 확인 및 제거
df_temp.isna().sum()
df_na = df_temp.dropna()
3. 원-핫 인코딩 (One-Hot Encoding)
범주형 데이터를 수치형 데이터로 변환하는 과정입니다.
# 특정 오브젝트 타입 컬럼만 선택하여 인코딩
cols = df_del.select_dtypes(include='object').columns
df_preset = pd.get_dummies(df_del, columns=cols)
4. 데이터 분리 및 스케일링
모델 학습을 위해 데이터를 나누고 단위를 맞추는 과정입니다.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import RobustScaler
# 피처(X)와 타겟(y) 분리
x = df_preset.drop(columns=['Time_Driving'])
y = df_preset['Time_Driving']
# 학습/검증 데이터 분리 (8:2)
x_train, x_valid, y_train, y_valid = train_test_split(x, y, test_size=0.2, random_state=42)
# 로버스트 스케일링
scaler = RobustScaler()
x_train = scaler.fit_transform(x_train)
x_valid = scaler.transform(x_valid)
5. 머신러닝 모델 학습 및 평가
의사결정나무와 랜덤 포레스트 회귀 모델 예시입니다.
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
# 모델 생성 및 학습
dt = DecisionTreeRegressor(max_depth=5, random_state=120)
dt.fit(x_train, y_train)
rf = RandomForestRegressor(random_state=42)
rf.fit(x_train, y_train)
# 예측 및 성능 평가 (MAE)
pred_dt = dt.predict(x_valid)
mae_dt = mean_absolute_error(y_valid, pred_dt)
6. 딥러닝 모델 구성 및 학습
Keras 시퀀셜 모델을 이용한 딥러닝 구현 부분입니다.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
# 모델 구조 정의
model = Sequential([
Dense(64, activation='selu', input_shape=(x_train.shape[1],)),
Dropout(0.1),
Dense(32, activation='selu'),
Dense(16, activation='selu'),
Dense(1, activation='linear')
])
# 조기 종료 설정
es = EarlyStopping(monitor='val_loss', patience=9)
# 컴파일 및 학습
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
history = model.fit(x_train, y_train,
validation_data=(x_valid, y_valid),
epochs=50, batch_size=128, callbacks=[es])
7. 학습 결과 시각화
학습 과정에서의 손실(MSE) 변화를 그래프로 그립니다.
plt.plot(history.history['mse'])
plt.plot(history.history['val_mse'])
plt.title('Model MSE')
plt.xlabel('Epochs')
plt.ylabel('MSE')
plt.legend(['Train', 'Validation'])
plt.show()