多輸出模型

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

為什麼用多輸出?

多任務學習 模型示意:輸入為車輛影像,輸出為車廠與車款兩個結果。

多標籤分類 模型示意:單一影像輸入,輸出多個預測。

正規化 模型示意:多段層塊,每段後面各自產生一個輸出。

Intermediate Deep Learning with PyTorch

字元與字母表分類

 

模型示意:字元影像輸入類神經網路。

Intermediate Deep Learning with PyTorch

字元與字母表分類

 

模型示意:兩個分類器從影像嵌入分別預測字元與字母表。

Intermediate Deep Learning with PyTorch

雙輸出 Dataset

class OmniglotDataset(Dataset):
    def __init__(self, transform, samples):
        self.transform = transform
        self.samples = samples

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, idx):
        img_path, alphabet, label = \
            self.samples[idx]
        img = Image.open(img_path).convert('L')
        img = self.transform(img)
        return img, alphabet, label
  • 我們可以重用同一個 Dataset…
  • …只要更新 samples:
  print(samples[0])
  [(
    'omniglot_train/.../0459_14.png',
     0,
     0,
   )]
Intermediate Deep Learning with PyTorch

雙輸出架構

class Net(nn.Module):
    def __init__(self, num_alpha, num_char):
        super().__init__()
        self.image_layer = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=3, padding=1),
            nn.MaxPool2d(kernel_size=2),
            nn.ELU(),
            nn.Flatten(),
            nn.Linear(16*32*32, 128)
        )

self.classifier_alpha = nn.Linear(128, 30) self.classifier_char = nn.Linear(128, 964)
def forward(self, x): x_image = self.image_layer(x)
output_alpha = self.classifier_alpha(x_image) output_char = self.classifier_char(x_image)
return output_alpha, output_char
  • 定義影像處理子網路
  • 定義各輸出專用分類器
  • 將影像送入專用子網路
  • 將結果送入各輸出層
  • 回傳兩個輸出
Intermediate Deep Learning with PyTorch

訓練迴圈

for epoch in range(10):
    for images, labels_alpha, labels_char \
    in dataloader_train:
        optimizer.zero_grad()
        outputs_alpha, outputs_char = net(images)

loss_alpha = criterion( outputs_alpha, labels_alpha ) loss_char = criterion( outputs_char, labels_char )
loss = loss_alpha + loss_char
loss.backward() optimizer.step()
  • 模型產生兩個輸出
  • 各輸出各自計算損失
  • 合併為總損失
  • 以總損失反向傳播並最佳化
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...