Skip to content
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

[MRG+2] Neighborhood Components Analysis #10058

Merged
merged 89 commits into from Feb 28, 2019
Merged
Changes from 1 commit
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
849a8d8
first commit
wdevazelhes Oct 27, 2017
04222de
minor corrections in docstring
wdevazelhes Oct 27, 2017
34c5457
remove comment
wdevazelhes Oct 27, 2017
89f68ee
Add verbose during iterations
wdevazelhes Oct 30, 2017
42e078a
Update code according to code review:
wdevazelhes Oct 31, 2017
4c7c0d4
Remove _make_masks and use OneHotEncoder instead
wdevazelhes Oct 31, 2017
4c81a16
precise that distances are squared
wdevazelhes Oct 31, 2017
824e940
remove useless None
wdevazelhes Oct 31, 2017
d4294ac
simplify tests
wdevazelhes Oct 31, 2017
296e295
ensure min samples = 2 to make check_fit2d_1sample pass
wdevazelhes Nov 2, 2017
616f9a2
Do not precompute pairwise differences
wdevazelhes Nov 7, 2017
12cf3a9
add example
wdevazelhes Nov 14, 2017
7b37e8d
reorganize transposes
wdevazelhes Nov 14, 2017
48cab11
simplify gradient
wdevazelhes Nov 14, 2017
47928aa
Fixes according to code review
wdevazelhes Nov 22, 2017
4612e5f
Retrieving LMNN documentation in order to adapt it to NCA
wdevazelhes Dec 13, 2017
27ab46b
Adapt documentation to Neighborhood Components Analysis
wdevazelhes Dec 29, 2017
44e19d6
fix pep8 errors
wdevazelhes Jan 3, 2018
dcb1a8a
fix flake8 error
wdevazelhes Jan 3, 2018
6ba1692
fix encoding error
wdevazelhes Jan 3, 2018
03b126b
changes according to review https://github.com/scikit-learn/scikit-le…
wdevazelhes Jan 15, 2018
8b5646c
correct objective function doc
wdevazelhes Jan 15, 2018
a7f6458
Merge branch 'master' into nca
wdevazelhes May 28, 2018
9a09e29
Add batch computations of loss and gradient.
wdevazelhes Jun 5, 2018
7721221
Update documentation.
wdevazelhes Jun 5, 2018
d5de730
Merge branch 'master' into nca
wdevazelhes Jun 5, 2018
173a966
FIX: import scipy.misc.logsumexp for older versions of scipy, and sci…
wdevazelhes Jun 6, 2018
2cd3bf6
FIX: remove newly introduced keepdims for logsumexp
wdevazelhes Jun 7, 2018
c50c841
FIX: remove unused old masks and use the new mask instead
wdevazelhes Jun 7, 2018
094aa97
FIX: fix doctest CI fail by putting ellipsis
wdevazelhes Jun 20, 2018
e6daf4e
FIX: fix doctest CI fail by putting ellipsis, this time in rst file
wdevazelhes Jun 20, 2018
e160a6e
FIX: fix doctest CI fail by putting ellipsis, this time in rst file
wdevazelhes Jun 20, 2018
fbc679b
Updates to be coherent with latest changes from pr #8602 (commits htt…
wdevazelhes Jun 22, 2018
1e93e82
Merge branch 'nca_feat/comments_changes' into nca
wdevazelhes Jun 22, 2018
92faf4f
ENH: Add warm_start feature from LMNN (PR #8602)
wdevazelhes Jun 22, 2018
b172898
FIX: rename remaining old n_features_out to n_components
wdevazelhes Jun 22, 2018
816f3de
FIX: Update doc like in commit https://github.com/scikit-learn/scikit…
wdevazelhes Jun 22, 2018
85b2cdd
FIX: make test_warm_start_effectiveness_work
wdevazelhes Jun 22, 2018
4ed68dd
ENH: Add possible LDA initialization
wdevazelhes Jun 22, 2018
1f9c208
ENH: add 'auto' initialization
wdevazelhes Jun 25, 2018
b0a96f9
Merge branch 'master' into nca
wdevazelhes Jun 25, 2018
e050128
FIX test appropriate message depending on init
wdevazelhes Jun 25, 2018
ead9850
FIX import name with relative path
wdevazelhes Jun 25, 2018
a807df2
FIX simplify test and check almost equal to pass tests on linux 32 bits
wdevazelhes Jun 25, 2018
e00d4a1
FIX Move LDA import inside NCA class to avoid circular dependencies
wdevazelhes Jun 26, 2018
aa90c9b
DOC add what s new entry
wdevazelhes Jun 28, 2018
85bd54f
MAINT simplify gradient testing
wdevazelhes Jun 29, 2018
aa9ace7
TST FIX be more tolerant on decimals for older versions of numerical …
wdevazelhes Jun 29, 2018
cc07261
STY fix continuation lines, removing backslashes
wdevazelhes Jun 29, 2018
16cf04d
FIX: fix logsumexp import
wdevazelhes Jul 15, 2018
8c7af3c
TST: simplify verbose testing with pytest capsys
wdevazelhes Jul 23, 2018
8ce872f
Merge branch 'master' into nca
wdevazelhes Jul 23, 2018
27f2b5c
TST: check more explicitely verbose
wdevazelhes Aug 1, 2018
85f8d21
FIX: remove non-ASCII character
wdevazelhes Aug 1, 2018
396f30f
ENH: simplify gradient expression
wdevazelhes Aug 17, 2018
8830373
MAINT: address review https://github.com/scikit-learn/scikit-learn/pu…
wdevazelhes Nov 29, 2018
16b022a
Merge branch 'master' into nca
wdevazelhes Nov 29, 2018
ded5ecb
DOC: Add what's new entry
wdevazelhes Nov 29, 2018
648ed5f
Merge branch 'master' into nca
wdevazelhes Dec 6, 2018
589f57d
FIX: try raw string to pass flake8 (cf. https://github.com/iodide-pro…
wdevazelhes Dec 6, 2018
600adf2
FIX: try the exact syntax that passed the linter
wdevazelhes Dec 6, 2018
d274c4a
TST: give some tolerance for test_toy_example_collapse_points
wdevazelhes Dec 6, 2018
2dbf064
relaunch travis
wdevazelhes Dec 7, 2018
e17003e
FIX: use checked_random_state instead of np.random
wdevazelhes Dec 12, 2018
32118aa
FIX: delete iterate.dat
wdevazelhes Dec 12, 2018
5c2154f
Merge branch 'master' into nca
wdevazelhes Dec 12, 2018
cf55015
FIX: Fix dealing with the case of LinearDiscriminantAnalysis initiali…
wdevazelhes Dec 12, 2018
44839a0
Address reviews https://github.com/scikit-learn/scikit-learn/pull/100…
wdevazelhes Jan 18, 2019
822620d
STY: fix PEP8 line too long error
wdevazelhes Jan 18, 2019
41d3cef
Fix doctest
wdevazelhes Jan 18, 2019
faa84fc
FIX: remove deprecated assert_true
wdevazelhes Jan 22, 2019
db2950a
TST fix assertion always true in tests
wdevazelhes Jan 22, 2019
f16770c
TST: fix PEP8 indent error
wdevazelhes Jan 22, 2019
4f7375e
Merge branch 'master' into nca
wdevazelhes Jan 22, 2019
49189c6
API: remove the possibility to store the opt_result (see https://gith…
wdevazelhes Jan 22, 2019
0fda2ca
Merge branch 'master' into nca
wdevazelhes Feb 25, 2019
f015bad
Move examples up in documentation and add NCA to manifold examples
wdevazelhes Feb 25, 2019
0e5d5b3
STY: fix pep8 errors
wdevazelhes Feb 25, 2019
77dc953
adress gael's review except https://github.com/scikit-learn/scikit-le…
wdevazelhes Feb 26, 2019
a653189
Address aurelien's review
wdevazelhes Feb 26, 2019
be9b1e1
Simplify test about auto init even more
wdevazelhes Feb 26, 2019
2b1c8f2
Fix doc and replace embedding by projection for consistency
wdevazelhes Feb 26, 2019
af14e5d
Address Gael's review
wdevazelhes Feb 26, 2019
3a78d1a
few nitpicks and make some links in the doc work
wdevazelhes Feb 27, 2019
58d169c
Address alex's review
wdevazelhes Feb 27, 2019
fbd28e1
Adress Alex's review
wdevazelhes Feb 28, 2019
8d65ebc
Add authors in test too
wdevazelhes Feb 28, 2019
ed0d23a
add check_scalar to utils
wdevazelhes Feb 28, 2019
6dbef86
MajorFeature > API
jnothman Feb 28, 2019
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

changes according to review #10058 (review)

  • Loading branch information...
wdevazelhes committed Jan 15, 2018
commit 03b126b0cacc1a002a4c447312b15a2d2f9d25a5
@@ -524,13 +524,13 @@ Neighborhood Components Analysis

.. sectionauthor:: William de Vazelhes <william.de-vazelhes@inria.fr>

Neighborhood Components Analysis (NCA, :class:`NeighborhoodComponentsAnalysis` )
Neighborhood Components Analysis (NCA, :class:`NeighborhoodComponentsAnalysis`)
is a distance metric learning algorithm which aims to improve the accuracy of
nearest neighbors classification compared to the standard Euclidean distance.
The algorithm directly maximizes a stochastic variant of the
leave-one-out k-nearest neighbors (KNN) score on the training set. It can also
learn a low-dimensional linear embedding of labeled data that can be
used for data visualization and fast classification.
learn a low-dimensional linear embedding of data that can be used for
data visualization and fast classification.

.. |nca_illustration_1| image:: ../auto_examples/neighbors/images/sphx_glr_plot_nca_illustration_001.png
:target: ../auto_examples/neighbors/plot_nca_illustration.html
@@ -543,36 +543,36 @@ used for data visualization and fast classification.
.. centered:: |nca_illustration_1| |nca_illustration_2|


This comment has been minimized.

Copy link
@jnothman

jnothman Jan 10, 2019

Member

drop blank

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Jan 18, 2019

Author Contributor

Done

In the above figure, we consider some points from a randomly generated dataset.
We focus on the stochastic KNN classification of point n°3, the thickness of a
bond representing a softmax distance hence the weight of the neighbor vote in
the classification. In the original space, sample 3 has many stochastic
neighbors from various classes, so the right class is not very likely. However,
in the embedding space, the only non-negligible stochastic neighbors are from
the same class as sample 3, guaranteeing that the latter will be well
classified.
In the above illustrating figure, we consider some points from a randomly
generated dataset. We focus on the stochastic KNN classification of point n°3,

This comment has been minimized.

Copy link
@jnothman

jnothman Jan 10, 2019

Member

n° -> no.?

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Jan 18, 2019

Author Contributor

Done

the thickness of a bond representing a softmax distance hence the weight of the

This comment has been minimized.

Copy link
@bellet

bellet Feb 25, 2019

Contributor

maybe clarify a bit this sentence because at this point there is not so much context on the method for the user to rely on

proposition:
"The thickness of a link between sample 3 and another point is proportional to their distance, and can be seen as the relative weight (or probability) that a stochastic nearest neighbor prediction rule would assign to this point."

it is possible to refer to the mathematical formulation section for details, but maybe it is better not to do this to avoid confusing users

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 26, 2019

Author Contributor

Yes I agree, I'll go for your proposition it's clearer
I'll add a link to the mathematical formulation, they could leave it alone and read the examples before, depending on what they would prefer

neighbor vote in the classification. In the original space, sample 3 has many
stochastic neighbors from various classes, so the right class is not very
likely. However, in the embedding space learned by NCA, the only non-negligible

This comment has been minimized.

Copy link
@bellet

bellet Feb 25, 2019

Contributor

the only stochastic neighbors with non-negligible weight?

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 26, 2019

Author Contributor

Yes that's better, will do

stochastic neighbors are from the same class as sample 3, guaranteeing that the
latter will be well classified.


This conversation was marked as resolved by GaelVaroquaux

This comment has been minimized.

Copy link
@jnothman

jnothman Nov 18, 2018

Member

too many blank

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Nov 29, 2018

Author Contributor

done


Classification
--------------

Combined with a nearest neighbors classifier (:class:`KNeighborsClassifier`),
this method is attractive for classification because it can naturally
handle multi-class problems without any increase in the model size, and no
additional parameter than that of KNN has to be selected by the user before
training.
NCA is attractive for classification because it can naturally handle
multi-class problems without any increase in the model size, and does not
introduce additional parameters that require fine-tuning by the user.

Neighborhood Components Analysis classification has been shown to work well in
practice for data sets of varying size and difficulty. In contrast to
related methods such as Linear Discriminant Analysis, NCA does not make any
assumptions about the class distributions. The nearest neighbor classification
can naturally produce highly irregular decision boundaries.
NCA classification has been shown to work well in practice for data sets of
varying size and difficulty. In contrast to related methods such as Linear
Discriminant Analysis, NCA does not make any assumptions about the class
distributions. The nearest neighbor classification can naturally produce highly
irregular decision boundaries.

To use this model for classification, one needs to combine a
:class:`NeighborhoodComponentsAnalysis` instance that learns the optimal
transformation with a :class:`KNeighborsClassifier` instance that performs the
classification in the embedded space. Here is an example using the two classes:
classification in the embedding space. Here is an example using the two
classes:

>>> from sklearn.neighbors import NeighborhoodComponentsAnalysis
>>> from sklearn.neighbors import KNeighborsClassifier
@@ -614,28 +614,26 @@ that automatically applies the transformation when fitting or predicting:
.. centered:: |nca_classification_1| |nca_classification_2|

The plot shows decision boundaries for Nearest Neighbor Classification and
Neighborhood Components Analysis classification, when training and scoring
on only two features, for visualisation purpose.
Neighborhood Components Analysis classification on the iris dataset, when
training and scoring on only two features, for visualisation purpose.

This comment has been minimized.

Copy link
@bellet

bellet Feb 25, 2019

Contributor

purposes

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 26, 2019

Author Contributor

yep, thanks



Dimensionality reduction
------------------------

:class:`NeighborhoodComponentsAnalysis` can be used to perform supervised
dimensionality reduction. The input data are projected onto a linear subspace
consisting of the directions which minimize the NCA objective. The desired
dimensionality can be set using the parameter ``n_features_out``. For instance,
the following shows a comparison of dimensionality reduction with Principal
Component Analysis (:class:`sklearn.decomposition.PCA`), Linear Discriminant
Analysis (:class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`)
and Neighborhood Component Analysis (:class:`NeighborhoodComponentsAnalysis`)
on the Digits dataset, a dataset with size :math:`n_{samples} = 1797` and
:math:`n_{features} = 64`. The data set is splitted in a training and test set
of equal size. What is more, a :class:`sklearn.preprocessing.StandardScaler`
fitted on the training set and transforms the data from both sets. For
evaluation the 3-nearest neighbor classification accuracy is computed on the
2-dimensional embedding found by each method. Each data sample belongs to one
of 10 classes.
NCA can be used to perform supervised dimensionality reduction. The input data
are projected onto a linear subspace consisting of the directions which
minimize the NCA objective. The desired dimensionality can be set using the
parameter ``n_features_out``. For instance, the following figure shows a
comparison of dimensionality reduction with Principal Component Analysis
(:class:`sklearn.decomposition.PCA`), Linear Discriminant Analysis
(:class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`) and
Neighborhood Component Analysis (:class:`NeighborhoodComponentsAnalysis`) on
the Digits dataset, a dataset with size :math:`n_{samples} = 1797` and
:math:`n_{features} = 64`. The data set is split into a training and a test set
of equal size, then standardized. For evaluation the 3-nearest neighbor
classification accuracy is computed on the 2-dimensional embedding found by
each method. Each data sample belongs to one of 10 classes.

.. |nca_dim_reduction_1| image:: ../auto_examples/neighbors/images/sphx_glr_plot_nca_dim_reduction_001.png
:target: ../auto_examples/neighbors/plot_nca_dim_reduction.html
@@ -655,23 +653,30 @@ of 10 classes.
Mathematical formulation
------------------------

NCA learns a linear transformation matrix :math:`L` of
size ``(n_features_out, n_features)``, which maximises in average the
probability :math:`p_i` of sample :math:`i` being
classified as :math:`C_i`, defined by:
The goal of NCA is to learn an optimal linear transformation matrix :math:`L^*`
of size ``(n_features_out, n_features)``, which maximises in average the
probability :math:`p_i` of sample :math:`i` being correctly classified, i.e.:

.. math::
p_{i}=\sum\nolimits_{j \in C_i}{p_{i j}}
L^*= \max\limits_{L} \sum\limits_{i=0}^{N - 1} p_{i}

This comment has been minimized.

Copy link
@bellet

bellet Jan 15, 2018

Contributor

should be argmax instead of max (or simply do not define L^*)

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Jan 15, 2018

Author Contributor

Ah yes, indeed

with :math:`N` = ``n_samples`` and :math:`p_i` the probability of sample
:math:`i` being correctly classified according to a stochastic nearest
neighbors rule in the learned embedded space:

.. math::
p_{i}=\sum\limits_{j \in C_i}{p_{i j}}
where :math:`C_i` is the set of points in the same class as sample :math:`i`,
and :math:`p_{i j}` is the softmax over Euclidean distances in the
transformed space:
and :math:`p_{i j}` is the softmax over Euclidean distances in the embedded
space:

.. math::
p_{i j} = \frac{\exp(-||L x_i - L x_j||^2)}{\sum\nolimits_{k \ne
i} {\exp{-(||L x_i - L x_k||^2)}}} , p_{i i} = 0
p_{i j} = \frac{\exp(-||L x_i - L x_j||^2)}{\sum\limits_{k \ne
i} {\exp{-(||L x_i - L x_k||^2)}}} , \quad p_{i i} = 0
Mahalanobis distance
@@ -690,12 +695,12 @@ where :math:`M = L^T L` is a symmetric positive semi-definite matrix of size
Implementation
--------------

This implementation follows what is explained in the paper. For the
This implementation follows what is explained in the original paper. For the

This comment has been minimized.

Copy link
@bellet

bellet Feb 25, 2019

Contributor

pointer to the reference?

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 26, 2019

Author Contributor

Yes that would be better indeed

optimisation method, it currently uses scipy's l-bfgs-b with a full gradient
computation at each iteration, to avoid to tune the learning rate and provide a
computation at each iteration, to avoid to tune the learning rate and provide
stable learning.

See the examples below and the doc string of
See the examples below and the docstring of
:meth:`NeighborhoodComponentsAnalysis.fit` for further information.

Complexity
@@ -705,7 +710,7 @@ Training
^^^^^^^^
First, time complexity depends on the number of iterations done. Besides,
currently the algorithm has to compute, for each sample, its contribution to
the cost and the gradient. The more complex operation in this computation are
the cost and the gradient. The dominating terms in this computation are
the dot products between differences in the input space and differences in the
embedded space, which has complexity ``n_features_out * n_features *
n_samples``. Therefore time complexity is ``O[n_iterations * n_samples^2 *
@@ -35,9 +35,9 @@
ax = plt.gca()

# Draw the graph nodes
ax.scatter(X[:, 0], X[:, 1], s=300, c=y, cmap='tab10', alpha=0.4)
for i in range(X.shape[0]):
ax.text(X[i, 0], X[i, 1], str(i), va='center', ha='center')
ax.scatter(X[i, 0], X[i, 1], s=300, c=cm.Set1(y[i]), alpha=0.4)


def p_i(X, i):
@@ -63,7 +63,7 @@ def relate_point(X, i, ax):
thickness = p_i(X, i)
if i != j:
line = ([pt_i[0], pt_j[0]], [pt_i[1], pt_j[1]])
ax.plot(*line, c=cm.tab10(y[j]),
ax.plot(*line, c=cm.Set1(y[j]),
linewidth=5*thickness[j])


@@ -87,14 +87,13 @@ def relate_point(X, i, ax):
# Get the embedding and find the new nearest neighbors
X_embedded = nca.transform(X)

ax2.scatter(X_embedded[:, 0], X_embedded[:, 1], s=300, c=y, cmap='tab10',
alpha=0.4)

relate_point(X_embedded, i, ax2)

for i in range(len(X)):
ax2.text(X_embedded[i, 0], X_embedded[i, 1], str(i),
va='center', ha='center')
ax2.scatter(X_embedded[i, 0], X_embedded[i, 1], s=300, c=cm.Set1(y[i]),
alpha=0.4)

# Make axes equal so that boundaries are displayed correctly as circles
ax2.set_title("NCA embedding")
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.