-
Notifications
You must be signed in to change notification settings - Fork 0
/
clustering.py
288 lines (221 loc) · 8.07 KB
/
clustering.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#import plotly_express as px
import plotly.graph_objs as go
#import plotly.plotly as py
from sklearn.decomposition import PCA
import numpy as np
import networkx as nx
from tqdm.notebook import tqdm
import pickle
import time
from numpy import unique
from numpy import where
from matplotlib import pyplot
from sklearn import metrics
from yellowbrick.cluster import SilhouetteVisualizer
#from clusteval import clusteval
#--------------------------------------------------------------------------------------
def make_df(graph):
df = pd.DataFrame(list(graph.items()))
df.rename(columns = {0:'word', 1:'vector'}, inplace = True)
df[[i for i in range(0, 50)]] = pd.DataFrame(df['vector'].tolist(), index=df.index)
df.drop('vector', axis=1, inplace=True)
df = df.drop('word', axis=1)
return df
def apply_pca(df):
pca = PCA(n_components=2).fit_transform(df)
#pcaratio = pca.explained_variance_ratio_
return pca
def clustevalres(X):
ce = clusteval(evaluate='silhouette')
ce.fit(X)
#ce.plot()
#ce.dendrogram()
ce.scatter(X)
ce = clusteval(evaluate='dbindex')
ce.fit(X)
#ce.plot()
ce.scatter(X)
#ce.dendrogram()
ce = clusteval(cluster='dbscan')
try:
ce.fit(X)
ce.plot()
ce.scatter(X)
except ValueError:
pass
#ce.dendrogram()
ce = clusteval(cluster='hdbscan')
ce.fit(X)
#ce.plot()
ce.scatter(X)
#ce.dendrogram()
def vary_damping(graph, algo):
for i in [0.5, 0.6, 0.7, 0.8, 0.9]:
print("damping:", i)
try:
algo(graph, damping=i)
except ValueError:
print("Damping", i, " resulted in just one big cluster")
print("""---""")
def vary_n_of_clusters(graph, algo):
for n in range(2, 15):
print("n:", n)
algo(graph, n)
print("""---""")
def vary_min_samples(graph, algo):
for n in range(4, 15):
print("n:", n)
algo(graph, n)
print("""---""")
def scatter_plot_aff(model, X):
#model.fit(X)
yhat = model.fit_predict(X)
clusters = unique(yhat)
from matplotlib.cm import get_cmap
colors = get_cmap("Set3").colors + get_cmap("Pastel1").colors + get_cmap("Pastel2").colors # type: list
i = 0
from matplotlib.axes._axes import _log as matplotlib_axes_logger
matplotlib_axes_logger.setLevel('ERROR')
for cluster in clusters:
row_ix = where(yhat == cluster)
try: pyplot.scatter(X[row_ix, 0], X[row_ix, 1], c=colors[i])#.reshape(1,-1)) #, linewidth=1, alpha=0.5, c=np.random.rand(len(clusters))/255)
except IndexError: break
i += 1
#pyplot.tick_params(left = False, right = False , labelleft = False, labelbottom = False, bottom = False)
pyplot.grid(False)
pyplot.show()
labels = model.labels_
sil_score = metrics.silhouette_score(X, labels, metric="sqeuclidean")
print("Sillhouette score: ", sil_score)
print("Percentage score: ", (sil_score+1)/2)
print("Number of clusters: ", len(model.cluster_centers_indices_))
def scatter_plot_rest(model, X, n):
model.fit(X)
yhat = model.fit_predict(X)
clusters = unique(yhat)
from matplotlib.cm import get_cmap
colors = get_cmap("Set3").colors + get_cmap("Pastel1").colors + get_cmap("Pastel2").colors # type: list
i = 0
from matplotlib.axes._axes import _log as matplotlib_axes_logger
matplotlib_axes_logger.setLevel('ERROR')
for cluster in clusters:
row_ix = where(yhat == cluster)
try: pyplot.scatter(X[row_ix, 0], X[row_ix, 1], c=colors[i])#.reshape(1,-1)) #, linewidth=1, alpha=0.5, c=np.random.rand(len(clusters))/255)
except IndexError: break
i += 1
#print(colors)
#print(i)
#print(colors[i])
#pyplot.tick_params(left = False, right = False , labelleft = False, labelbottom = False, bottom = False)
pyplot.grid(False)
pyplot.show()
labels = model.labels_
sil_score = metrics.silhouette_score(X, labels, metric="sqeuclidean")
print("Sillhouette score: ", sil_score)
print("Percentage score: ", (sil_score+1)/2)
print("Number of clusters: ", n)
def cluster_with_affinity_propagation(X, damping):
from sklearn.cluster import AffinityPropagation
model = AffinityPropagation(damping=damping)
scatter_plot_aff(model, X)
def agglomerative_clustering(X, n):
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=n)
scatter_plot_rest(model, X, n)
'''def agglomerative_clustering(X, n):
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=n)
yhat = model.fit_predict(X)
clusters = unique(yhat)
for cluster in clusters:
row_ix = where(yhat == cluster)
pyplot.scatter(X[row_ix, 0], X[row_ix, 1])#, s=3)
pyplot.show()
labels = model.labels_
sil_score = metrics.silhouette_score(X, labels, metric="sqeuclidean")
print("Sillhouette score: ", sil_score)
print("Percentage score: ", (sil_score+1)/2)
print("Number of clusters: ", n)'''
def cluster_with_birch(X, n):
from sklearn.cluster import Birch
model = Birch(threshold=0.01, n_clusters=n)
model.fit(X)
scatter_plot_rest(model, X, n)
def cluster_with_kmeans(X, n):
from sklearn.cluster import KMeans
model = KMeans(n_clusters=n)
model.fit(X)
scatter_plot_rest(model, X, n)
def cluster_with_mini_batch_kmeans(X, n):
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=n)
model.fit(X)
yhat = model.predict(X)
scatter_plot_rest(model, X, n)
def spectral_clustering(X, n):
from sklearn.cluster import SpectralClustering
model = SpectralClustering(n_clusters=n)
scatter_plot_rest(model, X, n)
def mean_shift_clustering(X):
from sklearn.cluster import MeanShift
model = MeanShift()
scatter_plot_rest(model, X, n)
def cluster_with_optics(X, n):
from sklearn.cluster import OPTICS
model = OPTICS(eps=0.8, min_samples=n)
scatter_plot_rest(model, X, n)
def cluster_with_dbscan(X, n):
from sklearn.cluster import DBSCAN
model = DBSCAN(eps=0.30, min_samples=n)
scatter_plot_rest(model, X, n)
def plot_with_annotations(graph):
import numpy as np
import matplotlib.pyplot as plt
df = apply_pca(make_df(graph))
df = list(df)
x = [i[0] for i in df]
y = [i[1] for i in df]
graph = sa_la_graph
df = pd.DataFrame(list(graph.items()))
df.rename(columns = {0:'word', 1:'vector'}, inplace = True)
annotations = list(df['word'])
plt.figure(figsize=(30,15))
plt.scatter(x, y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
plt.annotate(label, (x[i], y[i]))
plt.show()
def plot_clusters_old(df):
"""not in use"""
pca = PCA().fit(df)
pcaratio = pca.explained_variance_ratio_
trace = go.Scatter(x=np.arange(len(pcaratio)),y=np.cumsum(pcaratio))
data = [trace]
layout = dict(title="Results")
fig = dict(data=data, layout=layout)
pca = PCA(n_components=5)
sPCA = pca.fit_transform(df)
print("info retained: ", pca.explained_variance_ratio_)
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=6)
sPCA_labels = kmeans.fit_predict(sPCA)
dfPCA = pd.DataFrame(sPCA)
dfPCA['cluster'] = sPCA_labels
from sklearn.manifold import TSNE
X = dfPCA.iloc[:,:-1]
Xtsne = TSNE(n_components=2).fit_transform(X)
dftsne = pd.DataFrame(Xtsne)
dftsne['cluster'] = sPCA_labels
dftsne.columns = ['x1','x2','cluster']
fig = plt.plot(figsize=(10, 6))
sns.scatterplot(data=dftsne,x='x1',y='x2',hue='cluster',legend="full",alpha=0.5)#,ax=ax[0])
#fig.title('Hindi-German')
#sns.scatterplot(data=dfsPCA2,x='x1',y='x2',hue='cluster',legend="full",alpha=0.5,ax=ax[1])
#ax[1].set_title('Visualized on PCA 2D')
#fig.suptitle('Comparing clustering result when visualized using TSNE2D vs. PCA2D')
display(fig)