def test_predict_diff_dimention_data(): bkmeans = BisectingKMeans(max_n_clusters=3) X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [10]]) bkmeans.fit(X) with pytest.raises(ValueError): bkmeans.predict(np.array([[1,2]]))
def test_predict(max_n_clusters): X, _ = make_blobs(n_samples=500, n_features=10, centers=max_n_clusters, random_state=0) clf = BisectingKMeans(max_n_clusters) clf.fit(X) labels = clf.labels_ # re-predict labels for training set using predict pred = clf.predict(X) assert_array_equal(pred, labels) # predict centroid labels (this should pass once fit is implemented) pred = clf.predict(clf.centroids) assert_array_equal(pred, np.arange(clf.max_n_clusters))
def test_three_clusters(bisecting_strategy): """Tries to perform bisect k-means for three clusters to check if splitting data is performed correctly. """ # X = np.array([[1, 2], [1, 4], [1, 0], # [10, 2], [10, 4], [10, 0], # [10, 6], [10, 8], [10, 10]]) # X[0][1] swapped with X[1][1] intentionally for checking labeling X = np.array([[1, 2], [10, 4], [1, 0], [10, 2], [1, 4], [10, 0], [10, 6], [10, 8], [10, 10]]) bisect_means = BisectingKMeans(n_clusters=3, random_state=0, bisecting_strategy=bisecting_strategy) bisect_means.fit(X) expected_centers = [[10, 2], [10, 8], [1, 2]] expected_predict = [2, 0] expected_labels = [2, 0, 2, 0, 2, 0, 1, 1, 1] assert_allclose(expected_centers, bisect_means.cluster_centers_) assert_array_equal(expected_predict, bisect_means.predict([[0, 0], [12, 3]])) assert_array_equal(expected_labels, bisect_means.labels_)
def test_one_cluster(): """Test single cluster.""" X = np.array([[1, 2], [10, 2], [10, 8]]) bisect_means = BisectingKMeans(n_clusters=1, random_state=0).fit(X) # All labels from fit or predict should be equal 0 assert all(bisect_means.labels_ == 0) assert all(bisect_means.predict(X) == 0) assert_allclose(bisect_means.cluster_centers_, X.mean(axis=0).reshape(1, -1))
def test_fit_predict(is_sparse): """Check if labels from fit(X) method are same as from fit(X).predict(X).""" rng = np.random.RandomState(0) X = rng.rand(10, 2) if is_sparse: X[X < 0.8] = 0 X = sp.csr_matrix(X) bisect_means = BisectingKMeans(n_clusters=3, random_state=0) bisect_means.fit(X) assert_array_equal(bisect_means.labels_, bisect_means.predict(X))
def test_predict_not_fitted(): bkmeans = BisectingKMeans(max_n_clusters=2) X = np.zeros([3]) with pytest.raises(NotFittedError): bkmeans.predict(X)