MCPcopy Create free account
hub / github.com/alexrame/fishr / AbstractMMD

Class AbstractMMD

domainbed/algorithms.py:585–659  ·  view source on GitHub ↗

Perform ERM while matching the pair-wise domain feature distributions using MMD (abstract class)

Source from the content-addressed store, hash-verified

583
584
585class AbstractMMD(ERM):
586 """
587 Perform ERM while matching the pair-wise domain feature distributions
588 using MMD (abstract class)
589 """
590
591 def __init__(self, input_shape, num_classes, num_domains, hparams, gaussian):
592 super(AbstractMMD, self).__init__(input_shape, num_classes, num_domains, hparams)
593 if gaussian:
594 self.kernel_type = "gaussian"
595 else:
596 self.kernel_type = "mean_cov"
597
598 def my_cdist(self, x1, x2):
599 x1_norm = x1.pow(2).sum(dim=-1, keepdim=True)
600 x2_norm = x2.pow(2).sum(dim=-1, keepdim=True)
601 res = torch.addmm(
602 x2_norm.transpose(-2, -1), x1, x2.transpose(-2, -1), alpha=-2
603 ).add_(x1_norm)
604 return res.clamp_min_(1e-30)
605
606 def gaussian_kernel(self, x, y, gamma=[0.001, 0.01, 0.1, 1, 10, 100, 1000]):
607 D = self.my_cdist(x, y)
608 K = torch.zeros_like(D)
609
610 for g in gamma:
611 K.add_(torch.exp(D.mul(-g)))
612
613 return K
614
615 def mmd(self, x, y):
616 if self.kernel_type == "gaussian":
617 Kxx = self.gaussian_kernel(x, x).mean()
618 Kyy = self.gaussian_kernel(y, y).mean()
619 Kxy = self.gaussian_kernel(x, y).mean()
620 return Kxx + Kyy - 2 * Kxy
621 else:
622 mean_x = x.mean(0, keepdim=True)
623 mean_y = y.mean(0, keepdim=True)
624 cent_x = x - mean_x
625 cent_y = y - mean_y
626 cova_x = (cent_x.t() @ cent_x) / (len(x) - 1)
627 cova_y = (cent_y.t() @ cent_y) / (len(y) - 1)
628
629 mean_diff = (mean_x - mean_y).pow(2).mean()
630 cova_diff = (cova_x - cova_y).pow(2).mean()
631
632 return mean_diff + cova_diff
633
634 def update(self, minibatches, unlabeled=None):
635 objective = 0
636 penalty = 0
637 nmb = len(minibatches)
638
639 features = [self.featurizer(xi) for xi, _ in minibatches]
640 classifs = [self.classifier(fi) for fi in features]
641 targets = [yi for _, yi in minibatches]
642

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected