다중 출력 모델

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

왜 다중 출력인가?

멀티태스크 학습 모델 도식: 자동차 이미지 입력, 제조사와 모델 두 출력.

멀티라벨 분류 모델 도식: 단일 이미지 입력, 다중 예측 출력.

정규화 모델 도식: 여러 층 블록마다 출력 예측.

PyTorch로 배우는 Intermediate Deep Learning

문자·알파벳 분류

 

모델 도식: 문자 이미지를 신경망에 입력.

PyTorch로 배우는 Intermediate Deep Learning

문자·알파벳 분류

 

모델 도식: 두 분류기가 이미지 임베딩에서 문자와 알파벳을 분류.

PyTorch로 배우는 Intermediate Deep Learning

두 출력 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을 재사용 가능
  • 샘플 형식만 업데이트:
  print(samples[0])
  [(
    'omniglot_train/.../0459_14.png',
     0,
     0,
   )]
PyTorch로 배우는 Intermediate Deep Learning

두 출력 아키텍처

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
  • 이미지 처리 하위 네트워크 정의
  • 출력별 분류기 정의
  • 이미지를 전용 하위 네트워크에 통과
  • 결과를 각 출력 레이어에 통과
  • 두 출력을 반환
PyTorch로 배우는 Intermediate Deep Learning

학습 루프

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()
  • 모델은 두 출력을 생성
  • 각 출력의 손실 계산
  • 손실을 합쳐 총 손실로
  • 총 손실로 역전파·최적화
PyTorch로 배우는 Intermediate Deep Learning

Ayo berlatih!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...