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

Address alex's review

  • Loading branch information...
wdevazelhes committed Feb 27, 2019
commit 58d169c20793645b757f897795cfeb49a436e557
@@ -689,11 +689,11 @@ Implementation
--------------

This implementation follows what is explained in the original paper [1]_. For
the optimisation method, it currently uses scipy's l-bfgs-b with a full
the 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 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 +705,7 @@ NCA stores a matrix of pairwise distances, taking ``n_samples ** 2`` memory.
Time complexity depends on the number of iterations done by the optimisation
algorithm. However, one can set the maximum number of iterations with the
argument ``max_iter``. For each iteration, time complexity is
``O(n_components x n_samples x min(n_samples, n_features)``.
``O(n_components x n_samples x min(n_samples, n_features))``.


Transform
@@ -152,7 +152,7 @@ indices where the value is `1` represents the assigned classes of that sample::
>>> clf.predict([[0., 0.]])
array([[0, 1]])

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

.. topic:: Examples:
@@ -154,7 +154,7 @@ one-vs-all classification.

:class:`SGDClassifier` supports both weighted classes and weighted
instances via the fit parameters ``class_weight`` and ``sample_weight``. See
the examples below and the doc string of :meth:`SGDClassifier.fit` for
the examples below and the docstring of :meth:`SGDClassifier.fit` for
further information.

.. topic:: Examples:
@@ -48,12 +48,11 @@ class NeighborhoodComponentsAnalysis(BaseEstimator, TransformerMixin):
'auto'
Depending on ``n_components``, the most reasonable initialization
will be chosen among the following ones. First, we try to use
'lda', as it uses labels information: if ``n_components <=
n_classes``, ``init='lda'``. If we can't, we then try 'pca', as it
projects data in meaningful directions (those of higher variance):
if ``n_components < min(n_features, n_samples)``, ``init = 'pca'``.
Otherwise, we just use 'identity'.
will be chosen. If ``n_components <= n_classes`` we use 'lda', as
it uses labels information. If not, but
``n_components < min(n_features, n_samples)``, we use 'pca', as
it projects data in meaningful directions (those of higher
variance). Otherwise, we just use 'identity'.
'pca'
``n_components`` principal components of the inputs passed
@@ -95,9 +94,10 @@ class NeighborhoodComponentsAnalysis(BaseEstimator, TransformerMixin):
callback : callable, optional (default=None)
If not None, this function is called after every iteration of the
optimizer, taking as arguments the current solution (transformation)
and the number of iterations. This might be useful in case one wants
to examine or store the transformation found after each iteration.
optimizer, taking as arguments the current solution (flattened
transformation matrix) and the number of iterations. This might be
useful in case one wants to examine or store the transformation
found after each iteration.
verbose : int, optional (default=0)
If 0, no progress messages will be printed.
@@ -26,8 +26,8 @@ def test_simple_example():
"""Test on a simple example.
Puts four points in the input space where the opposite labels points are
next to each other. After transform the same labels points should be next
to each other.
next to each other. After transform the samples from the same class
should be next to each other.
"""
X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])
@@ -36,23 +36,24 @@ def test_simple_example():
random_state=42)
nca.fit(X, y)
X_t = nca.transform(X)
np.testing.assert_equal(pairwise_distances(X_t).argsort()[:, 1],
np.array([2, 3, 0, 1]))
assert_array_equal(pairwise_distances(X_t).argsort()[:, 1],
np.array([2, 3, 0, 1]))


def test_toy_example_collapse_points():
"""Test on a toy example of three points that should collapse
Test that on this simple example, the new points are collapsed:
Two same label points with a different label point in the middle.
The objective is 2/(1 + exp(d/2)), with d the euclidean distance
between the two same labels points. This is maximized for d=0
(because d>=0), with an objective equal to 1 (loss=-1.).
We build a simple example: two points from the same class and a point from
a different class in the middle of them. On this simple example, the new
(transformed) points should all collapse into one single point. Indeed, the
objective is 2/(1 + exp(d/2)), with d the euclidean distance between the
two samples from the same class. This is maximized for d=0 (because d>=0),
with an objective equal to 1 (loss=-1.).
"""
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
input_dim = 5
two_points = random_state.randn(2, input_dim)
two_points = rng.randn(2, input_dim)
X = np.vstack([two_points, two_points.mean(axis=0)[np.newaxis, :]])
y = [0, 0, 1]

