8000 [MRG] Error for cosine affinity when zero vectors present (#7943) · scikit-learn/scikit-learn@3d99769 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3d99769

Browse files
mthorrellGaelVaroquaux
authored andcommitted
[MRG] Error for cosine affinity when zero vectors present (#7943)
* cosine affinity cannot be used when X contains zero vectors * fixed issue with tabs spaces * changed to np.any and created a test for this new ValueError * use assert_raise_message and flipped order of if conditions * fixed 0 row calculation
1 parent da96da9 commit 3d99769

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

sklearn/cluster/hierarchical.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,10 @@ def linkage_tree(X, connectivity=None, n_clusters=None, linkage='complete',
432432
'Unknown linkage option, linkage should be one '
433433
'of %s, but %s was given' % (linkage_choices.keys(), linkage))
434434

435+
if affinity == 'cosine' and np.any(~np.any(X, axis=1)):
436+
raise ValueError(
437+
'Cosine affinity cannot be used when X contains zero vectors')
438+
435439
if connectivity is None:
436440
from scipy.cluster import hierarchy # imports PIL
437441

sklearn/cluster/tests/test_hierarchical.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,15 @@ def test_agglomerative_clustering_wrong_arg_memory():
128128
assert_raises(ValueError, clustering.fit, X)
129129

130130

131+
def test_zero_cosine_linkage_tree():
132+
# Check that zero vectors in X produce an error when
133+
# 'cosine' affinity is used
134+
X = np.array([[0, 1],
135+
[0, 0]])
136+
msg = 'Cosine affinity cannot be used when X contains zero vectors'
137+
assert_raise_message(ValueError, msg, linkage_tree, X, affinity='cosine')
138+
139+
131140
def test_agglomerative_clustering():
132141
# Check that we obtain the correct number of clusters with
133142
# agglomerative clustering.

0 commit comments

Comments
 (0)
0