-
Notifications
You must be signed in to change notification settings - Fork 1
/
tests.py
168 lines (157 loc) · 4.83 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import numpy as np
import pandas as pd
import pytest
from sklearn import cluster, datasets, decomposition
from sklearn import preprocessing as prep
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.utils.validation import check_is_fitted
from cluster_optimizer import ClusterOptimizer
class ErrorClusterer(cluster.DBSCAN):
def fit(self, X, y=None):
raise RuntimeError("This is a drill.")
@pytest.mark.filterwarnings("ignore:Estimator fit failed", "ignore:One or more")
def test_fit_error():
X, _ = datasets.make_blobs(n_samples=100, n_features=2, random_state=325)
grid = {"eps": np.arange(0.25, 3.25, 0.25), "min_samples": [5, 20, 50]}
search = ClusterOptimizer(
ErrorClusterer(), grid, scoring="silhouette", error_score=-1, refit=False
)
search.fit(X)
results = pd.DataFrame(search.results_)
assert results["noise_ratio"].isna().all()
assert np.all(results["score"] == -1)
@pytest.mark.filterwarnings("ignore:Scoring failed", "ignore:Noise ratio")
def test_singular_metric():
df, _ = datasets.load_iris(return_X_y=True, as_frame=True)
grid = {"eps": np.arange(0.25, 3.25, 0.25), "min_samples": [5, 20, 50]}
search = ClusterOptimizer(
cluster.DBSCAN(), grid, scoring="silhouette", error_score=-1
)
search.fit(df)
check_is_fitted(
search,
[
"results_",
"best_score_",
"best_index_",
"best_estimator_",
"best_params_",
"labels_",
],
)
assert round(search.best_score_, 1) == 0.7
assert search.best_params_["eps"] == 0.75
assert search.best_params_["min_samples"] == 20
assert sorted(search.results_.keys()) == sorted(
[
"fit_time",
"param_eps",
"param_min_samples",
"params",
"rank_score",
"score",
"score_time",
"noise_ratio",
"smallest_clust_size",
]
)
@pytest.mark.filterwarnings(
"ignore:Scoring failed",
"ignore:One or more",
"ignore:Noise ratio",
)
def test_multi_metric():
df, _ = datasets.load_iris(return_X_y=True, as_frame=True)
grid = {"eps": np.arange(0.25, 3.25, 0.25), "min_samples": [5, 20, 50]}
search = ClusterOptimizer(
cluster.DBSCAN(),
grid,
scoring=["silhouette", "calinski_harabasz", "davies_bouldin_score"],
refit="silhouette",
)
search.fit(df)
check_is_fitted(
search,
[
"results_",
"best_score_",
"best_index_",
"best_estimator_",
"best_params_",
"labels_",
],
)
assert round(search.best_score_, 1) == 0.7
assert search.best_params_["eps"] == 0.75
assert search.best_params_["min_samples"] == 20
assert sorted(search.results_.keys()) == sorted(
[
"fit_time",
"param_eps",
"param_min_samples",
"params",
"rank_silhouette",
"rank_davies_bouldin_score",
"davies_bouldin_score",
"rank_calinski_harabasz",
"calinski_harabasz",
"silhouette",
"score_time",
"noise_ratio",
"smallest_clust_size",
]
)
@pytest.mark.filterwarnings("ignore:Scoring failed", "ignore:Noise ratio")
def test_pipeline():
text = [
pd.DataFrame.__doc__,
pd.Series.__doc__,
prep.Binarizer.__doc__,
prep.MultiLabelBinarizer.__doc__,
prep.OneHotEncoder.__doc__,
prep.OrdinalEncoder.__doc__,
prep.FunctionTransformer.__doc__,
prep.StandardScaler.__doc__,
prep.RobustScaler.__doc__,
prep.MinMaxScaler.__doc__,
prep.PowerTransformer.__doc__,
prep.PolynomialFeatures.__doc__,
prep.SplineTransformer.__doc__,
prep.QuantileTransformer.__doc__,
]
text = [y for x in text for y in x.split("\n")]
grid = {
"kmeans__n_clusters": np.arange(3, 10),
}
pipe = make_pipeline(
TfidfVectorizer(),
decomposition.TruncatedSVD(random_state=864),
cluster.KMeans(random_state=6),
)
search = ClusterOptimizer(pipe, grid, scoring="silhouette", error_score=-1)
search.fit(text)
check_is_fitted(
search,
[
"results_",
"best_score_",
"best_index_",
"best_estimator_",
"best_params_",
"labels_",
],
)
assert 0.5 < search.best_score_
assert sorted(search.results_.keys()) == sorted(
[
"fit_time",
"param_kmeans__n_clusters",
"params",
"rank_score",
"score",
"score_time",
"noise_ratio",
"smallest_clust_size",
]
)