多输入模型

PyTorch 深度学习进阶

Michal Oleszak

Machine Learning Engineer

为何使用多输入?

利用更多信息

模型示意图:模型接收两张汽车图像作为输入,输出一个结果。

多模态模型

模型示意图:模型接收一张图像和一段文本为输入,输出文本。

度量学习

模型示意图:模型接收两张人脸作为输入,判断是否同一人。

自监督学习

模型示意图:模型接收同一图像的两种增强版本,学习它们相同。

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

字符分类

模型示意图:将字符图像输入神经网络。

PyTorch 深度学习进阶

字符分类

模型示意图:将独热编码的字母表向量输入神经网络。

PyTorch 深度学习进阶

字符分类

模型示意图:合并字符与字母表的嵌入。

PyTorch 深度学习进阶

字符分类

模型示意图:分类器基于合并后的嵌入预测字符。

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
  • 赋值样本与变换

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

  • 加载并变换图像

  • 返回两个输入和标签
PyTorch 深度学习进阶

张量拼接

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]]
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), )
  • 定义图像处理层
  • 定义字母表处理层
  • 定义分类器层
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)
  • 图像经图像层
  • 字母表经字母表层
  • 拼接两者输出
  • 经分类器得到结果
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()
  • 训练数据含三部分:
    • 图像
    • 字母表向量
    • 标签
  • 向模型传入图像与字母表
PyTorch 深度学习进阶

开始练习吧!

PyTorch 深度学习进阶

Preparing Video For Download...