🏠 Mô hình Wide & Deep Neural Network - Dự đoán Giá Nhà California
📝 Mô tả
Đây là một mô hình Wide & Deep Neural Network được huấn luyện trên tập dữ liệu California Housing để dự đoán giá nhà trung bình (MedHouseVal). Mô hình được xây dựng bằng PyTorch, dựa trên kiến trúc trong cuốn Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow của Aurélien Géron.
📌 Nhiệm vụ
Dự đoán giá nhà dựa trên dữ liệu bảng (tabular regression) với 8 đặc trưng đầu vào.
📥 Đầu vào
- Số chiều:
[batch_size, 8] - Kiểu dữ liệu:
torch.FloatTensor - Các đặc trưng đầu vào:
'MedInc'– Thu nhập trung vị'HouseAge'– Tuổi trung bình của căn nhà'AveRooms'– Số phòng trung bình'AveBedrms'– Số phòng ngủ trung bình'Population'– Dân số'AveOccup'– Số người trung bình trên mỗi hộ'Latitude'– Vĩ độ'Longitude'– Kinh độ
📤 Đầu ra
- Kiểu:
torch.FloatTensorcó shape[batch_size, 1] - Ý nghĩa: Giá nhà trung bình dự đoán (giá trị thực).
🧪 Cách sử dụng mô hình
Dưới đây là ví dụ về cách sử dụng mô hình với dữ liệu đầu vào giả lập:
import torch
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin
# Tạo dữ liệu đầu vào giả lập (batch 1, 8 features)
x_input = torch.randn(1, 8)
print("Mock input:")
print(x_input)
# Định nghĩa mô hình Wide & Deep Neural Network
class WideAndDeepNet(nn.Module, PyTorchModelHubMixin):
def __init__(self):
super().__init__()
self.hidden1 = nn.Linear(6, 30)
self.hidden2 = nn.Linear(30, 30)
self.main_head = nn.Linear(35, 1)
self.aux_head = nn.Linear(30, 1)
self.main_loss_fn = nn.MSELoss(reduction='sum')
self.aux_loss_fn = nn.MSELoss(reduction='sum')
def forward(self, input_wide, input_deep, label=None):
act = torch.relu(self.hidden1(input_deep))
act = torch.relu(self.hidden2(act))
concat = torch.cat([input_wide, act], dim=1)
main_output = self.main_head(concat)
aux_output = self.aux_head(act)
if label is not None:
main_loss = self.main_loss_fn(main_output.squeeze(), label)
aux_loss = self.aux_loss_fn(aux_output.squeeze(), label)
return WideAndDeepNetOutput(main_output=main_output, aux_output=aux_output)
# Tải mô hình từ Hugging Face Hub
model = WideAndDeepNet.from_pretrained("sadhaklal/wide-and-deep-net-california-housing-v3")
model.eval()
# Dự đoán với mô hình
with torch.no_grad():
prediction = model(x_input)
print(f"Giá nhà dự đoán (mock input): {prediction.item():.3f}")