PyTorch 与面向对象编程

PyTorch 深度学习进阶

Michal Oleszak

Machine Learning Engineer

学习目标

如何训练稳健的深度学习模型:

  • 用优化器改进训练
  • 缓解梯度消失与爆炸
  • 卷积神经网络(CNN)
  • 循环神经网络(RNN)
  • 多输入与多输出模型

 

 

PyTorch 标志

PyTorch 深度学习进阶

先修要求

本课程默认你已掌握以下主题:

PyTorch 深度学习进阶

面向对象编程(OOP)

  • 我们将用 OOP 定义:

    • PyTorch Datasets
    • PyTorch Models
  • 在 OOP 中,我们创建的对象包含:

    • 能力(方法)
    • 数据(属性)
PyTorch 深度学习进阶

面向对象编程(OOP)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance
  • 创建 BankAccount 对象时会调用 __init__
  • balanceBankAccount 对象的属性
account = BankAccount(100)
print(account.balance)
100
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
PyTorch 深度学习进阶

水可饮用性数据集

Pandas DataFrame 展示了水可饮用性数据的部分首尾行。

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 的单个样本特征和标签
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.])
PyTorch 深度学习进阶

PyTorch 模型

顺序式模型定义:

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()
PyTorch 深度学习进阶

Passons à la pratique !

PyTorch 深度学习进阶

Preparing Video For Download...