Skip to content

[MRG+1] Enforce euclidean metric on LLE - #9888

Closed
CoderPat wants to merge 10 commits into
scikit-learn:mainfrom
CoderPat:llr-metric-generalization
Closed

CoderPat wants to merge 10 commits into
scikit-learn:mainfrom
CoderPat:llr-metric-generalization

Conversation

@CoderPat

@CoderPat CoderPat commented Oct 8, 2017

Copy link
Copy Markdown
Contributor

Reference Issue

Fixes #9868

What does this implement/fix? Explain your changes.

The LocallyLinearEmbedding class uses the NearestNeighbors class to calculate the K nearest neighbors yet only allowed the use of the euclidean distance metric to calculate those. I added the arguments needed to the class (and all functions used by it) in order to allow any valid metric for nearest neighbors to be used. Also added a test to ensure that another metric can be used.

Any other comments?

I'm not entirely sure of the utility of changing the metric from the euclidean to another one since the error function is calculated based on the euclidean metric. Maybe I also need to change the error calculation function to be dependent on the metric? Either way it is at least possible to choose the neighbors for the embeding based the user choice of metric.
Apreciate any feedback since its my first contribution

@jnothman

jnothman commented Oct 9, 2017

Copy link
Copy Markdown
Member

Hmmm... I think I incorrectly triaged #9868. I briefly looked at the locally linear embedding code and saw that it could accept a NearestNeighbors object instead of the input data, which implied to me that the embedding is based on nearest neighborhoods and not on the original feature space.

In my haste, I did not see that it extracts _fit_X from the NearestNeighbors object and proceeds to use the original feature space. I now find #9868 inadmissable. I'm sorry.

@jnothman

jnothman commented Oct 9, 2017

Copy link
Copy Markdown
Member

On the contrary, I think we should patch the code to enforce that the NearestNeighbors metric in use is 'euclidean'!

@CoderPat

CoderPat commented Oct 9, 2017

Copy link
Copy Markdown
Contributor Author

That seems more consistent with the algorithm.
So basically check that, if the input is in the form of a NearestNeighbors, check if the metric is euclidean?
I will work on it

@jnothman

jnothman commented Oct 9, 2017 via email

Copy link
Copy Markdown
Member

@CoderPat

CoderPat commented Oct 9, 2017

Copy link
Copy Markdown
Contributor Author

@jnothman
No problem, sometimes you have to move backward to move forward.
I have a fix that only allows NN classes that use the euclidean metric to be used by the algorithm.
I did notice thought that while the algorithm accepts NN and such classes, the wrapping class only accepts vectors. Is that intended behaviour from scikit and the .fit method itself or the the author just forgot to also allow NN classes?

@jnothman jnothman left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, LGTM!

@jnothman jnothman changed the title [MGR] Generalize metric for Locally Linear Embedding [MRG+1] Generalize metric for Locally Linear Embedding Oct 9, 2017
@CoderPat CoderPat changed the title [MRG+1] Generalize metric for Locally Linear Embedding [MRG+1] [MRG+1] Enforce euclidean metric on LLE Oct 10, 2017
@CoderPat CoderPat changed the title [MRG+1] [MRG+1] Enforce euclidean metric on LLE [MRG+1] Enforce euclidean metric on LLE Oct 10, 2017

@lesteve lesteve left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few comments

nbrs.fit(X)

if isinstance(X, (BallTree, KDTree, NearestNeighbors)) and \
not (X.metric == 'euclidean'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can use X.effective_metric_ == 'euclidean' here. which is pretty much the same as metric == 'euclidean' or 'minkowki' with p=2.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did it because according to the specification of the Nearest Neighbors, the effective metric is only set after you call the fit method, which might not be the case since I now changed the verification to before the fit method (to save computation).

def test_invalid_metric():
rand = np.random.RandomState(0)
X = rand.randint(0, 100, size=(20, 3))
NN = neighbors.NearestNeighbors(2, metric='manhattan').fit(X)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use capitals for variable names (see PEP8). X and Y are a notable exception in scikit-learn for historical reasons.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed (although the previous test has it).

Comment thread sklearn/manifold/locally_linear.py Outdated
if isinstance(X, (BallTree, KDTree, NearestNeighbors)) and \
not (X.metric == 'euclidean'
or (X.metric == 'minkowski' and X.p == 2)):
raise ValueError("metric must be euclidean or equivalent")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Best practice: put the offending value in the exception. I tend to like error messages like this.

"'parameter' should be have this value for this and this reason. Got 'parameter={}' instead.".format(value)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

raise ValueError("unrecognized method '%s'" % method)

nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to add a new line here. In general only change the minimal/required amount of things to make the review process easier and more focussed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed


msg = "metric must be euclidean or equivalent"
assert_raise_message(ValueError, msg, manifold.locally_linear_embedding,
NN, 2, 1, method='standard', eigen_solver='arpack')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think method and eigen_solver are needed, right?

I would use keyword parameters, i.e. n_neighbors=2, n_components=1 because it's more readable (I don't think people know the signature of locally_linear_embedding by heart).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the first, fixed.

Regarding the second, kept just so it's uniform with the previous test (but can change both)

@CoderPat

