MCPcopy Create free account
hub / github.com/alinlab/SelfPatch / PCA

Class PCA

utils.py:634–685  ·  view source on GitHub ↗

Class to compute and apply PCA.

Source from the content-addressed store, hash-verified

632
633
634class PCA():
635 """
636 Class to compute and apply PCA.
637 """
638 def __init__(self, dim=256, whit=0.5):
639 self.dim = dim
640 self.whit = whit
641 self.mean = None
642
643 def train_pca(self, cov):
644 """
645 Takes a covariance matrix (np.ndarray) as input.
646 """
647 d, v = np.linalg.eigh(cov)
648 eps = d.max() * 1e-5
649 n_0 = (d < eps).sum()
650 if n_0 > 0:
651 d[d < eps] = eps
652
653 # total energy
654 totenergy = d.sum()
655
656 # sort eigenvectors with eigenvalues order
657 idx = np.argsort(d)[::-1][:self.dim]
658 d = d[idx]
659 v = v[:, idx]
660
661 print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0))
662
663 # for the whitening
664 d = np.diag(1. / d**self.whit)
665
666 # principal components
667 self.dvt = np.dot(d, v.T)
668
669 def apply(self, x):
670 # input is from numpy
671 if isinstance(x, np.ndarray):
672 if self.mean is not None:
673 x -= self.mean
674 return np.dot(self.dvt, x.T).T
675
676 # input is from torch and is on GPU
677 if x.is_cuda:
678 if self.mean is not None:
679 x -= torch.cuda.FloatTensor(self.mean)
680 return torch.mm(torch.cuda.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)
681
682 # input if from torch, on CPU
683 if self.mean is not None:
684 x -= torch.FloatTensor(self.mean)
685 return torch.mm(torch.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)
686
687
688def compute_ap(ranks, nres):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected