예상문제정리와 함께 관련 코드들 정리이다
기본 import 라이브러리
import sklearn as sk
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
!pip install seaborn
import seaborn as sns
파일 불러오기, merge 하기
# 데이터 파일 읽기
df_a = pd.read_json('.json')
df_b = pd.read_csv('.csv')
# 데이터 병합
df = pd.merge(df_a, df_b, on='RID', how='inner')
2. Address1(주소1)의 분포 시각화
요구사항:
- Address1에 대한 분포를 Seaborn의 countplot을 사용해 시각화.
- Address1 값이 '-'인 데이터를 제거 후 처리.
- 결과 그래프에서 경기도와 서울특별시의 상대적 분포를 확인.
코드:
import seaborn as sns
import matplotlib.pyplot as plt
# '-' 값을 제거한 데이터프레임
df = df[df['Address1'] != '-']
# Address1 분포 그래프
sns.countplot(data=df, x='Address1')
plt.title('Address1 Distribution')
plt.show()
joint plot 시각화
코드:
# Time_Driving과 Speed_Per_Hour의 jointplot 생성
sns.jointplot(data=df, x='Time_Driving', y='Speed_Per_Hour')
plt.show()
4. 이상치 처리
요구사항:
- Speed_Per_Hour 값이 300 이상인 이상치를 제거.
- RID 열 삭제.
- 처리 후 결과를 df_temp에 저장.
코드:
# 이상치 제거 및 새로운 데이터프레임 생성
df_temp = df[df['Speed_Per_Hour'] < 300].copy()
# 'RID' 열 삭제
df_temp.drop(columns=['RID'], inplace=True)
5. Time_Driving과 Speed_Per_Hour 관계 시각화
요구사항:
- Seaborn의 jointplot을 사용하여 Time_Driving과 Speed_Per_Hour의 관계를 시각화.
코드:
# Time_Driving과 Speed_Per_Hour의 jointplot 생성
sns.jointplot(data=df, x='Time_Driving', y='Speed_Per_Hour')
plt.title('Time Driving vs Speed Per Hour')
plt.show()
6. 결측치 처리
요구사항:
- 결측치를 확인하고 제거.
- 제거된 데이터프레임을 df_na에 저장.
- 결측치 개수를 답안07에 저장.
코드:
# 결측치 확인
print(df_temp.isna().sum())
# 결측치 제거
df_na = df_temp.dropna()
7. 불필요한 열 삭제
요구사항:
- Time_Departure와 Time_Arrival 열 삭제.
- 삭제된 결과를 df_del에 저장.
코드:
# 불필요한 열 삭제
df_del = df_na.drop(['Time_Departure', 'Time_Arrival'], axis=1)
8. 원-핫 인코딩
요구사항:
- Object 타입 열에 대해 원-핫 인코딩 수행.
- 결과를 df_preset에 저장.
코드:
# Object 타입 열 선택
cols = df_del.select_dtypes(include=['object']).columns
# 원-핫 인코딩 수행
df_preset = pd.get_dummies(df_del, columns=cols)
10. 훈련 및 검증 데이터셋 분리
요구사항:
- Time_Driving을 y로 설정하고 나머지 컬럼을 X로 설정.
- 훈련 및 검증 데이터셋을 80:20으로 분리.
- RobustScaler를 사용하여 스케일링.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import RobustScaler
# Feature와 Label 분리
X = df_preset.drop('Time_Driving', axis=1)
y = df_preset['Time_Driving']
# 데이터셋 분리
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=42)
# 스케일링
scaler = RobustScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_valid_scaled = scaler.transform(X_valid)
11. 의사결정나무와 랜덤포레스트 모델 학습
요구사항:
- 의사결정나무와 랜덤포레스트 모델을 각각 생성 및 학습.
- 모델 이름:
- 의사결정나무: dt
- 랜덤포레스트: rf
코드:
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# 의사결정나무 모델 생성
dt = DecisionTreeRegressor(max_depth=5, min_samples_split=3, random_state=120)
dt.fit(X_train_scaled, y_train)
# 랜덤포레스트 모델 생성
rf = RandomForestRegressor(max_depth=5, min_samples_split=3, random_state=120)
rf.fit(X_train_scaled, y_train)
12. 모델 성능 평가 (MAE 계산)
요구사항:
- 검증 데이터셋을 사용해 각 모델의 예측 결과와 MAE 계산.
- MAE 결과를 각각 dt_mae, rf_mae에 저장.
- 성능이 더 우수한 모델 이름을 답안12 변수에 저장.
코드:
from sklearn.metrics import mean_absolute_error
# 의사결정나무 예측 및 평가
y_pred_dt = dt.predict(X_valid_scaled)
dt_mae = mean_absolute_error(y_valid, y_pred_dt)
# 랜덤포레스트 예측 및 평가
y_pred_rf = rf.predict(X_valid_scaled)
rf_mae = mean_absolute_error(y_valid, y_pred_rf)
# 성능 비교
답안12 = 'decisiontree' if dt_mae < rf_mae else 'randomforest'
print("Decision Tree MAE:", dt_mae)
print("Random Forest MAE:", rf_mae)
print("Best Model:", 답안12)
13. 딥러닝 모델 생성 및 학습
요구사항:
- TensorFlow를 사용해 딥러닝 모델 생성.
- MSE 손실 함수와 30 epochs, 배치 크기 16으로 학습.
- 학습 기록을 history에 저장.
코드:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
# 딥러닝 모델 생성
model = Sequential([
Dense(64, activation='relu', input_shape=(X_train_scaled.shape[1],)),
Dense(32, activation='relu'),
Dropout(0.2),
Dense(1)
])
# 모델 컴파일
model.compile(optimizer='adam', loss='mse', metrics=['mse'])
# 모델 학습
history = model.fit(
X_train_scaled, y_train,
validation_data=(X_valid_scaled, y_valid),
epochs=30,
batch_size=16
)
14. 딥러닝 모델 성능 평가
요구사항:
- 학습과 검증 데이터셋의 MSE를 그래프로 시각화.
코드:
import matplotlib.pyplot as plt
# 학습 및 검증 MSE 그래프
plt.plot(history.history['mse'], label='Train MSE')
plt.plot(history.history['val_mse'], label='Validation MSE')
plt.title('Model MSE')
plt.xlabel('Epochs')
plt.ylabel('MSE')
plt.legend()
plt.show()
그 외에 잘 정리된 블로그들 몇개를 추가합니다.
https://blog.naver.com/ivorry02/223714118880
[KT AIVLE 6기 DX] AICE Associate 대비
※주의 사항 ~출력하세요 : print() 데이터 불러오기 [import : 라이브러리 로드] [read_csv : csv 파일 로...
blog.naver.com
시험 대비 파잇팅~~