@@ -90,10 +91,10 @@ def test_finite_differences():
approximation.
"""
# Initialize the transformation `M`, as well as `X` and `y` and `NCA`
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
X, y = make_classification()
M = random_state.randn(random_state.randint(1, X.shape[1] + 1),
X.shape[1])
M = rng.randn(rng.randint(1, X.shape[1] + 1),
X.shape[1])
nca = NeighborhoodComponentsAnalysis()
nca.n_iter_ = 0
mask = y[:, np.newaxis] == y[np.newaxis, :]
@@ -114,7 +115,7 @@ def test_params_validation():
X = np.arange(12).reshape(4, 3)
y = [1, 1, 2, 2]
NCA = NeighborhoodComponentsAnalysis
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)

# TypeError
assert_raises(TypeError, NCA(max_iter='21').fit, X, y)
@@ -133,7 +134,7 @@ def test_params_validation():
'`max_iter`= -1, must be >= 1.',
NCA(max_iter=-1).fit, X, y)

init = random_state.rand(5, 3)
init = rng.rand(5, 3)

This comment has been minimized.

Copy link
@GaelVaroquaux

GaelVaroquaux Feb 25, 2019

Member

I would much rather use a function-local RNG than the module-level one, as it will make the test not fully reproducible.

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 25, 2019

Author Contributor

Agreed, will do

assert_raise_message(ValueError,
'The output dimensionality ({}) of the given linear '
'transformation `init` cannot be greater than its '
@@ -175,11 +176,11 @@ def test_transformation_dimensions():


def test_n_components():
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
X = np.arange(12).reshape(4, 3)
y = [1, 1, 2, 2]

init = random_state.rand(X.shape[1] - 1, 3)
init = rng.rand(X.shape[1] - 1, 3)

# n_components = X.shape[1] != transformation.shape[0]
n_components = X.shape[1]
@@ -209,7 +210,7 @@ def test_n_components():


def test_init_transformation():
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
X, y = make_blobs(n_samples=30, centers=6, n_features=5, random_state=0)

# Start learning from scratch
@@ -232,12 +233,12 @@ def test_init_transformation():
nca_lda = NeighborhoodComponentsAnalysis(init='lda')
nca_lda.fit(X, y)

init = random_state.rand(X.shape[1], X.shape[1])
init = rng.rand(X.shape[1], X.shape[1])
nca = NeighborhoodComponentsAnalysis(init=init)
nca.fit(X, y)

# init.shape[1] must match X.shape[1]
init = random_state.rand(X.shape[1], X.shape[1] + 1)
init = rng.rand(X.shape[1], X.shape[1] + 1)
nca = NeighborhoodComponentsAnalysis(init=init)
assert_raise_message(ValueError,
'The input dimensionality ({}) of the given '
@@ -247,7 +248,7 @@ def test_init_transformation():
nca.fit, X, y)

# init.shape[0] must be <= init.shape[1]
init = random_state.rand(X.shape[1] + 1, X.shape[1])
init = rng.rand(X.shape[1] + 1, X.shape[1])
nca = NeighborhoodComponentsAnalysis(init=init)
assert_raise_message(ValueError,
'The output dimensionality ({}) of the given '
@@ -257,7 +258,7 @@ def test_init_transformation():
nca.fit, X, y)

# init.shape[0] must match n_components
init = random_state.rand(X.shape[1], X.shape[1])
init = rng.rand(X.shape[1], X.shape[1])
n_components = X.shape[1] - 2
nca = NeighborhoodComponentsAnalysis(init=init, n_components=n_components)
assert_raise_message(ValueError,
@@ -276,17 +277,17 @@ def test_init_transformation():
def test_auto_init(n_samples, n_features, n_classes, n_components):
# Test that auto choose the init as expected with every configuration
# of order of n_samples, n_features, n_classes and n_components.
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
nca_base = NeighborhoodComponentsAnalysis(init='auto',
n_components=n_components,
max_iter=1,
random_state=random_state)
random_state=rng)
if n_classes >= n_samples:
pass
# n_classes > n_samples is impossible, and n_classes == n_samples
# throws an error from lda but is an absurd case
else:
X = random_state.randn(n_samples, n_features)
X = rng.randn(n_samples, n_features)

This comment has been minimized.

Copy link
@GaelVaroquaux

GaelVaroquaux Feb 25, 2019

Member

Same comment here: I would prefer to use a function-local RNG, for reproducibility of the test.

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 25, 2019

Author Contributor

Agreed, will do

y = np.tile(range(n_classes), n_samples // n_classes + 1)[:n_samples]
if n_components > n_features:
# this would return a ValueError, which is already tested in
@@ -359,13 +360,13 @@ def test_warm_start_effectiveness():
def test_verbose(init_name, capsys):
# assert there is proper output when verbose = 1, for every initialization
# except auto because auto will call one of the others
random_state = np.random.RandomState(42)
rng = np.random.RandomState(42)
X, y = make_blobs(n_samples=30, centers=6, n_features=5, random_state=0)
regexp_init = r'... done in \ *\d+\.\d{2}s'
msgs = {'pca': "Finding principal components" + regexp_init,
'lda': "Finding most discriminative components" + regexp_init}
if init_name == 'precomputed':
This conversation was marked as resolved by GaelVaroquaux

This comment has been minimized.

Copy link
@GaelVaroquaux

GaelVaroquaux Feb 25, 2019

Member

Module-level RNG here too.

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 25, 2019

Author Contributor

Agreed, will do

init = random_state.randn(X.shape[1], X.shape[1])
init = rng.randn(X.shape[1], X.shape[1])
else:
init = init_name
nca = NeighborhoodComponentsAnalysis(verbose=1, init=init)
@@ -461,6 +462,7 @@ def test_callback(capsys):
max_iter = 10

def my_cb(transformation, n_iter):
assert transformation.shape == (iris_data.shape[1]**2,)
rem_iter = max_iter - n_iter

This comment has been minimized.

Copy link
@agramfort

agramfort Feb 27, 2019

Member

can you also test that transformation has the right shape here?

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 27, 2019

Author Contributor

Yes, I agree, that would take advantage of this test to test that the shape is the right one inside the iterations
Should I even do a separate test for that or here is fine ?

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 27, 2019

Author Contributor

It made me think that I should advertise the fact that callbacks needs to be applied on the raveled transformation matrix, so I added this to the docstring of nca:

-        optimizer, taking as arguments the current solution (transformation)
-        and the number of iterations. This might be useful in case one wants
-        to examine or store the transformation found after each iteration.

+       optimizer, taking as arguments the current solution (flattened
+       transformation matrix) and the number of iterations. This might be
+       useful in case one wants to examine or store the transformation
+       found after each iteration.

This comment has been minimized.

Copy link
@agramfort

agramfort Feb 27, 2019

Member

do it here. no need for a new test.
ok to the change of docstring.

This comment has been minimized.

Copy link
@agramfort

agramfort Feb 27, 2019

Member

don't forget to add a test of shape here

This comment has been minimized.

Copy link
@wdevazelhes

wdevazelhes Feb 28, 2019

Author Contributor

do it here. no need for a new test.
ok to the change of docstring.

Allright,

don't forget to add a test of shape here

Done, in commit 58d169c

print('{} iterations remaining...'.format(rem_iter))

@@ -953,7 +953,7 @@ def check_scalar(x, name, target_type, min_val=None, max_val=None):
Acceptable data types for the parameter.
min_val : float or int, optional (default=None)
The minimum value value the parameter can take. If None (default) it
The minimum valid value the parameter can take. If None (default) it
is implied that the parameter does not have a lower bound.
max_val : float or int, optional (default=None)
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.