def fit(self, x_train, y_train): self._train_le(y_train) self.n_samples = len(x_train) self.sub_basis = pca_for_sets( x_train, self.n_sdim, self.p_norm ).contiguous() self._fit(x_train, y_train) gpu_free()
def predict_proba(self, x_pred): sub_basis = pca_for_sets(x_pred, self.n_sdim, self.p_norm) sim, _, _ = subspacea_subs(self.sub_basis, sub_basis, self.metric_mat, False) sim = sim.cpu().numpy() sim = self.lda.transform(sim.T) sim = l2dist(self.dic, sim) pred = [ 1 / (1e-10 + np.min(sim[self.labels == i, :], axis=0)) for i in range(self.n_classes) ] return np.asarray(pred)
def _fit(self, x_train, y_train): cls_data = [ torch.cat( [x_train[j] for j in range(len(y_train)) if y_train[j] == i], 1) for i in set(y_train) ] sub_basis = (pca_for_sets(cls_data, self.n_sdim, self.p_norm).contiguous().permute((2, 0, 1))) gram_mat = (sub_basis @ sub_basis.permute((0, 2, 1))).sum(0) full_dim = torch.matrix_rank(gram_mat) _, eig_vec = torch.symeig(gram_mat, eigenvectors=True) eig_vec = eig_vec.flip(1)[:, self.n_reducedim:full_dim] self.metric_mat = eig_vec @ eig_vec.T self.dic = ortha_subs(self.sub_basis, self.metric_mat)
def predict_proba(self, x_pred, ret_kmat=False): if self.reddim_mat is not None: if self.reddim_mat.shape[0] != self.reddim_mat.shape[1]: x_pred = [self.reddim_mat @ i for i in x_pred] sub_basis = pca_for_sets(x_pred, self.n_sdim, self.p_norm) sub_basis = ortha_subs(sub_basis, self.metric_mat) sim, _, _ = subspacea_subs(self.dic, sub_basis, self.metric_mat, False) sim = sim.cpu().numpy() pred = [ np.max(sim[self.labels == i, :], axis=0) for i in range(self.n_classes) ] if ret_kmat: return np.asarray(pred), sim return np.asarray(pred)