PyTorch 與物件導向程式設計

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

本章重點

如何訓練穩健的深度學習模型:

  • 使用最佳化器改進訓練
  • 緩解梯度消失與爆炸
  • 卷積神經網路(CNN)
  • 循環神經網路(RNN)
  • 多輸入與多輸出模型

 

 

PyTorch 標誌

Intermediate Deep Learning with PyTorch

先備知識

本課程假設你已熟悉以下主題:

  • 神經網路訓練:

    • 前向傳播
    • 損失計算
    • 反向傳播(backpropagation)
  • 使用 PyTorch 訓練模型:

    • Datasets 與 DataLoaders
    • 模型訓練迴圈
    • 模型評估
  • 先修課程:Introduction to Deep Learning with PyTorch

Intermediate Deep Learning with PyTorch

物件導向程式設計(OOP)

  • 我們將用 OOP 定義:

    • PyTorch Datasets
    • PyTorch Models
  • 在 OOP 中,物件包含:

    • 能力(methods)
    • 資料(attributes)
Intermediate Deep Learning with PyTorch

物件導向程式設計(OOP)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance
  • 建立 BankAccount 物件時會呼叫 __init__
  • balanceBankAccount 物件的屬性
account = BankAccount(100)
print(account.balance)
100
Intermediate Deep Learning with PyTorch

物件導向程式設計(OOP)

  • 方法:執行任務的 Python 函式
  • deposit 方法會增加餘額
class BankAccount:
    def __init__(self, balance):
        self.balance = balance


def deposit(self, amount): self.balance += amount
account = BankAccount(100)
account.deposit(50)
print(account.balance)
150
Intermediate Deep Learning with PyTorch

飲用水可飲用性資料集

Pandas DataFrame 顯示飲用水可飲用性資料的前幾列與後幾列。

Intermediate Deep Learning with PyTorch

PyTorch Dataset

from torch.utils.data import Dataset

class WaterDataset(Dataset):

def __init__(self, csv_path): super().__init__() df = pd.read_csv(csv_path) self.data = df.to_numpy()
def __len__(self): return self.data.shape[0]
def __getitem__(self, idx): features = self.data[idx, :-1] label = self.data[idx, -1] return features, label
  • init:載入資料並存成 numpy 陣列
    • super().__init__() 可讓 WaterDataset 具備 torch Dataset 的行為
  • len:回傳資料集大小
  • getitem
    • 接收名為 idx 的引數
    • 回傳索引 idx 的單筆樣本之特徵與標籤
Intermediate Deep Learning with PyTorch

PyTorch DataLoader

dataset_train = WaterDataset(
    "water_train.csv"
)
from torch.utils.data import DataLoader

dataloader_train = DataLoader(
    dataset_train,
    batch_size=2,
    shuffle=True,
)
features, labels = next(iter(dataloader_train))
print(f"Features: {features},\nLabels: {labels}")
Features: tensor([
  [0.4899, 0.4180, 0.6299, 0.3496, 0.4575,
   0.3615, 0.3259, 0.5011, 0.7545],
  [0.7953, 0.6305, 0.4480, 0.6549, 0.7813,
   0.6566, 0.6340, 0.5493, 0.5789]
]),
Labels: tensor([1., 0.])
Intermediate Deep Learning with PyTorch

PyTorch 模型

Sequential 模型定義:

net = nn.Sequential(
  nn.Linear(9, 16),
  nn.ReLU(),
  nn.Linear(16, 8),
  nn.ReLU(),
  nn.Linear(8, 1),
  nn.Sigmoid(),
)

以類別定義模型:

class Net(nn.Module):

def __init__(self): super().__init__() self.fc1 = nn.Linear(9, 16) self.fc2 = nn.Linear(16, 8) self.fc3 = nn.Linear(8, 1)
def forward(self, x): x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = nn.functional.sigmoid(self.fc3(x)) return x net = Net()
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...