Skip to content

Commit d2341b5

Browse files
committed
TST: test verbosity mini_bach_kmeans
1 parent a27c0db commit d2341b5

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

sklearn/cluster/tests/test_k_means.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""Testing for K-means"""
2+
from cStringIO import StringIO
3+
import sys
4+
import warnings
25

36
import numpy as np
4-
import warnings
57
from scipy import sparse as sp
68

79
from sklearn.utils.testing import assert_equal
@@ -265,12 +267,12 @@ def test_mb_k_means_plus_plus_init_dense_array():
265267
def test_mb_kmeans_verbose():
266268
mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters,
267269
random_state=42, verbose=1)
268-
from cStringIO import StringIO
269-
import sys
270270
old_stdout = sys.stdout
271271
sys.stdout = StringIO()
272-
mb_k_means.fit(X)
273-
sys.stdout = old_stdout
272+
try:
273+
mb_k_means.fit(X)
274+
finally:
275+
sys.stdout = old_stdout
274276

275277

276278
def test_mb_k_means_plus_plus_init_sparse_matrix():
@@ -325,9 +327,16 @@ def test_minibatch_reassign():
325327
random_state=42)
326328
mb_k_means.fit(X)
327329
centers_before = mb_k_means.cluster_centers_.copy()
328-
_mini_batch_step(X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_,
329-
mb_k_means.counts_, np.zeros(X.shape[1], np.double),
330-
True, random_state=42, reassignment_ratio=1)
330+
try:
331+
old_stdout = sys.stdout
332+
sys.stdout = StringIO()
333+
# Turn on verbosity to smoke test the display code
334+
_mini_batch_step(X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_,
335+
mb_k_means.counts_, np.zeros(X.shape[1], np.double),
336+
False, random_reassign=True, random_state=42,
337+
reassignment_ratio=1, verbose=True)
338+
finally:
339+
sys.stdout = old_stdout
331340
centers_after = mb_k_means.cluster_centers_.copy()
332341
# Check that all the centers have moved
333342
assert_greater(((centers_before - centers_after)**2).sum(axis=1).min(),
@@ -563,13 +572,13 @@ def test_n_init():
563572
def test_k_means_function():
564573
# test calling the k_means function directly
565574
# catch output
566-
from cStringIO import StringIO
567-
import sys
568575
old_stdout = sys.stdout
569576
sys.stdout = StringIO()
570-
cluster_centers, labels, inertia = k_means(X, n_clusters=n_clusters,
571-
verbose=True)
572-
sys.stdout = old_stdout
577+
try:
578+
cluster_centers, labels, inertia = k_means(X, n_clusters=n_clusters,
579+
verbose=True)
580+
finally:
581+
sys.stdout = old_stdout
573582
centers = cluster_centers
574583
assert_equal(centers.shape, (n_clusters, n_features))
575584

0 commit comments

Comments
 (0)