-
Notifications
You must be signed in to change notification settings - Fork 162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
speedup pairwise_distance #256
Merged
qbarthelemy
merged 11 commits into
pyRiemann:master
from
gabelstein:speedup_pairwise_distance
Aug 11, 2023
Merged
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
9a9aa20
add faster individual pairwise distance functions
gabelstein b490ffe
Update whatsnew.rst
gabelstein 98b5330
Update test_utils_distance.py
gabelstein 530cb0c
Apply suggestions from code review
gabelstein 5c63ab0
remove individual pairwise functions from api
gabelstein 1b8f88d
remove check for array_equal in distance functions
gabelstein 61b7161
make pairwise_distance functions private
gabelstein 59dafc3
Implement code review
gabelstein 07bda25
correct typos and clean code
qbarthelemy 76e55f3
set Y input to None if applicable (faster)
gabelstein 12ea7d9
Merge branch 'master' into speedup_pairwise_distance
qbarthelemy File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ A catalog of new features, improvements, and bug-fixes in each release. | |
v0.6.dev | ||
-------- | ||
|
||
- Speedup pairwise distance function :func:`pyriemann.utils.distance.pairwise_distance` by adding individual functions. :pr:`256` by :user:`gabelstein` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Say for what metric it's faster |
||
|
||
v0.5 (Jun 2023) | ||
--------------- | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
|
||
import numpy as np | ||
from scipy.linalg import eigvalsh, solve | ||
from sklearn.metrics import euclidean_distances | ||
|
||
from .base import logm, sqrtm, invsqrtm | ||
|
||
|
@@ -446,6 +447,178 @@ def distance(A, B, metric='riemann', squared=False): | |
return d | ||
|
||
|
||
def pairwise_distance_euclid(X, Y=None, squared=False): | ||
"""Pairwise Euclidean distance matrix. | ||
|
||
Compute the matrix of Euclidan distances between pairs of elements of X and | ||
Y. | ||
|
||
Parameters | ||
---------- | ||
X : ndarray, shape (n_matrices_X, n, n) | ||
First set of matrices. | ||
Y : None | ndarray, shape (n_matrices_Y, n, n), default=None | ||
Second set of matrices. If None, Y is set to X. | ||
squared : bool, default False | ||
Return squared distance. | ||
|
||
Returns | ||
------- | ||
dist : ndarray, shape (n_matrices_X, n_matrices_X) or (n_matrices_X, \ | ||
n_matrices_Y) | ||
Euclidean Distances between pairs of elements of X if Y is None, or | ||
between elements of X and Y. | ||
|
||
Notes | ||
----- | ||
.. versionadded:: 0.6 | ||
|
||
See Also | ||
-------- | ||
pairwise_distance | ||
distance_euclid | ||
""" | ||
if isinstance(Y, type(None)) or np.array_equal(X, Y): | ||
gabelstein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dist = euclidean_distances(X.reshape(len(X), -1), squared=squared) | ||
np.fill_diagonal(dist, 0) # diagonal is not exactly 0 | ||
gabelstein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
else: | ||
dist = euclidean_distances(X.reshape(len(X), -1), | ||
Y.reshape(len(Y), -1), | ||
squared=squared) | ||
return dist | ||
|
||
|
||
def pairwise_distance_harmonic(X, Y=None, squared=False): | ||
"""Pairwise harmonic distance matrix. | ||
|
||
Compute the matrix of harmonic distances between pairs of elements of X and | ||
Y. | ||
|
||
Parameters | ||
---------- | ||
X : ndarray, shape (n_matrices_X, n, n) | ||
First set of matrices. | ||
Y : None | ndarray, shape (n_matrices_Y, n, n), default=None | ||
Second set of matrices. If None, Y is set to X. | ||
squared : bool, default False | ||
Return squared distance. | ||
|
||
Returns | ||
------- | ||
dist : ndarray, shape (n_matrices_X, n_matrices_X) or (n_matrices_X, \ | ||
n_matrices_Y) | ||
Harmonic Distances between pairs of elements of X if Y is None, or | ||
between elements of X and Y. | ||
Notes | ||
----- | ||
.. versionadded:: 0.6 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You don't need these now that it's private |
||
|
||
See Also | ||
-------- | ||
pairwise_distance | ||
distance_harmonic | ||
""" | ||
if isinstance(Y, type(None)) or np.array_equal(X, Y): | ||
invY = invX = np.linalg.inv(X) | ||
else: | ||
invX = np.linalg.inv(X) | ||
invY = np.linalg.inv(Y) | ||
|
||
return pairwise_distance_euclid(invX, invY, squared=squared) | ||
|
||
|
||
def pairwise_distance_logeuclid(X, Y=None, squared=False): | ||
"""Pairwise Log-Euclidean distance matrix. | ||
|
||
Compute the matrix of Log-Euclidan distances between pairs of elements of X | ||
and Y. | ||
|
||
Parameters | ||
---------- | ||
X : ndarray, shape (n_matrices_X, n, n) | ||
First set of matrices. | ||
Y : None | ndarray, shape (n_matrices_Y, n, n), default=None | ||
Second set of matrices. If None, Y is set to X. | ||
squared : bool, default False | ||
Return squared distance. | ||
|
||
Returns | ||
------- | ||
dist : ndarray, shape (n_matrices_X, n_matrices_X) or (n_matrices_X, \ | ||
n_matrices_Y) | ||
Log-Euclidean Distances between pairs of elements of X if Y is None, or | ||
between elements of X and Y. | ||
|
||
Notes | ||
----- | ||
.. versionadded:: 0.6 | ||
|
||
See Also | ||
-------- | ||
pairwise_distance | ||
distance_logeuclid | ||
""" | ||
if isinstance(Y, type(None)) or np.array_equal(X, Y): | ||
logY = logX = logm(X) | ||
else: | ||
logX = logm(X) | ||
logY = logm(Y) | ||
|
||
return pairwise_distance_euclid(logX, logY, squared=squared) | ||
|
||
|
||
def pairwise_distance_riemann(X, Y=None, squared=False): | ||
"""Pairwise Riemann distance matrix. | ||
|
||
Compute the matrix of Riemann distances between pairs of elements of X | ||
and Y. | ||
|
||
Parameters | ||
---------- | ||
X : ndarray, shape (n_matrices_X, n, n) | ||
First set of matrices. | ||
Y : None | ndarray, shape (n_matrices_Y, n, n), default=None | ||
Second set of matrices. If None, Y is set to X. | ||
squared : bool, default False | ||
Return squared distance. | ||
|
||
Returns | ||
------- | ||
dist : ndarray, shape (n_matrices_X, n_matrices_X) or (n_matrices_X, \ | ||
n_matrices_Y) | ||
Riemann Distances between pairs of elements of X if Y is None, or | ||
between elements of X and Y. | ||
|
||
Notes | ||
----- | ||
.. versionadded:: 0.6 | ||
|
||
See Also | ||
-------- | ||
pairwise_distance | ||
distance_riemann | ||
""" | ||
XisY = False | ||
if isinstance(Y, type(None)) or np.array_equal(X, Y): | ||
XisY = True | ||
Y = X | ||
|
||
n_matrices_X, n_matrices_Y = len(X), len(Y) | ||
Xinv12 = invsqrtm(X) | ||
res = np.zeros((n_matrices_X, n_matrices_Y)) | ||
|
||
# row by row so it fits in memory | ||
for i, x_ in enumerate(Xinv12): | ||
evals_ = np.linalg.eigvalsh(x_ @ Y[i * XisY:] @ x_) | ||
res_ = np.sum(np.log(evals_) ** 2, -1) | ||
res[i, i * XisY:] = res_ | ||
|
||
if XisY: | ||
res = res + res.T | ||
|
||
return res if squared else np.sqrt(res) | ||
|
||
|
||
def pairwise_distance(X, Y=None, metric='riemann', squared=False): | ||
"""Pairwise distance matrix. | ||
|
||
|
@@ -477,6 +650,15 @@ def pairwise_distance(X, Y=None, metric='riemann', squared=False): | |
-------- | ||
distance | ||
""" | ||
if metric == 'euclid': | ||
return pairwise_distance_euclid(X, Y=Y, squared=squared) | ||
elif metric == 'harmonic': | ||
return pairwise_distance_harmonic(X, Y=Y, squared=squared) | ||
elif metric == 'logeuclid': | ||
return pairwise_distance_logeuclid(X, Y=Y, squared=squared) | ||
elif metric == 'riemann': | ||
return pairwise_distance_riemann(X, Y=Y, squared=squared) | ||
|
||
n_matrices_X, _, _ = X.shape | ||
|
||
# compute full pairwise matrix for non-symmetric metrics | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would not make these functions public to avoid over crowding the public namespace.