# 2️⃣ Xây dựng mô hình DL đơn giản bằng PyTorch

Trang này **không thêm lý thuyết mới**.\
Mục tiêu duy nhất là: **ghép toàn bộ Group 4 vào một mô hình PyTorch chạy được**.

> Neuron → Layer → Activation → Loss → Backprop\
> (giờ xuất hiện **đầy đủ trong code**)

***

### 1. Bài toán minh họa (giữ đơn giản)

* **Binary classification**
* Dữ liệu giả lập dạng **tabular**
* Input: 3 đặc trưng số
* Output: 0 hoặc 1

👉 Chọn bài toán này vì:

* Dễ đọc
* Dễ liên hệ với **case Diabetes** sau này

***

### 2. Kiến trúc mô hình (MLP rất nhỏ)

```
Input (3)
   ↓
Hidden layer (8 neurons, ReLU)
   ↓
Output layer (1 neuron, Sigmoid)
```

* Không CNN
* Không Transformer
* Chỉ **MLP (Multi-Layer Perceptron)**

👉 Đây là **Deep Learning ở mức cơ bản nhất**, nhưng đầy đủ cơ chế.

***

### 3. Định nghĩa mô hình trong PyTorch

```python
import torch
import torch.nn as nn

class SimpleMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(3, 8)
        self.act = nn.ReLU()
        self.output = nn.Linear(8, 1)
        self.out_act = nn.Sigmoid()

    def forward(self, x):
        x = self.hidden(x)
        x = self.act(x)
        x = self.output(x)
        x = self.out_act(x)
        return x
```

#### Liên hệ trực tiếp với Group 4

* `nn.Linear` → **Neuron + Layer**
* `ReLU`, `Sigmoid` → **Activation**
* `forward()` → **Forward pass**

***

### 4. Chuẩn bị Loss & Optimizer

```python
model = SimpleMLP()

criterion = nn.BCELoss()
optimizer = torch.optim.Adam(
    model.parameters(), lr=0.01
)
```

* **Loss**: Binary Cross-Entropy (Group 4.4)
* **Optimizer**: Adam (dùng gradient để sửa weight – Group 4.5)

👉 Optimizer chỉ là **công cụ cập nhật**, không phải “trí tuệ”.

***

### 5. Training loop (trái tim của Deep Learning)

```python
epochs = 100

for epoch in range(epochs):
    optimizer.zero_grad()      # reset gradient
    y_pred = model(X)          # forward
    loss = criterion(y_pred, y)
    loss.backward()            # backprop
    optimizer.step()           # update weights

    if epoch % 10 == 0:
        print(f"Epoch {epoch}, Loss: {loss.item():.4f}")
```

#### Đọc code theo đúng tư duy [Broken mention](broken://pages/OaiB8Aiue6XAilofDCRp)

```
X → forward → prediction
        ↓
      loss
        ↓
   backpropagation
        ↓
    update weights
```

👉 **Không có bước nào “bí ẩn”**.

***

### 6. Điều gì đang thực sự được “học”?

* PyTorch **không học**
* Mô hình **không hiểu bài toán**
* Chỉ có:
  * Loss giảm dần
  * Weight thay đổi

👉 “Học” = **tối ưu weight để loss nhỏ hơn**

***

### 7. Những điều cố tình **chưa làm** ở mục này

⛔ Chuẩn hóa dữ liệu\
⛔ Train / validation split\
⛔ Đánh giá accuracy\
⛔ Overfitting

👉 Các phần này **để dành cho 6.3**.

***

### 8. Tóm tắt (rất quan trọng)

> **6.2 là cây cầu từ “hiểu” sang “làm được”**\
> Nếu bạn đọc code và chỉ ra được:
>
> * đâu là layer
> * đâu là activation
> * đâu là loss
> * đâu là backprop

→ bạn **đã nắm Deep Learning cơ bản**.

Câu nhớ nhanh:

```
Group 4: Deep Learning hoạt động thế nào
Group 6.2: Deep Learning trông như thế nào trong code
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://deeplearningcoban.gitbook.io/deeplearningcoban.com/thuc-hanh-deep-learning-co-ban-hands-on/xay-dung-mo-hinh-dl-don-gian-bang-pytorch.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
