Skip to content

Commit

Permalink
cosmetic changes
Browse files Browse the repository at this point in the history
  • Loading branch information
plcrodrigues committed Jun 13, 2017
1 parent dc8a2c6 commit cc56872
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 63 deletions.
27 changes: 9 additions & 18 deletions examples/ERP/plot_embedding_EEG.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from pyriemann.estimation import ERPCovariances, XdawnCovariances
from pyriemann.tangentspace import TangentSpace
from pyriemann.embedding import CovEmbedding
from pyriemann.embedding import Embedding

import mne
from mne import io
Expand All @@ -21,7 +21,6 @@
from sklearn.pipeline import make_pipeline
from sklearn.cross_validation import KFold
from sklearn.linear_model import LogisticRegression

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

Expand Down Expand Up @@ -62,28 +61,20 @@
# Embedding the Xdawn covariance matrices with Diffusion maps

#covs = XdawnCovariances(nfilter=4).fit_transform(X,y)
covs = ERPCovariances(estimator='oas', classes=[3,4]).fit_transform(X,y)
lapl = CovEmbedding(metric='riemann', n_components=3)
covs = ERPCovariances(estimator='oas', classes=[3, 4]).fit_transform(X, y)
lapl = Embedding(metric='riemann', n_components=3)
embd = lapl.fit_transform(covs)

#%%

###############################################################################
# Plot the three first components of the embedded points

fig,ax = plt.subplots(figsize=(7,8), facecolor='white')

for label in np.unique(y):
idx = (y==label)
ax.scatter(embd[idx,0], embd[idx,1], s=36)

ax.set_xlabel(r'$\varphi_1$', fontsize=16)
ax.set_ylabel(r'$\varphi_2$', fontsize=16)





fig, ax = plt.subplots(figsize=(7, 8), facecolor='white')

for label in np.unique(y):
idx = (y == label)
ax.scatter(embd[idx, 0], embd[idx, 1], s=36)


ax.set_xlabel(r'$\varphi_1$', fontsize=16)
ax.set_ylabel(r'$\varphi_2$', fontsize=16)
85 changes: 40 additions & 45 deletions pyriemann/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.manifold import spectral_embedding
from pyriemann.utils.distance import distance, pairwise_distance

class CovEmbedding(BaseEstimator):


class Embedding(BaseEstimator):

"""Embed SPD matrices into an Euclidean space of smaller dimension.
It uses diffusion maps to embed the SPD matrices into an Euclidean space.
The Euclidean distance between points in this new space approximates
the Diffusion distance (also called commute distance) between vertices
of a graph where each SPD matrix is a vertex.
It uses Laplacian Eigenmaps [1] to embed SPD matrices into an Euclidean
space. The basic hypothesis is that high-dimensional data lives in a
low-dimensional manifold, whose intrinsic geometry can be described
via the Laplacian matrix of a graph. The vertices of this graph are
the SPD matrices and the weights of the links are determined by the
Riemannian distance between each pair of them.
Parameters
----------
Expand All @@ -22,35 +25,40 @@ class CovEmbedding(BaseEstimator):
The type of metric to be used for defining pairwise distance between
covariance matrices.
eps: float (default: None)
the scaling of the Gaussian kernel. If none is given
it will use the square of the median of pairwise distances between
points.
The scaling of the Gaussian kernel. If none is given
it will use the square of the median of pairwise distances between
points.
References
----------
[1] M. Belkin and P. Niyogi, "Laplacian Eigenmaps for dimensionality
reduction and data representation,"" in Journal Neural Computation,
vol. 15, no. 6, p. 1373-1396 , 2003
"""

def __init__(self, n_components=2, metric='riemann', eps=None):
"""Init."""
self.metric = metric
self.n_components = n_components
self.eps = eps

def _get_affinity_matrix(self, X, eps):

# make matrix with pairwise distances between points
distmatrix = pairwise_distance(X, metric='riemann')
distmatrix = pairwise_distance(X, metric='riemann')

# determine which scale for the gaussian kernel
if self.eps is None:
eps = np.median(distmatrix)**2/2
eps = np.median(distmatrix)**2 / 2

# make kernel matrix from the distance matrix
kernel = np.exp(-distmatrix**2/(4*eps))
# normalize the kernel matrix
kernel = np.exp(-distmatrix**2 / (4 * eps))

# normalize the kernel matrix
q = np.dot(kernel, np.ones(len(kernel)))
kernel_n = np.divide(kernel, np.outer(q,q))
self.affinity_matrix_ = kernel_n
kernel_n = np.divide(kernel, np.outer(q, q))

self.affinity_matrix_ = kernel_n
return self.affinity_matrix_

def fit(self, X, y=None):
Expand All @@ -63,42 +71,29 @@ def fit(self, X, y=None):
Returns
-------
self : Embedding instance
The Embedding instance.
"""
self : object
Returns the instance itself.
"""

affinity_matrix = self._get_affinity_matrix(X, self.eps)
self.embedding_ = spectral_embedding(adjacency=affinity_matrix,
n_components=self.n_components,
self.embedding_ = spectral_embedding(adjacency=affinity_matrix,
n_components=self.n_components,
norm_laplacian=True)

return self

def fit_transform(self, X, y=None):
"""Calculates the coordinates of the embedded points.
Parameters
----------
X : ndarray, shape (n_trials, n_channels, n_channels)
ndarray of SPD matrices.
X : ndarray, shape (n_trials, n_channels, n_channels)
ndarray of SPD matrices.
Returns
-------
X_new: array-like, shape (n_samples, n_components)
"""

self.fit(X)
return self.embedding_













self.fit(X)
return self.embedding_

0 comments on commit cc56872

Please sign in to comment.