Domain-Adversarial Neural Networks (abstract class)
| 198 | |
| 199 | |
| 200 | class AbstractDANN(Algorithm): |
| 201 | """Domain-Adversarial Neural Networks (abstract class)""" |
| 202 | |
| 203 | def __init__(self, input_shape, num_classes, num_domains, hparams, conditional, class_balance): |
| 204 | |
| 205 | super(AbstractDANN, self).__init__(input_shape, num_classes, num_domains, hparams) |
| 206 | |
| 207 | self.register_buffer('update_count', torch.tensor([0])) |
| 208 | self.conditional = conditional |
| 209 | self.class_balance = class_balance |
| 210 | |
| 211 | # Algorithms |
| 212 | self.featurizer = networks.Featurizer(input_shape, self.hparams) |
| 213 | self.classifier = networks.Classifier( |
| 214 | self.featurizer.n_outputs, num_classes, self.hparams['nonlinear_classifier'] |
| 215 | ) |
| 216 | self.discriminator = networks.MLP(self.featurizer.n_outputs, num_domains, self.hparams) |
| 217 | self.class_embeddings = nn.Embedding(num_classes, self.featurizer.n_outputs) |
| 218 | |
| 219 | # Optimizers |
| 220 | self.disc_opt = torch.optim.Adam( |
| 221 | (list(self.discriminator.parameters()) + list(self.class_embeddings.parameters())), |
| 222 | lr=self.hparams["lr_d"], |
| 223 | weight_decay=self.hparams['weight_decay_d'], |
| 224 | betas=(self.hparams['beta1'], 0.9) |
| 225 | ) |
| 226 | |
| 227 | self.gen_opt = torch.optim.Adam( |
| 228 | (list(self.featurizer.parameters()) + list(self.classifier.parameters())), |
| 229 | lr=self.hparams["lr_g"], |
| 230 | weight_decay=self.hparams['weight_decay_g'], |
| 231 | betas=(self.hparams['beta1'], 0.9) |
| 232 | ) |
| 233 | |
| 234 | def update(self, minibatches, unlabeled=None): |
| 235 | device = "cuda" if minibatches[0][0].is_cuda else "cpu" |
| 236 | self.update_count += 1 |
| 237 | all_x = torch.cat([x for x, y in minibatches]) |
| 238 | all_y = torch.cat([y for x, y in minibatches]) |
| 239 | all_z = self.featurizer(all_x) |
| 240 | if self.conditional: |
| 241 | disc_input = all_z + self.class_embeddings(all_y) |
| 242 | else: |
| 243 | disc_input = all_z |
| 244 | disc_out = self.discriminator(disc_input) |
| 245 | disc_labels = torch.cat( |
| 246 | [ |
| 247 | torch.full((x.shape[0],), i, dtype=torch.int64, device=device) |
| 248 | for i, (x, y) in enumerate(minibatches) |
| 249 | ] |
| 250 | ) |
| 251 | |
| 252 | if self.class_balance: |
| 253 | y_counts = F.one_hot(all_y).sum(dim=0) |
| 254 | weights = 1. / (y_counts[all_y] * y_counts.shape[0]).float() |
| 255 | disc_loss = F.cross_entropy(disc_out, disc_labels, reduction='none') |
| 256 | disc_loss = (weights * disc_loss).sum() |
| 257 | else: |
nothing calls this directly
no outgoing calls
no test coverage detected