Mô hình PyTorch là một lớp kế thừa nn.Module: khai báo các lớp con trong __init__, viết phép tính trong forward. Tham số của các lớp con tự được đăng ký — model.parameters() trả về tất cả.
import torch.nn as nn
import torch.nn.functional as F
class MLP(nn.Module):
def __init__(self, d_in, d_hidden, n_classes):
super().__init__()
self.fc1 = nn.Linear(d_in, d_hidden) # W: (d_hidden, d_in), out = x Wᵀ + b
self.fc2 = nn.Linear(d_hidden, n_classes)
def forward(self, x):
return self.fc2(F.relu(self.fc1(x))) # logits
model = MLP(784, 128, 10)
loss_fn = nn.CrossEntropyLoss() # nhận LOGITS, tự làm log-softmax
opt = torch.optim.Adam(model.parameters(), lr=1e-3)nn.CrossEntropyLoss / F.cross_entropy nhận logits chứ không phải xác suất — đừng softmax trước, sẽ bị softmax hai lần và học rất kém.
?nn.Linear(100, 10) lưu trọng số W có shape gì?
Luyện tập ngay
Viết code và chấm tự động — có trợ lý AI gợi ý khi bí.