본문 바로가기

데이터사이언스/데이터사이언티스트4기

딥러닝 보스턴 주택 가격 예측 모델

# 보스턴 집값 딥러닝
from keras.datasets import boston_housing
from tensorflow.keras import models, layers
import matplotlib.pyplot as plt
import numpy as np

# 1. Load data
(train_data, train_labels), (test_data, test_labels) = boston_housing.load_data()

# 2. Manual standardization (without sklearn)
# 먼저 입력 데이터의 각 특성의 평균을 뺍니다.
mean = train_data.mean(axis=0)
train_data -= mean

# 평균을 뺀 입력 데이터에서 표준편차를 나눕니다.
std = train_data.std(axis=0)
train_data /= std

# 테스트 데이터셋도 마찬가지로 평균을 빼고, 표준편차로 나눕니다.
test_data -= mean
test_data /= std

# 3. Build the model
# 문제 1-2: 주택 가격 예측을 위한 딥러닝 모델 구성 및 컴파일합니다.
# input_shape은 (train_data.shape[1], )으로 구성합니다.
# 회귀(예측)을 위한 모델이므로 loss를 mse, metrics를 mae로 사용합니다.
def build_model():
    model = models.Sequential()
    model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(1))  # 출력층: 회귀 문제이므로 1개의 뉴런
    model.compile(optimizer='adam', loss='mse', metrics=['mae'])
    return model

model = build_model()

# 4. Train the model
# 문제 1-3: 예측을 위한 딥러닝 모델을 학습합니다.
history = model.fit(train_data, train_labels,
                    epochs=100, batch_size=16,
                    validation_split=0.2,
                    verbose=0)

# 5. Evaluate the model
# 문제 1-4: 테스트 데이터셋을 이용해 모델을 평가합니다.
mse, mae = model.evaluate(test_data, test_labels, verbose=0)
print(f"Test MAE: {mae:.3f}")

# 6. Plot training history
# 문제 1-4: 테스트 MAE 시각화를 위한 학습 도표를 그립니다.
plt.plot(history.history['mae'], label='Train MAE')
plt.plot(history.history['val_mae'], label='Val MAE')
plt.xlabel('Epoch')
plt.ylabel('Mean Absolute Error')
plt.title(f'Training and Validation MAE
Final Test MAE: {mae:.3f}')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

# 7. Compare predicted and actual prices
predicted = model.predict(test_data).flatten()
plt.figure(figsize=(8, 6))
plt.scatter(test_labels, predicted)
plt.xlabel('Actual Prices ($1000s)')
plt.ylabel('Predicted Prices ($1000s)')
plt.title('Actual vs. Predicted Prices')
plt.plot([min(test_labels), max(test_labels)], [min(test_labels), max(test_labels)], color='red')
plt.grid(True)
plt.tight_layout()
plt.show()