Copy link
Copy Markdown
Contributor Author

Should be all set by now.

@MHStadler

MHStadler commented Jul 17, 2018 •

Copy link
Copy Markdown

@CoderPat @jnothman Hi - I am not sure your conclusions here are correct:

See for example this paper [1], where a genetic distance metric is used
Even the original paper mentions no such constraints on the distance metric, only saying that they used the euclidean distance for their specific experiments

The reconstruction error is dependent on the weights that are calculated, which differ on how the neighbourhood is chosen. Using a different distance metric that better encapsulate the underlying manifold will make it easier to find good reconstruction weights, thus reducing the error.

I'd be interested in hearing what you think - I hope this is the right place to raise this

Thank you!

Edit: See also this reference paper, especially Section 4, for further details on neighbourhood selection [2]

[1] Siu, Hoicheong, Li Jin, and Momiao Xiong. "Manifold learning for human population structure studies." PloS one 7.1 (2012): e29901. (Open Access: http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0029901)
[2] Saul, Lawrence K., and Sam T. Roweis. "Think globally, fit locally: unsupervised learning of low dimensional manifolds." Journal of machine learning research 4.Jun (2003): 119-155. (Open Access: http://www.jmlr.org/papers/volume4/saul03a/saul03a.pdf)

@cmarmo

cmarmo commented Dec 15, 2020

Copy link
Copy Markdown
Contributor

Hi @CoderPat , it has been a while, I'm really sorry about that. Are you still interested in working on that? Would you be able to synchronize with upstream? Thanks a lot for your patience!

@CoderPat

Copy link
Copy Markdown
Contributor Author

Didn't even remember this anymore 😅 It should be relatively easy to merge with upstream, I'll try to do it this week

@cmarmo cmarmo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @CoderPat.
Waiting for a core-dev review... :)

Comment thread sklearn/manifold/_locally_linear.py Resolved
Base automatically changed from master to main January 22, 2021 10:49

@jjerphan jjerphan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for adding some consistency, @CoderPat.

Here is a suggestion to improve the explicitness.

Comment on lines +300 to +304
if isinstance(X, (BallTree, KDTree, NearestNeighbors)) and \
not (X.metric == 'euclidean'
or (X.metric == 'minkowski' and X.p == 2)):
raise ValueError("metric must be euclidean or equivalent. "
"Got metric={} and p={}".format(X.metric, X.p))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is better to make the equivalence explicit here.

Suggested change
if isinstance(X, (BallTree, KDTree, NearestNeighbors)) and \
not (X.metric == 'euclidean'
or (X.metric == 'minkowski' and X.p == 2)):
raise ValueError("metric must be euclidean or equivalent. "
"Got metric={} and p={}".format(X.metric, X.p))
if (
isinstance(X, (BallTree, KDTree, NearestNeighbors)) and
not (X.metric == 'euclidean' or (X.metric == 'minkowski' and X.p == 2))
):
raise ValueError("metric must be 'euclidean' or must be 'minkowski' "
with p=2. Got metric={} and p={}".format(X.metric, X.p))

X = rand.randint(0, 100, size=(20, 3))
nbrs = neighbors.NearestNeighbors(n_neighbors=2, metric='manhattan').fit(X)

msg = "metric must be euclidean or equivalent"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
msg = "metric must be euclidean or equivalent"
msg = "metric must be 'euclidean' or must be 'minkowski' with p=2"


nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs)

if isinstance(X, (BallTree, KDTree, NearestNeighbors)) and \

@qbarthelemy qbarthelemy Jan 14, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test, allowing BallTree and KDTree, is not coherent with the current documentation of X:

    X : {array-like, NearestNeighbors}
        Sample data, shape = (n_samples, n_features), in the form of a
        numpy array or a NearestNeighbors object.

@Micky774

Copy link
Copy Markdown
Contributor

@CoderPat Do you still have the time/interest to work on this? If not, I can pick it up and finish the last few updates required.

@CoderPat

Copy link
Copy Markdown
Contributor Author

Hey I'm a bit busy this week, but could potentially do it over the weekend
But if the core-devs don't mid multi-author PR, feel free to go for it @Micky774

@Micky774

Micky774 commented Feb 6, 2022

Copy link
Copy Markdown
Contributor

The reconstruction error is dependent on the weights that are calculated, which differ on how the neighbourhood is chosen. Using a different distance metric that better encapsulate the underlying manifold will make it easier to find good reconstruction weights, thus reducing the error.

After looking through the implementation, I don't think any part of the LLE implementation depends on choice-of-metric outside of referencing the NearestNeighbor object's kneighbors method. Therefore, along with the point raised by @MHStadler, I'm also of the opinion that we don't need to to enforce a Euclidean metric choice here.

Also, here is another example using a non-Euclidean metric in LLE. Specifically, under their discussion of the algorithm they note that it can be readily generalized to more sophisticated choices of metric, including locally-defined metrics.

Thoughts @jnothman ?

@adrinjalali

Copy link
Copy Markdown
Member

Closing, there seems to be some interest in continuing this in a fresh PR.

@adrinjalali adrinjalali closed this Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

scikit-learn/sklearn/manifold/locally_linear.py could have a parameter for metric type

10 participants