Использованный мною сценарий был вдохновлен этой ссылкой
Я изменил реализацию модели на эту:
Код: Выделить всё
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
class MultiOutputModel(nn.Module):
def __init__(self, n_action_classes, n_priority_classes, n_diagnosis_classes):
super().__init__()
self.base_model = models.mobilenet_v2().features # take the model without classifier
last_channel = models.mobilenet_v2().last_channel # size of the layer before classifier
# the input for the classifier should be two-dimensional, but we will have
# [batch_size, channels, width, height]
# so, let's do the spatial averaging: reduce width and height to 1
self.pool = nn.AdaptiveAvgPool2d((1, 1))
# create separate classifiers for our outputs
self.action = nn.Sequential(
nn.Dropout(p=0.2),
nn.Linear(in_features=last_channel, out_features=n_action_classes)
)
self.priority = nn.Sequential(
nn.Dropout(p=0.2),
nn.Linear(in_features=last_channel, out_features=n_priority_classes)
)
self.diagnosis = nn.Sequential(
nn.Dropout(p=0.2),
nn.Linear(in_features=n_action_classes + n_priority_classes,
out_features=n_diagnosis_classes)
)
def forward(self, x):
x = self.base_model(x)
x = self.pool(x)
# reshape from [batch, channels, 1, 1] to [batch, channels] to put it into classifier
x = torch.flatten(x, 1)
# Subclass predictions
action = self.action(x)
priority = self.priority(x)
# Concatenate subclass outputs for parent class prediction
combined_action_priority_outputs = torch.cat([action, priority], dim=1)
diagnosis = self.diagnosis(combined_action_priority_outputs)
return {
'action': action,
'priority': priority,
'diagnosis': diagnosis
}
Подробнее здесь: https://stackoverflow.com/questions/789 ... subclasses