PyTorch 定義模型
## PyTorch 中繼承 `Module` 定義模型
在 PyTorch 中,自訂神經網路通常會繼承 `torch.nn.Module`,並實作兩個部分:
1. `__init__()`
建立模型中的層,例如 `nn.Linear`。
2. `forward()`
定義資料如何通過這些層。
基本結構如下:
```python
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super().__init__()
# 定義模型層
def forward(self, x):
# 定義前向傳播
return x
```
呼叫模型時,直接使用:
```python
output = model(input_data)
```
不需要自行直接呼叫 `forward()`。
---
## 範例一:單層線性神經網路
這個模型只有一個全連接層,將 4 個輸入特徵轉換成 2 個輸出值。
```python
import torch
import torch.nn as nn
class SingleLinearModel(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.linear = nn.Linear(
in_features=input_size,
out_features=output_size
)
def forward(self, x):
return self.linear(x)
# 建立模型
model = SingleLinearModel(input_size=4, output_size=2)
# 建立一批輸入資料
# batch size = 3,每筆資料有 4 個特徵
x = torch.tensor([
[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 4.0, 5.0],
[3.0, 4.0, 5.0, 6.0]
])
# 前向傳播
output = model(x)
print(model)
print("輸入形狀:", x.shape)
print("輸出形狀:", output.shape)
```
輸出形狀為:
```text
輸入形狀: torch.Size([3, 4])
輸出形狀: torch.Size([3, 2])
```
此模型沒有使用激勵函式,其計算形式大致為:
y = x*W + b
其中 `W` 和 `b` 是由 `nn.Linear` 自動建立並註冊的可學習參數。
---
## 範例二:多層全連接神經網路
以下模型包含三個線性層,但刻意不使用任何激勵函式:
```python
import torch
import torch.nn as nn
class MultiLayerLinearModel(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(4, 8)
self.layer2 = nn.Linear(8, 6)
self.layer3 = nn.Linear(6, 2)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
# 建立模型
model = MultiLayerLinearModel()
# 建立一批輸入資料
x = torch.randn(5, 4)
# 前向傳播
output = model(x)
print(model)
print("輸入形狀:", x.shape)
print("輸出形狀:", output.shape)
```
輸出形狀為:
```text
輸入形狀: torch.Size([5, 4])
輸出形狀: torch.Size([5, 2])
```
資料流向如下:
```text
4 個輸入特徵
↓
Linear(4, 8)
↓
Linear(8, 6)
↓
Linear(6, 2)
↓
2 個輸出值
```
由於這個範例沒有加入激勵函式,因此多層線性層的整體效果仍可視為一個線性轉換。不過,它示範了如何在 `Module` 中定義多個網路層,以及如何在 `forward()` 中依序傳遞資料。
---
## 查看模型參數
PyTorch 會自動註冊在 `__init__()` 中建立的層,因此可以使用:
```python
for name, parameter in model.named_parameters():
print(name, parameter.shape)
```
也可以使用:
```python
print(model.state_dict())
```
這些參數包括各個線性層的:
- `weight`
- `bias`
以上範例僅建立模型並進行前向傳播,沒有包含損失函式、反向傳播、最佳化器或訓練演算。
相關學習地圖、教學課程
Python 人工智慧