|
1 | 1 | """Testing for K-means""" |
| 2 | +from cStringIO import StringIO |
| 3 | +import sys |
| 4 | +import warnings |
2 | 5 |
|
3 | 6 | import numpy as np |
4 | | -import warnings |
5 | 7 | from scipy import sparse as sp |
6 | 8 |
|
7 | 9 | from sklearn.utils.testing import assert_equal |
@@ -265,12 +267,12 @@ def test_mb_k_means_plus_plus_init_dense_array(): |
265 | 267 | def test_mb_kmeans_verbose(): |
266 | 268 | mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, |
267 | 269 | random_state=42, verbose=1) |
268 | | - from cStringIO import StringIO |
269 | | - import sys |
270 | 270 | old_stdout = sys.stdout |
271 | 271 | 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 |
274 | 276 |
|
275 | 277 |
|
276 | 278 | def test_mb_k_means_plus_plus_init_sparse_matrix(): |
@@ -325,9 +327,16 @@ def test_minibatch_reassign(): |
325 | 327 | random_state=42) |
326 | 328 | mb_k_means.fit(X) |
327 | 329 | 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 |
331 | 340 | centers_after = mb_k_means.cluster_centers_.copy() |
332 | 341 | # Check that all the centers have moved |
333 | 342 | assert_greater(((centers_before - centers_after)**2).sum(axis=1).min(), |
@@ -563,13 +572,13 @@ def test_n_init(): |
563 | 572 | def test_k_means_function(): |
564 | 573 | # test calling the k_means function directly |
565 | 574 | # catch output |
566 | | - from cStringIO import StringIO |
567 | | - import sys |
568 | 575 | old_stdout = sys.stdout |
569 | 576 | 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 |
573 | 582 | centers = cluster_centers |
574 | 583 | assert_equal(centers.shape, (n_clusters, n_features)) |
575 | 584 |
|
|
0 commit comments