多輸入模型

Intermediate Deep Learning with PyTorch

Michal Oleszak

Machine Learning Engineer

為何使用多輸入?

運用更多資訊

模型架構:以兩張車輛影像為輸入,輸出一個結果。

多模態模型

模型架構:以一張影像與一段文字為輸入,輸出文字。

度量學習

模型架構:以兩張人臉影像為輸入,預測是否為同一人。

自我監督式學習

模型架構:以同一張影像的兩個增強版本為輸入,學習它們為同一來源。

Intermediate Deep Learning with PyTorch

Omniglot 資料集

Omniglot 資料集的影像樣本。

1 Lake, B. M., Salakhutdinov, R., and Tenenbaum, J. B. (2015). Human-level concept learning through probabilistic program induction. Science, 350(6266), 1332-1338.
Intermediate Deep Learning with PyTorch

字元分類

模型架構:字元影像傳入類神經網路。

Intermediate Deep Learning with PyTorch

字元分類

模型架構:one-hot 字母表向量傳入類神經網路。

Intermediate Deep Learning with PyTorch

字元分類

模型架構:結合字元與字母表的嵌入。

Intermediate Deep Learning with PyTorch

字元分類

模型架構:分類器從結合後的嵌入預測字元。

Intermediate Deep Learning with PyTorch

雙輸入 Dataset

from PIL import Image

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
  • 指派 samples 與 transforms

    print(samples[0])
    
    [(
      'omniglot_train/.../0459_14.png',
       array([1., 0., 0., ..., 0., 0., 0.]),
       0
     )]
    
  • 實作 __len__()

  • 載入並轉換影像

  • 回傳兩個輸入與標籤
Intermediate Deep Learning with PyTorch

Tensor 串接

x = torch.tensor([
  [1, 2, 3],
])

y = torch.tensor([
  [4, 5, 6],
])

沿軸 0 串接

torch.cat((x, y), dim=0)
[[1, 2, 3],
 [4, 5, 6]]

沿軸 1 串接

torch.cat((x, y), dim=1)
[[1, 2, 3, 4, 5, 6]]
Intermediate Deep Learning with PyTorch

雙輸入架構

class Net(nn.Module):
    def __init__(self):
        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.alphabet_layer = nn.Sequential( nn.Linear(30, 8), nn.ELU(), )
self.classifier = nn.Sequential( nn.Linear(128 + 8, 964), )
  • 定義影像處理層
  • 定義字母表處理層
  • 定義分類器層
Intermediate Deep Learning with PyTorch

雙輸入架構

def forward(self, x_image, x_alphabet):

x_image = self.image_layer(x_image)
x_alphabet = self.alphabet_layer(x_alphabet)
x = torch.cat((x_image, x_alphabet), dim=1)
return self.classifier(x)
  • 影像經過影像層
  • 字母表經過字母表層
  • 串接影像與字母表的輸出
  • 將結果傳入分類器
Intermediate Deep Learning with PyTorch

訓練迴圈

net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)

for epoch in range(10):
    for img, alpha, labels in dataloader_train:
        optimizer.zero_grad()
        outputs = net(img, alpha)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
  • 訓練資料包含三項:
    • 影像
    • 字母表向量
    • 標籤
  • 將影像與字母表一併傳入模型
Intermediate Deep Learning with PyTorch

一起來練習吧!

Intermediate Deep Learning with PyTorch

Preparing Video For Download...