Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- associate #aice
- 무설치 #할일관리 #로컬PC용
- 배경화면 #수험생 #공부
- AIPOT #AI프롬프트활용능력 #AIPOT1급 #한국생산성본부 #영진닷컴 #이기적스터디카페 #AI자격증 #합격후기 #91점합격
- Aice #Associate #자격증
- LLM #Langchain
Archives
- Today
- Total
열정적인 하루
Aice Associate 모의고사 #2 데이터셋 제공, 정답 제공 본문
building_energy_data.csv
0.21MB
데이터셋 컬럼 설명
- Date: 측정 날짜
- Temperature: 외부 기온 (°C)
- Humidity: 습도 (%)
- Wind_Speed: 풍속 (m/s)
- Rainfall: 강수량 (mm)
- Day_of_Week: 요일
- Season: 계절 (Spring/Summer/Fall/Winter/-)
- Holiday: 공휴일 여부 (0: 평일, 1: 공휴일)
- Building_Type: 건물 유형
- Building_Age: 건물 연령 (년)
- Floor_Area: 건물 면적 (m²)
- Occupancy_Rate: 건물 점유율 (0.0~1.0)
- Power_Consumption: 전력 소비량 (kWh) - 회귀 예측 타겟
- Peak_Hour: 피크 시간대 여부 (0: 일반, 1: 피크) - 분류 예측 타겟
문제 1. 데이터 분석 및 시각화 (20점)
1-1. (10점) Building_Type(건물 유형) 분포 분석
대상 데이터프레임: df
요구사항:
- Seaborn의 countplot을 사용하여 Building_Type별 데이터 분포를 시각화하세요.
- 그래프의 제목을 'Building Type Distribution'으로 설정하세요.
- x축 레이블을 45도 회전시키세요.
필요 라이브러리:
python
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
1-2. (10점) Season별 평균 전력 소비량 및 데이터 정제
대상 데이터프레임: df
요구사항:
- Season이 '-'인 행을 제거하여 df_clean 변수에 저장하세요.
- groupby를 사용하여 Season별 Power_Consumption의 평균과 합계를 동시에 계산하세요.
- 결과를 season_stats 변수에 저장하고 출력하세요.
- Seaborn의 barplot을 사용하여 Season별 평균 전력 소비량을 시각화하세요.
- 그래프 제목을 'Average Power Consumption by Season'으로 설정하세요.
필요 라이브러리:
python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
문제 2. 데이터 전처리 (25점)
2-1. (10점) 상관관계 분석 및 히트맵
대상 데이터프레임: df_clean
다음 코드의 빈칸 <blank1>과 <blank2>를 채우고 실행하세요.
python
# 수치형 컬럼 선택
numeric_columns = ['Temperature', 'Humidity', 'Wind_Speed', 'Rainfall',
'Building_Age', 'Floor_Area', 'Occupancy_Rate', 'Power_Consumption']
# 상관관계 행렬 계산
correlation_matrix = df_clean[numeric_columns].<blank1>()
# 히트맵으로 시각화
plt.figure(figsize=(12, 10))
sns.<blank2>(correlation_matrix, annot=True, cmap='RdYlGn', fmt='.2f', linewidths=0.5)
plt.title('Correlation Heatmap of Numeric Features')
plt.tight_layout()
plt.show()
요구사항:
- <blank1> 값을 answer_2_1_a 변수에 저장하세요. 예) answer_2_1_a = '함수명'
- <blank2> 값을 answer_2_1_b 변수에 저장하세요. 예) answer_2_1_b = '함수명'
- 코드를 실행하세요.
필요 라이브러리:
python
import matplotlib.pyplot as plt
import seaborn as sns
2-2. (15점) 라벨 인코딩 및 원-핫 인코딩
대상 데이터프레임: df_clean
요구사항:
- LabelEncoder를 사용하여 Day_of_Week 컬럼을 숫자로 변환하고 결과를 label_encoder 변수에 저장하세요.
- 변환된 값을 'Day_of_Week_Encoded' 컬럼으로 df_clean에 추가하세요.
- Building_Type과 Season 컬럼에 대해 pd.get_dummies를 사용하여 원-핫 인코딩을 수행하세요.
- 원본 Day_of_Week, Building_Type, Season, Date 컬럼을 제거하세요.
- 최종 전처리된 데이터프레임을 df_processed 변수에 저장하세요.
필요 라이브러리:
python
from sklearn.preprocessing import LabelEncoder
import pandas as pd
문제 3. 데이터 분할 및 정규화 (15점)
3-1. (10점) Train/Test 데이터 분할 (회귀 문제)
대상 데이터프레임: df_processed
요구사항:
- Power_Consumption 컬럼을 y_reg(회귀 타겟)로 분리하세요.
- Peak_Hour 컬럼을 y_clf(분류 타겟)로 분리하세요.
- 나머지 컬럼을 X(특성)로 분리하세요.
- train_test_split을 사용하여 회귀 문제용 데이터를 분할하세요.
- X와 y_reg를 분할
- test_size: 0.25
- random_state: 2024
- 분할된 데이터를 X_train_reg, X_test_reg, y_train_reg, y_test_reg 변수에 저장하세요.
필요 라이브러리:
python
from sklearn.model_selection import train_test_split
3-2. (5점) 데이터 표준화 (StandardScaler)
요구사항:
- StandardScaler를 사용하여 X_train_reg를 fit_transform하세요.
- 같은 scaler로 X_test_reg를 transform하세요.
- 스케일러 객체를 scaler 변수에 저장하세요.
- 변환된 데이터를 X_train_scaled, X_test_scaled 변수에 저장하세요.
필요 라이브러리:
python
from sklearn.preprocessing import StandardScaler
문제 4. 머신러닝 모델링 (20점)
4-1. (20점) 회귀 모델 학습 및 비교
요구사항:
1) 의사결정나무 회귀 모델(DecisionTreeRegressor)
- max_depth: 12
- min_samples_split: 8
- min_samples_leaf: 4
- random_state: 2024
- 모델을 dt_reg 변수에 저장하세요.
2) 랜덤포레스트 회귀 모델(RandomForestRegressor)
- n_estimators: 150
- max_depth: 15
- min_samples_split: 6
- min_samples_leaf: 3
- random_state: 2024
- 모델을 rf_reg 변수에 저장하세요.
3) 두 모델 모두 fit()을 사용하여 X_train_scaled와 y_train_reg로 학습시키세요.
4) 각 모델로 X_test_scaled에 대한 예측을 수행하세요.
- 의사결정나무 예측 결과: dt_pred 변수에 저장
- 랜덤포레스트 예측 결과: rf_pred 변수에 저장
5) 두 모델의 성능을 평가하세요.
- mean_squared_error와 r2_score를 사용하여 MSE와 R² 점수를 계산하고 출력하세요.
필요 라이브러리:
python
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
문제 5. 딥러닝 모델링 (15점)
요구사항:
- 다음과 같은 구조로 모델을 구축하세요:
- 첫 번째 Dense 레이어: 128 units, activation='relu', input_shape은 X_train_scaled의 특성 수로 설정
- 두 번째 Dense 레이어: 64 units, activation='selu'
- 세 번째 Dense 레이어: 32 units, activation='relu'
- 네 번째 Dense 레이어: 16 units, activation='selu'
- 출력 Dense 레이어: 1 unit, activation='linear' (회귀 문제)
- optimizer: 'adam'
- loss: 'mean_squared_error'
- metrics: ['mse', 'mae']
- Keras의 EarlyStopping 콜백: monitor='val_loss', patience=12, restore_best_weights=True로 설정하고 early_stopping 변수에 저장하세요.
- Keras의 ModelCheckpoint 콜백: filepath='best_energy_model.h5', monitor='val_mse', save_best_only=True, mode='min'으로 설정하고 model_checkpoint 변수에 저장하세요.
- 학습 데이터: X_train_scaled, y_train_reg
- batch_size: 32
- epochs: 150
- validation_data: (X_test_scaled, y_test_reg)
- callbacks: [early_stopping, model_checkpoint]
- verbose: 1
- 학습 결과를 history 변수에 저장하세요.
문제 6. 모델 성능 평가 (5점)
6-1. (5점) 학습 곡선 시각화
요구사항:
- Matplotlib을 사용하여 2개의 서브플롯을 생성하세요. (1행 2열)
- figure 크기 : (15,5)
- 첫 번째 plot: 학습 MSE와 검증 MSE를 함께 표시
- 범례: 'Train MSE', 'Validation MSE'
- 제목: 'Model MSE'
- X축: 'Epochs', Y축: 'MSE'
- 두 번째 plot: 학습 MAE와 검증 MAE를 함께 표시
- 범례: 'Train MAE', 'Validation MAE'
- 제목: 'Model MAE'
- X축: 'Epochs', Y축: 'MAE'
필요 라이브러리:
python
import matplotlib.pyplot as plt
보너스 문제 7. 고급 모델 평가 및 분류 문제 (추가 10점)
요구사항:
- Part 1: 회귀 모델 로드 및 평가 (5점)
- Keras의 load_model을 사용하여 'best_energy_model.h5'를 불러와 loaded_model 변수에 저장하세요.
- loaded_model의 predict() 메서드로 X_test_scaled에 대한 예측을 수행하고 dl_pred 변수에 저장하세요.
- mean_squared_error와 r2_score를 계산하여 출력하세요.
Part 2: 분류 모델 구축 및 평가 (5점)
- Peak_Hour(피크 시간대) 분류를 위해 X와 y_clf(Peak_Hour)로 데이터를 재분할하세요.
- Scikit-learn의 train_test_split 사용
- test_size: 0.25
- random_state: 2024
- stratify: y_clf 사용
- 변수명: X_train_clf, X_test_clf, y_train_clf, y_test_clf
- 데이터를 표준화하세요.
- 새로운 StandardScaler 객체를 생성하고 scaler_clf 변수에 저장하세요.
- X_train_clf를 fit_transform하여 X_train_clf_scaled 변수에 저장하세요.
- X_test_clf를 transform하여 X_test_clf_scaled 변수에 저장하세요.
- 타겟 데이터를 원-핫 인코딩하세요.
- Keras의 to_categorical을 사용하여 y_train_clf를 변환하고 y_train_cat 변수에 저장, num_classes는 2로 설정하세요.
- Keras의 to_categorical을 사용하여 y_test_clf를 변환하고 y_test_cat 변수에 저장, num_classes는 2로 설정하세요.
- TensorFlow/Keras로 분류 모델을 구축하세요.
- Sequential 모델 생성
- 첫 번째 Dense 레이어: 32 units, activation='relu', input_shape은 X_train_clf_scaled의 특성 수
- 두 번째 Dense 레이어: 16 units, activation='relu'
- 출력 Dense 레이어: 2 units, activation='softmax'
- 모델을 clf_model 변수에 저장하세요.
- 모델을 컴파일하세요.
- optimizer: 'adam'
- loss: 'categorical_crossentropy'
- metrics: ['accuracy']
- 모델을 학습하세요.
- 학습 데이터: X_train_clf_scaled, y_train_cat
- batch_size: 32
- epochs: 50
- validation_data: (X_test_clf_scaled, y_test_cat)
- verbose: 0
- 학습 결과를 clf_history 변수에 저장하세요.
- 예측 및 평가를 수행하세요.
- clf_model의 predict() 메서드로 X_test_clf_scaled를 예측하고 y_pred_prob 변수에 저장하세요.
- NumPy의 argmax를 사용하여 y_pred_prob를 클래스 레이블로 변환하고 y_pred 변수에 저장하세요. (axis=1)
- y_test_cat도 argmax로 변환하고 y_test_label 변수에 저장하세요. (axis=1)
- 성능 평가를 출력하세요.
- Scikit-learn의 confusion_matrix를 사용하여 혼동 행렬을 생성하고 cm 변수에 저장하세요.
- Scikit-learn의 classification_report를 사용하여 성능 리포트를 출력하세요.
- Confusion Matrix를 시각화하세요.
- Seaborn의 heatmap을 사용하세요. (annot=True, fmt='d', cmap='Blues')
- xticklabels와 yticklabels를 ['Normal', 'Peak']로 설정하세요.
필요 라이브러리:
python
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
[정답]
더보기
정답 및 해설
문제 1 정답
1-1. Building_Type 분포 분석
python
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 데이터 로드
df = pd.read_csv('building_energy_data.csv')
# Countplot 시각화
plt.figure(figsize=(10, 6))
sns.countplot(data=df, x='Building_Type')
plt.title('Building Type Distribution')
plt.xlabel('Building Type')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
1-2. Season별 평균 전력 소비량
python
# 1. Season '-' 제거
df_clean = df[df['Season'] != '-'].copy()
print(f"정제 후 데이터 shape: {df_clean.shape}")
# 2. groupby로 평균과 합계 계산
season_stats = df_clean.groupby('Season')['Power_Consumption'].agg(['mean', 'sum'])
print(season_stats)
# 3. Barplot 시각화
plt.figure(figsize=(10, 6))
sns.barplot(data=df_clean, x='Season', y='Power_Consumption', estimator='mean')
plt.title('Average Power Consumption by Season')
plt.xlabel('Season')
plt.ylabel('Average Power Consumption (kWh)')
plt.tight_layout()
plt.show()
문제 2 정답
2-1. 상관관계 분석
python
answer_2_1_a = 'corr'
answer_2_1_b = 'heatmap'
# 실행 코드
numeric_columns = ['Temperature', 'Humidity', 'Wind_Speed', 'Rainfall',
'Building_Age', 'Floor_Area', 'Occupancy_Rate', 'Power_Consumption']
correlation_matrix = df_clean[numeric_columns].corr()
plt.figure(figsize=(12, 10))
sns.heatmap(correlation_matrix, annot=True, cmap='RdYlGn', fmt='.2f', linewidths=0.5)
plt.title('Correlation Heatmap of Numeric Features')
plt.tight_layout()
plt.show()
2-2. 라벨 인코딩 및 원-핫 인코딩
python
from sklearn.preprocessing import LabelEncoder
import pandas as pd
# 1. LabelEncoder로 Day_of_Week 인코딩
label_encoder = LabelEncoder()
df_clean['Day_of_Week_Encoded'] = label_encoder.fit_transform(df_clean['Day_of_Week'])
# 2. 원-핫 인코딩
df_processed = pd.get_dummies(df_clean, columns=['Building_Type', 'Season'], drop_first=False)
# 3. 불필요한 컬럼 제거
df_processed = df_processed.drop(['Day_of_Week', 'Date'], axis=1)
print(f"전처리 후 데이터 shape: {df_processed.shape}")
print(f"컬럼 목록: {df_processed.columns.tolist()}")
문제 3 정답
3-1. Train/Test 데이터 분할
python
from sklearn.model_selection import train_test_split
# 1. 타겟 분리
y_reg = df_processed['Power_Consumption']
y_clf = df_processed['Peak_Hour']
X = df_processed.drop(['Power_Consumption', 'Peak_Hour'], axis=1)
# 2. 회귀 문제용 데이터 분할
X_train_reg, X_test_reg, y_train_reg, y_test_reg = train_test_split(
X, y_reg, test_size=0.25, random_state=2024
)
print(f"X_train_reg shape: {X_train_reg.shape}")
print(f"X_test_reg shape: {X_test_reg.shape}")
print(f"y_train_reg shape: {y_train_reg.shape}")
print(f"y_test_reg shape: {y_test_reg.shape}")
3-2. 데이터 표준화
python
from sklearn.preprocessing import StandardScaler
# StandardScaler 적용
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train_reg)
X_test_scaled = scaler.transform(X_test_reg)
print(f"X_train_scaled shape: {X_train_scaled.shape}")
print(f"X_test_scaled shape: {X_test_scaled.shape}")
문제 4 정답
4-1. 회귀 모델 학습 및 비교
python
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
# 1. 의사결정나무 회귀 모델
dt_reg = DecisionTreeRegressor(
max_depth=12,
min_samples_split=8,
min_samples_leaf=4,
random_state=2024
)
# 2. 랜덤포레스트 회귀 모델
rf_reg = RandomForestRegressor(
n_estimators=150,
max_depth=15,
min_samples_split=6,
min_samples_leaf=3,
random_state=2024
)
# 3. 모델 학습
dt_reg.fit(X_train_scaled, y_train_reg)
rf_reg.fit(X_train_scaled, y_train_reg)
# 4. 예측
dt_pred = dt_reg.predict(X_test_scaled)
rf_pred = rf_reg.predict(X_test_scaled)
# 5. 성능 평가
print("Decision Tree Regressor:")
print(f"MSE: {mean_squared_error(y_test_reg, dt_pred):.4f}")
print(f"R² Score: {r2_score(y_test_reg, dt_pred):.4f}\n")
print("Random Forest Regressor:")
print(f"MSE: {mean_squared_error(y_test_reg, rf_pred):.4f}")
print(f"R² Score: {r2_score(y_test_reg, rf_pred):.4f}")
문제 5 정답
5-1. 회귀 예측 딥러닝 모델
python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# 1. 모델 구축
model = Sequential([
Dense(128, activation='relu', input_shape=(X_train_scaled.shape[1],)),
Dense(64, activation='selu'),
Dense(32, activation='relu'),
Dense(16, activation='selu'),
Dense(1, activation='linear')
])
# 2. 모델 컴파일
model.compile(
optimizer='adam',
loss='mean_squared_error',
metrics=['mse', 'mae']
)
# 3. 콜백 설정
early_stopping = EarlyStopping(
monitor='val_loss',
patience=12,
restore_best_weights=True
)
model_checkpoint = ModelCheckpoint(
filepath='best_energy_model.h5',
monitor='val_mse',
save_best_only=True,
mode='min'
)
# 4. 모델 학습
history = model.fit(
X_train_scaled, y_train_reg,
batch_size=32,
epochs=150,
validation_data=(X_test_scaled, y_test_reg),
callbacks=[early_stopping, model_checkpoint],
verbose=1
)
print("모델 학습 완료")
문제 6 정답
6-1. 학습 곡선 시각화
python
import matplotlib.pyplot as plt
# 서브플롯 생성
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
# 첫 번째 서브플롯: MSE
axes[0].plot(history.history['mse'], label='Train MSE')
axes[0].plot(history.history['val_mse'], label='Validation MSE')
axes[0].set_title('Model MSE')
axes[0].set_xlabel('Epochs')
axes[0].set_ylabel('MSE')
axes[0].legend()
axes[0].grid(True)
# 두 번째 서브플롯: MAE
axes[1].plot(history.history['mae'], label='Train MAE')
axes[1].plot(history.history['val_mae'], label='Validation MAE')
axes[1].set_title('Model MAE')
axes[1].set_xlabel('Epochs')
axes[1].set_ylabel('MAE')
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.show()
보너스 문제 7 정답
7-1. 저장된 모델 로드 및 분류 모델
python
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Part 1: 회귀 모델 로드 및 평가
loaded_model = load_model('best_energy_model.h5')
dl_pred = loaded_model.predict(X_test_scaled)
print("Loaded Model Performance:")
print(f"MSE: {mean_squared_error(y_test_reg, dl_pred):.4f}")
print(f"R² Score: {r2_score(y_test_reg, dl_pred):.4f}\n")
# Part 2: 분류 모델 구축
# 1. 데이터 분할
X_train_clf, X_test_clf, y_train_clf, y_test_clf = train_test_split(
X, y_clf, test_size=0.25, random_state=2024, stratify=y_clf
)
# 2. 표준화
X_train_clf_scaled = scaler.fit_transform(X_train_clf)
X_test_clf_scaled = scaler.transform(X_test_clf)
# 3. 원-핫 인코딩
y_train_cat = to_categorical(y_train_clf, num_classes=2)
y_test_cat = to_categorical(y_test_clf, num_classes=2)
# 4. 분류 모델 구축
clf_model = Sequential([
Dense(32, activation='relu', input_shape=(X_train_clf_scaled.shape[1],)),
Dense(16, activation='relu'),
Dense(2, activation='softmax')
])
clf_model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 5. 모델 학습
clf_history = clf_model.fit(
X_train_clf_scaled, y_train_cat,
batch_size=32,
epochs=50,
validation_data=(X_test_clf_scaled, y_test_cat),
verbose=0
)
# 6. 예측 및 평가
y_pred_prob = clf_model.predict(X_test_clf_scaled)
y_pred = np.argmax(y_pred_prob, axis=1)
y_test_label = np.argmax(y_test_cat, axis=1)
# Confusion Matrix
cm = confusion_matrix(y_test_label, y_pred)
print("\nConfusion Matrix:")
print(cm)
# Classification Report
print("\nClassification Report:")
print(classification_report(y_test_label, y_pred))
# Confusion Matrix 시각화
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix - Peak Hour Classification')
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.show()
'IT' 카테고리의 다른 글
| AI-POT프롬프트활용능력 1급 시험 독학으로 합격하기 (0) | 2026.05.01 |
|---|---|
| LLM 시작을 위한 Langchain 무료 입문 가이드 (2) | 2026.04.19 |
| Aice Associate 시험 예제 및 데이터셋 (0) | 2025.10.16 |
| 비데·정수기 해지 예측 데이터셋 (0) | 2025.10.14 |
| Aice Associate 준비 인코딩 방법 정리 (0) | 2025.10.12 |