def test_MDM_transform(): """Test transform of MDM""" covset = generate_cov(100, 3) labels = np.array([0, 1]).repeat(50) mdm = MDM(metric='riemann') mdm.fit(covset, labels) mdm.transform(covset)
def test_MDM_transform(): """Test transform of MDM""" covset = generate_cov(100,3) labels = np.array([0,1]).repeat(50) mdm = MDM(metric='riemann') mdm.fit(covset,labels) mdm.transform(covset)
def test_MDM_predict(): """Test prediction of MDM""" covset = generate_cov(100, 3) labels = np.array([0, 1]).repeat(50) mdm = MDM(metric='riemann') mdm.fit(covset, labels) mdm.predict(covset) # test fit_predict mdm = MDM(metric='riemann') mdm.fit_predict(covset, labels) # test transform mdm.transform(covset) # predict proba mdm.predict_proba(covset) # test n_jobs mdm = MDM(metric='riemann', n_jobs=2) mdm.fit(covset, labels) mdm.predict(covset)
class DistanceCalculatorRafal(BaseEstimator, TransformerMixin): """Distance Calulator Based on MDM Rafal style.""" def __init__(self, metric_mean='logeuclid', metric_dist=['riemann'], n_jobs=12, subsample=10): """Init.""" self.metric_mean = metric_mean self.metric_dist = metric_dist self.n_jobs = n_jobs self.subsample = subsample def fit(self, X, y): """Fit.""" self.mdm = MDM(metric=self.metric_mean, n_jobs=self.n_jobs) labels = y[::self.subsample] pCalcMeans = partial(mean_covariance, metric=self.metric_mean) pool = Pool(processes=6) mc1 = pool.map(pCalcMeans, [X[labels[:, i] == 1] for i in range(N_EVENTS)]) pool.close() pool = Pool(processes=6) mc0 = pool.map(pCalcMeans, [X[labels[:, i] == 0] for i in range(N_EVENTS)]) pool.close() self.mdm.covmeans = mc1 + mc0 return self def transform(self, X, y=None): """Transform.""" feattr = [] for metric in self.metric_dist: self.mdm.metric_dist = metric feat = self.mdm.transform(X) # print 'feat', feat, feat.shape # substract distance of the class 0 feat = feat[:, 0:N_EVENTS] - feat[:, N_EVENTS:] feattr.append(feat) feattr = np.concatenate(feattr, axis=1) feattr[np.isnan(feattr)] = 0 return feattr def fit_transform(self, X, y): """Fit and transform.""" self.fit(X, y) return self.transform(X)
class DistanceCalculatorRafal(BaseEstimator, TransformerMixin): """Distance Calulator Based on MDM Rafal style.""" def __init__(self, metric_mean='logeuclid', metric_dist=['riemann'], n_jobs=12, subsample=10): """Init.""" self.metric_mean = metric_mean self.metric_dist = metric_dist self.n_jobs = n_jobs self.subsample = subsample def fit(self, X, y): """Fit.""" self.mdm = MDM(metric=self.metric_mean, n_jobs=self.n_jobs) labels = y[::self.subsample] pCalcMeans = partial(mean_covariance, metric=self.metric_mean) pool = Pool(processes=6) mc1 = pool.map(pCalcMeans, [X[labels[:, i] == 1] for i in range(6)]) pool.close() pool = Pool(processes=6) mc0 = pool.map(pCalcMeans, [X[labels[:, i] == 0] for i in range(6)]) pool.close() self.mdm.covmeans = mc1 + mc0 return self def transform(self, X, y=None): """Transform.""" feattr = [] for metric in self.metric_dist: self.mdm.metric_dist = metric feat = self.mdm.transform(X) # substract distance of the class 0 feat = feat[:, 0:6] - feat[:, 6:] feattr.append(feat) feattr = np.concatenate(feattr, axis=1) feattr[np.isnan(feattr)] = 0 return feattr def fit_transform(self, X, y): """Fit and transform.""" self.fit(X, y) return self.transform(X)
class FgMDM2(BaseEstimator, ClassifierMixin, TransformerMixin): def __init__(self, metric='riemann', tsupdate=False, n_jobs=1): """Init.""" self.metric = metric self.n_jobs = n_jobs self.tsupdate = tsupdate if isinstance(metric, str): self.metric_mean = metric elif isinstance(metric, dict): # check keys for key in ['mean', 'distance']: if key not in metric.keys(): raise KeyError('metric must contain "mean" and "distance"') self.metric_mean = metric['mean'] else: raise TypeError('metric must be dict or str') def fit(self, X, y): self.classes_ = unique_labels(y) self._mdm = MDM(metric=self.metric, n_jobs=self.n_jobs) self._fgda = FGDA(metric=self.metric_mean, tsupdate=self.tsupdate) cov = self._fgda.fit_transform(X, y) self._mdm.fit(cov, y) return self def predict(self, X): cov = self._fgda.transform(X) return self._mdm.predict(cov) def predict_proba(self, X): cov = self._fgda.transform(X) return self._mdm.predict_proba(cov) def transform(self, X): cov = self._fgda.transform(X) return self._mdm.transform(cov)
class DistanceCalculatorAlex(BaseEstimator, TransformerMixin): """Distance Calulator Based on MDM.""" def __init__(self, metric_mean='logeuclid', metric_dist=['riemann'], n_jobs=7, subsample=10): """Init.""" self.metric_mean = metric_mean self.metric_dist = metric_dist self.n_jobs = n_jobs self.subsample = subsample def fit(self, X, y): """Fit.""" self.mdm = MDM(metric=self.metric_mean, n_jobs=self.n_jobs) labels = np.squeeze(create_sequence(y.T)[::self.subsample]) self.mdm.fit(X, labels) return self def transform(self, X, y=None): """Transform.""" feattr = [] for metric in self.metric_dist: self.mdm.metric_dist = metric feat = self.mdm.transform(X) # substract distance of the class 0 feat = feat[:, 1:] - np.atleast_2d(feat[:, 0]).T feattr.append(feat) feattr = np.concatenate(feattr, axis=1) feattr[np.isnan(feattr)] = 0 return feattr def fit_transform(self, X, y): """Fit and transform.""" self.fit(X, y) return self.transform(X)
class ERPDistance(BaseEstimator, TransformerMixin): """ERP distance cov estimator. This transformer estimates Riemannian distance for ERP covariance matrices. After estimation of special form ERP covariance matrices using the ERP transformer, a MDM [1] algorithm is used to compute Riemannian distance. References: [1] A. Barachant, S. Bonnet, M. Congedo and C. Jutten, "Multiclass Brain-Computer Interface Classification by Riemannian Geometry," in IEEE Transactions on Biomedical Engineering, vol. 59, no. 4, p. 920-928, 2012 """ def __init__(self, window=500, nfilters=3, subsample=1, metric='riemann', n_jobs=1): """Init.""" self.window = window self.nfilters = nfilters self.subsample = subsample self.metric = metric self.n_jobs = n_jobs self._fitted = False def fit(self, X, y): """fit.""" # Create ERP and get cov mat self.ERP = ERP(self.window, self.nfilters, self.subsample) train_cov = self.ERP.fit_transform(X, y) labels_train = self.ERP.labels_train # Add rest epochs rest_cov = self._get_rest_cov(X, y) train_cov = np.concatenate((train_cov, rest_cov), axis=0) labels_train = np.concatenate((labels_train, [0] * len(rest_cov))) # fit MDM self.MDM = MDM(metric=self.metric, n_jobs=self.n_jobs) self.MDM.fit(train_cov, labels_train) self._fitted = True return self def transform(self, X, y=None): """Transform.""" test_cov = self.ERP.transform(X) dist = self.MDM.transform(test_cov) dist = dist[:, 1:] - np.atleast_2d(dist[:, 0]).T return dist def update_subsample(self, old_sub, new_sub): """update subsampling.""" if self._fitted: self.ERP.update_subsample(old_sub, new_sub) def _get_rest_cov(self, X, y): """Sample rest epochs from data and compute the cov mat.""" ix = np.where(np.diff(y[:, 0]) == 1)[0] rest = [] offset = -self.window for i in ix: start = i + offset - self.window stop = i + offset rest.append(self.ERP.erp_cov(X[slice(start, stop)].T)) return np.array(rest)
class ERPDistance(BaseEstimator, TransformerMixin): """ERP distance cov estimator. This transformer estimates Riemannian distance for ERP covariance matrices. After estimation of special form ERP covariance matrices using the ERP transformer, a MDM [1] algorithm is used to compute Riemannian distance. References: [1] A. Barachant, S. Bonnet, M. Congedo and C. Jutten, "Multiclass Brain-Computer Interface Classification by Riemannian Geometry," in IEEE Transactions on Biomedical Engineering, vol. 59, no. 4, p. 920-928, 2012 """ def __init__(self, window=500, nfilters=3, subsample=1, metric='riemann', n_jobs=1): """Init.""" self.window = window self.nfilters = nfilters self.subsample = subsample self.metric = metric self.n_jobs = n_jobs self._fitted = False def fit(self, X, y): """fit.""" # Create ERP and get cov mat self.ERP = ERP(self.window, self.nfilters, self.subsample) train_cov = self.ERP.fit_transform(X, y) labels_train = self.ERP.labels_train # Add rest epochs rest_cov = self._get_rest_cov(X, y) train_cov = np.concatenate((train_cov, rest_cov), axis=0) labels_train = np.concatenate((labels_train, [0] * len(rest_cov))) # fit MDM self.MDM = MDM(metric=self.metric, n_jobs=self.n_jobs) self.MDM.fit(train_cov, labels_train) self._fitted = True return self def transform(self, X, y=None): """Transform.""" test_cov = self.ERP.transform(X) dist = self.MDM.transform(test_cov) dist = dist[:, 1:] - np.atleast_2d(dist[:, 0]).T return dist def update_subsample(self, old_sub, new_sub): """update subsampling.""" if self._fitted: self.ERP.update_subsample(old_sub, new_sub) def _get_rest_cov(self, X, y): """Sample rest epochs from data and compute the cov mat.""" ix = np.where(np.diff(y[:, 0]) == 1)[0] rest = [] offset = - self.window for i in ix: start = i + offset - self.window stop = i + offset rest.append(self.ERP.erp_cov(X[slice(start, stop)].T)) return np.array(rest)