/
main.py
173 lines (147 loc) · 5.22 KB
/
main.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
169
170
171
172
173
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn import datasets
from sklearn.cluster import MeanShift
from dist_metrics import dist_metrics
def predict(x, mu, **kwargs):
r = dist_metrics[dist_metric](x, mu)
return np.argmin(r)
def cluster_points(X, mu, **kwargs):
clusters = {}
for x in X:
cluster_num = predict(x, mu, dist_metric=kwargs['dist_metric'], )
try:
clusters[cluster_num].append(x)
except KeyError:
clusters[cluster_num] = [x]
return clusters
def has_converged(mu, oldmu):
return set([tuple(a) for a in mu]) == set([tuple(a) for a in oldmu])
def reevaluate_centers(clusters):
newmu = []
keys = sorted(clusters.keys())
for k in keys:
newmu.append(np.mean(clusters[k], axis=0))
return newmu
def find_centers(X, k, **kwargs):
# Initialize to K random centers
oldmu = []
mu = [X[c] for c in np.random.randint(X.shape[0], size=k)]
clusters = {}
while not has_converged(mu, oldmu):
oldmu = mu
clusters = cluster_points(X, mu, **kwargs)
mu = reevaluate_centers(clusters)
if kwargs['step_plot']:
plot_data_with_centers(X, mu, **kwargs)
return mu, clusters
def plot_data_with_centers(data, centers, labels, **kwargs):
data1 = pd.DataFrame(data=data)
data1['target'] = pd.Series(labels, index=data1.index)
g = sns.FacetGrid(data1, hue='target', palette="tab20", size=5)
g.map(plt.scatter, 0, 1, s=100, linewidth=.5, edgecolor="white")
for ax in g.axes.flat:
for center in centers:
ax.plot(center[0], center[1], 'kv', markersize=15)
g.add_legend()
if 'name' in kwargs:
plt.title(kwargs['name'])
plt.show()
def main(X, bandwith=None, step_plot=False, **kwargs):
"""
Parameters
----------
X: list
Dataset
k: int
Number of centers
dist_metric: {'euclid', 'euclid_square', 'manhattan', 'chebyshev', 'power'}
Distance metric
power_root: int
Root for 'power' metric
power_power: int
Power for 'power' metric
step_plot: bool
Plot for an every iteration
"""
kwargs['step_plot'] = step_plot
if bandwith:
mean_shift = MeanShift(bandwidth=bandwith).fit(X)
else:
mean_shift = MeanShift().fit(X)
plot_data_with_centers(X, mean_shift.cluster_centers_, mean_shift.labels_, **kwargs)
if __name__ == '__main__':
n_samples = 1000
random_state = 170
transformation = [[0.6, -0.6], [-0.4, 0.8]]
models = [
{
'name': 'Far Blobs',
'X':
datasets.make_blobs(n_samples=n_samples, centers=25, random_state=0, center_box=(-10000, 10000),
cluster_std=50)[0],
},
{
'name': 'Noisy Circles',
'X':
datasets.make_circles(n_samples=n_samples, factor=.5, noise=.05)[0],
},
{
'name': 'Noisy Moons',
'X': datasets.make_moons(n_samples=n_samples, noise=.05)[0],
},
{
'name': 'Blobs',
'X': datasets.make_blobs(n_samples=n_samples, random_state=8)[0],
},
{
'name': 'No structure',
'X': np.random.rand(n_samples, 2),
},
{
'name': 'Anisotropicly distributed data',
'X': np.dot(datasets.make_blobs(n_samples=n_samples, random_state=random_state)[0], transformation),
},
{
'name': 'Blobs with varied variances',
'X': datasets.make_blobs(n_samples=n_samples,
cluster_std=[1.0, 2.5, 0.5],
random_state=random_state)[0],
},
{
'name': '2 features, 1 informative, 1 cluster',
'X': datasets.make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=1,
n_clusters_per_class=1)[0],
},
{
'name': '2 features, 2 informative, 1 cluster',
'X': datasets.make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=2,
n_clusters_per_class=1)[0],
},
{
'name': '2 features, 2 informative',
'X': datasets.make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=2)[0],
},
{
'name': '2 features, 2 informative, 2 cluster, 3 classes',
'X': datasets.make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=2,
n_clusters_per_class=1, n_classes=3)[0],
},
{
'name': '2 features, 5 centers',
'X': datasets.make_blobs(n_samples=500, n_features=2, centers=5)[0],
},
{
'name': '2 features, 6 classes',
'X': datasets.make_gaussian_quantiles(n_samples=500, n_features=2, n_classes=6)[0],
},
{
'name': 'Circles',
'X': datasets.make_circles(n_samples=500, factor=0.5)[0],
},
]
# for m in models:
# main(**m)
main(**models[0])