Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[MRG+1] Pass affinity to fix connectivity in linkage tree #9357

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

Merged
merged 1 commit into from
Jul 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions sklearn/cluster/hierarchical.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@
# For non fully-connected graphs


def _fix_connectivity(X, connectivity, n_components=None,
affinity="euclidean"):
def _fix_connectivity(X, connectivity, affinity):
Copy link
Member

Choose a reason for hiding this comment

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

Much clearer.

"""
Fixes the connectivity matrix

Expand Down Expand Up @@ -190,7 +189,8 @@ def ward_tree(X, connectivity=None, n_clusters=None, return_distance=False):
else:
return children_, 1, n_samples, None

connectivity, n_components = _fix_connectivity(X, connectivity)
connectivity, n_components = _fix_connectivity(X, connectivity,
affinity='euclidean')
if n_clusters is None:
n_nodes = 2 * n_samples - 1
else:
Expand Down Expand Up @@ -415,7 +415,8 @@ def linkage_tree(X, connectivity=None, n_components=None,
return children_, 1, n_samples, None, distances
return children_, 1, n_samples, None

connectivity, n_components = _fix_connectivity(X, connectivity)
connectivity, n_components = _fix_connectivity(X, connectivity,
affinity=affinity)

connectivity = connectivity.tocoo()
# Put the diagonal to zero
Expand Down
27 changes: 27 additions & 0 deletions sklearn/cluster/tests/test_hierarchical.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,30 @@ def test_agg_n_clusters():
msg = ("n_clusters should be an integer greater than 0."
" %s was provided." % str(agc.n_clusters))
assert_raise_message(ValueError, msg, agc.fit, X)


def test_affinity_passed_to_fix_connectivity():
# Test that the affinity parameter is actually passed to the pairwise
# function

size = 2
rng = np.random.RandomState(0)
X = rng.randn(size, size)
mask = np.array([True, False, False, True])

connectivity = grid_to_graph(n_x=size, n_y=size,
mask=mask, return_as=np.ndarray)

class FakeAffinity:
def __init__(self):
self.counter = 0

def increment(self, *args, **kwargs):
self.counter += 1
return self.counter

fa = FakeAffinity()

linkage_tree(X, connectivity=connectivity, affinity=fa.increment)

assert_equal(fa.counter, 3)