-
Notifications
You must be signed in to change notification settings - Fork 0
/
clusters_with_selection.py
410 lines (349 loc) · 18.8 KB
/
clusters_with_selection.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from streamlit_plotly_events import plotly_events
from sklearn.cluster import KMeans
import hdbscan
import pickle as pkl
import sys
from plotly.subplots import make_subplots
app = dash.Dash(__name__)
# read in the data files for plotting
plot_df = pd.read_csv(sys.argv[1],index_col=False) # file name containing the cluster characteristics. 'plot_df.csv' from analyze_clusters.ipynb
cluster_label = sys.argv[2]
if len(sys.argv) > 3:
port = sys.argv[3] # the port number used on your browser. Default value can be 8888. If you want to run multiple apps at the same time, \
else:
port = 8888
# list of clustering methods available
available_indicators = [
'ICA (2 comp)',
'ICA (3 comp)',
'TSNE',
'UMAP',
]
# title of the plot based on clustering method - Infoshield, TrafficLight, etc
if 'LSH' in cluster_label:
title = 'Infoshield Clusters'
elif 'label' in cluster_label:
title = 'TrafficLight'
else:
title = cluster_label
# CHANGE DIMENSIONS ACCORDING TO COLUMNS IN YOUR DATASET
dimension_cols = ["Cluster Size", "Phone Count", "Loc Count", "Phone Entropy", "Loc Radius",\
"Person Name Count",\
"Valid URLs", "Invalid URLs", "Ads/week"]
app.layout = html.Div([
html.Div(children=[
html.H1(children='Micro-cluster feature embeddings'),
dcc.Dropdown( # dropdown menu for choosing clustering method/ UMAP/ TSNE
id='analysis-type',
options=[{'label': i, 'value': i} for i in available_indicators],
value='ICA (2 comp)'
),
dcc.Graph( # scatter plot showing the micro-clusters using method chosen above
id='micro-cluster-scatter',
responsive=True)
], style={'width': '49%', 'display': 'inline-block'}),
html.Div(children=[ # pair-wise scatter plot
html.H1(children='Cluster Characterization'),
html.Div(children=title),
dcc.Dropdown( # dropdown menu for choosing clustering method/ UMAP/ TSNE
id='feature-type',
options=[{'label': i, 'value': i} for i in dimension_cols],
value='all',
multi=True
),
dcc.Graph(
id='main-plot',
)
],style={'width': '49%', 'float': 'right', 'display': 'inline-block'})
], style={"height":"100vh"})
# values to be displayed when hovering over a micro-cluster point in a plot
# REPLACE WITH COLUMNS FROM YOUR DATASET
hover_cols = ['Cluster Size Val','Phone Count Val', 'Loc Count Val', 'Loc Radius Val', \
'Loc Radius Val','Person Name Count Val','Valid URLs Val', 'Invalid URLs Val',\
'Ads/week Val', 'Num URLs Val', 'cluster_id']
'''
=========================CLUSTER CHARACTERIZATION PLOT====================================
'''
# function for highlighting in red the chosen cluster over all pair-plots
@app.callback(
Output('main-plot','figure'), # output: 'main-plot' figure. Corresponding to app.layout
Input('main-plot','clickData'), # input: 'main-plot' with clicked data point.
Input('micro-cluster-scatter','selectedData'), # input: 'micro-cluster-scatter' with points selected using lasso-tool
Input('feature-type', 'value'))
def highlight_same_clusters(clickData, selected_clusters, selected_feats):
if selected_feats == 'all':
selected_feats = dimension_cols
if selected_clusters: # if some selection of points has been made
selected_points = [] # the selection info is in JSON format and we need to extract the index of points selected
for item in selected_clusters['points']:
selected_points.append(item['pointIndex'])
to_plot = plot_df.iloc[selected_points] # plotting only the selected points
else: # if no selection has been made
to_plot = plot_df.copy()
# dim_list = []
# for col in dimension_cols:
# dim_list.append(dict(label=col, values=to_plot[col]))
if clickData: # if a certain point has been clicked on (we want to track that point across pair-plots)
cluster_id = clickData['points'][0]['customdata'][-1] # extract info from JSON format
# pair-plots
# fig = go.Figure(data=go.Splom(
# dimensions=dim_list, showlowerhalf=False,
# marker=dict(showscale=False, line_color='white', line_width=0.5)
# ))
fig = px.scatter_matrix(to_plot, dimensions=selected_feats,opacity=0.6,\
hover_data=hover_cols)
fig.update_layout(height=1600, width=1600)
# highlight the current clicked point across all pair-plots in red
# dim_list_update = []
# for col in dimension_cols:
# dim_list_update.append(dict(label=col, values=to_plot[to_plot.cluster_id==cluster_id][col]))
# fig.add_traces(go.Splom(
# dimensions=dim_list_update, showlowerhalf=False,
# marker=dict(showscale=False, line_color='white', line_width=0.5)
# ))
fig.add_traces(
px.scatter_matrix(to_plot[to_plot.cluster_id==cluster_id], \
dimensions=selected_feats).update_traces(marker_color="red").data
)
else: # if no point has been clicked on, show default with all points blue
# fig = go.Figure(data=go.Splom(
# dimensions=dim_list, showlowerhalf=False,
# marker=dict(showscale=False, line_color='white', line_width=0.5)
# ))
print(to_plot[selected_feats])
fig = px.scatter_matrix(to_plot, dimensions=selected_feats,opacity=0.6,\
hover_data=hover_cols)
fig.update_layout(height=1600, width=1600)
return fig
'''
=============================MICRO-CLUSTER FEATURE EMBEDDING======================================
'''
# function for showing the clicked point from pair-plots on the scatter plot
@app.callback(
Output('micro-cluster-scatter', 'figure'),
Input('analysis-type', 'value'),
Input('main-plot','clickData'),
Input('micro-cluster-scatter','clickData'),
Input('main-plot','selectedData'))
def update_graph(selected_clustering, clickData, clickData_from_mcs, selectedData):
data_cols = ['x','y']
# the ICA (2&3), TSNE and UMAP are precomputed and saved to disk for plotting
if selected_clustering == available_indicators[0]: # ICA 2 comp
df = pd.read_csv("data/is_ica.zip",index_col=False) #CHANGE THE DATA FILES ACCORDINGLY
color_labels = None
elif selected_clustering == available_indicators[1]: # ICA 3 comp
df = pd.read_csv("data/is_ica_3.zip",index_col=False)
color_labels = None
elif selected_clustering == available_indicators[2]: # TSNE
tsne_res = pkl.load(open("data/all_tsne_res.pkl",'rb'))
# df = pd.read_csv("data/is_tsne.zip",index_col=False)
color_labels = None
elif selected_clustering == available_indicators[3]: # UMAP
umap_res = pkl.load(open("data/umap_res.pkl",'rb'))
# df = pd.read_csv("data/is_umap.zip",index_col=False)
color_labels = None
if selected_clustering == available_indicators[1]:
fig = px.scatter_matrix(df, dimensions=['x','y','z'], hover_data=hover_cols, height=1000)
elif selected_clustering == available_indicators[2]: #TSNE with diff perplexity values. Displays a grid of plots
perp_vals = list(tsne_res.keys())
titles = []
for p in perp_vals:
titles.append(str(p))
fig = make_subplots(
rows=1, cols=len(perp_vals),\
subplot_titles=tuple(titles), \
horizontal_spacing=0.01, vertical_spacing=0.01, \
shared_xaxes=True, shared_yaxes=True, \
x_title='Perplexity Values'
)
template_str = ""
for i, col in enumerate(hover_cols):
if i != len(hover_cols)-1:
template_str += (col+":%{customdata["+str(i)+"]}<br>")
else:
template_str += (col+":%{customdata["+str(i)+"]}")
for i, p in enumerate(perp_vals):
fig.add_scatter(x=list(tsne_res[p].x), y=list(tsne_res[p].y), \
customdata=tsne_res[p][hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'opacity':0.3, 'color': 'blue'}, \
row=1, col=i+1)
if i == 0:
fig.layout.annotations[i].update(text=str(p))
fig.update_layout(height=1600, width=1000, showlegend=False)
elif selected_clustering == available_indicators[3]: # UMAP
nbr_sizes = [10, 50, 100, 200, 500, 1000]
mini_dists = [0, 0.01, 0.05, 0.1, 0.5, 1]
titles = []
for d in mini_dists:
titles.append(str(d))
template_str = ""
for i, col in enumerate(hover_cols):
if i != len(hover_cols)-1:
template_str += (col+":%{customdata["+str(i)+"]}<br>")
else:
template_str += (col+":%{customdata["+str(i)+"]}")
fig = make_subplots(rows=len(nbr_sizes), cols=len(mini_dists), \
subplot_titles=tuple(titles[:6]), \
horizontal_spacing=0.2, vertical_spacing=0.2, \
shared_xaxes=True, shared_yaxes=True, \
x_title='Min. distance', y_title='Nbrhood Size')
for i in range(len(nbr_sizes)):
for j in range(len(mini_dists)):
fig.add_scatter(x=list(umap_res[i][j].x), y=list(umap_res[i][j].y), \
customdata=umap_res[i][j][hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'opacity':0.3, 'color': '#17becf'}, \
row=i+1, col=j+1)
if j == len(mini_dists)-1:
fig.update_yaxes(side='right', title_text=str(nbr_sizes[i]), row=i+1, col=j+1)
if i == 0:
fig.layout.annotations[j].update(text=str(mini_dists[j]))
fig.update_layout(height=1500, width=1000, showlegend=False, title_text='Min. Distance')
else:
fig = px.scatter(df, x='x',y='y', hover_data=hover_cols, height=1600)
if clickData:
if (not selected_clustering in [available_indicators[2], available_indicators[3]]): # if a certain point has been clicked on (only if not TSNE and UMAP)
cluster_id = clickData['points'][0]['customdata'][-1] # retrieve info of clicked point
# if it's ICA with 3 comp, then pair-plot instead of regular scatter plot
if selected_clustering == available_indicators[1]:
fig.add_traces(
px.scatter_matrix(df[df.cluster_id==cluster_id], dimensions=['x','y','z'],
hover_data=hover_cols).update_traces(marker_color="red",marker_size=20,marker_symbol='star').data
)
else: # regular scatter plot
fig.add_traces(
px.scatter(df[df.cluster_id==cluster_id], \
x='x',y='y', hover_data=hover_cols).update_traces(marker_color="red",marker_size=20,marker_symbol='star').data
)
else:
cluster_id = clickData['points'][0]['customdata'][-1]
if selected_clustering == available_indicators[2]: # TSNE
for i, p in enumerate(perp_vals):
dd = tsne_res[p]
hover_trace = dict(type='scatter', \
x=list(dd[dd.cluster_id==cluster_id].x), y=list(dd[dd.cluster_id==cluster_id].y), \
customdata=dd[hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'symbol':'star', 'color': 'red','size':10})
fig.append_trace(hover_trace, 1, i+1)
if selected_clustering == available_indicators[3]:
nbr_sizes = [10, 50, 100, 200, 500, 1000]
mini_dists = [0, 0.01, 0.05, 0.1, 0.5, 1]
template_str = ""
for i, col in enumerate(hover_cols):
if i != len(hover_cols)-1:
template_str += (col+":%{customdata["+str(i)+"]}<br>")
else:
template_str += (col+":%{customdata["+str(i)+"]}")
for i in range(len(nbr_sizes)):
for j in range(len(mini_dists)):
dd = umap_res[i][j]
hover_trace = dict(type='scatter',\
x=list(dd[dd.cluster_id==cluster_id].x), y=list(dd[dd.cluster_id==cluster_id].y), \
customdata=dd[hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'symbol':'star', 'color': 'red','size':10}, \
)
fig.append_trace(hover_trace, i+1, j+1)
if j == len(mini_dists)-1:
fig.update_yaxes(side='right', title_text=str(nbr_sizes[i]), row=i+1, col=j+1)
if i == 0:
fig.layout.annotations[j].update(text=str(mini_dists[j]))
fig.update_layout(height=1500, width=1000, showlegend=False, title_text='Min. Distance')
if clickData_from_mcs: # only for UMAP and TSNE
cluster_id = clickData_from_mcs['points'][0]['customdata'][-1] # retrieve info of hovered point
if selected_clustering == available_indicators[2]: # TSNE
for i, p in enumerate(perp_vals):
dd = tsne_res[p]
hover_trace = dict(type='scatter', \
x=list(dd[dd.cluster_id==cluster_id].x), y=list(dd[dd.cluster_id==cluster_id].y), \
customdata=dd[hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'opacity':1, 'color': 'black','size':10})
fig.append_trace(hover_trace, 1, i+1)
if selected_clustering == available_indicators[3]:
nbr_sizes = [10, 50, 100, 200, 500, 1000]
mini_dists = [0, 0.01, 0.05, 0.1, 0.5, 1]
template_str = ""
for i, col in enumerate(hover_cols):
if i != len(hover_cols)-1:
template_str += (col+":%{customdata["+str(i)+"]}<br>")
else:
template_str += (col+":%{customdata["+str(i)+"]}")
for i in range(len(nbr_sizes)):
for j in range(len(mini_dists)):
dd = umap_res[i][j]
hover_trace = dict(type='scatter',\
x=list(dd[dd.cluster_id==cluster_id].x), y=list(dd[dd.cluster_id==cluster_id].y), \
customdata=dd[hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'opacity':1, 'color': 'black','size':10}, \
)
fig.append_trace(hover_trace, i+1, j+1)
if j == len(mini_dists)-1:
fig.update_yaxes(side='right', title_text=str(nbr_sizes[i]), row=i+1, col=j+1)
if i == 0:
fig.layout.annotations[j].update(text=str(mini_dists[j]))
fig.update_layout(height=1500, width=1000, showlegend=False, title_text='Min. Distance')
if selectedData:
selected_points = [] # the selection info is in JSON format and we need to extract the index of points selected
for item in selectedData['points']:
selected_points.append(item['pointIndex'])
if (not selected_clustering in [available_indicators[2], available_indicators[3]]): # if a certain point has been clicked on (only if not TSNE and UMAP)
# if it's ICA with 3 comp, then pair-plot instead of regular scatter plot
if selected_clustering == available_indicators[1]:
fig.add_traces(
px.scatter_matrix(df.iloc[selected_points], dimensions=['x','y','z'],
hover_data=hover_cols).update_traces(marker_color="red",marker_size=20,marker_symbol='star').data
)
else: # regular scatter plot
fig.add_traces(
px.scatter(df.iloc[selected_points], \
x='x',y='y', hover_data=hover_cols).update_traces(marker_color="red",marker_size=20,marker_symbol='star').data
)
else:
if selected_clustering == available_indicators[2]: # TSNE
for i, p in enumerate(perp_vals):
dd = tsne_res[p]
hover_trace = dict(type='scatter', \
x=list(dd.iloc[selected_points].x), y=list(dd.iloc[selected_points].y), \
customdata=dd.iloc[selected_points][hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'color': 'red','size':10})
fig.append_trace(hover_trace, 1, i+1)
if selected_clustering == available_indicators[3]:
nbr_sizes = [10, 50, 100, 200, 500, 1000]
mini_dists = [0, 0.01, 0.05, 0.1, 0.5, 1]
template_str = ""
for i, col in enumerate(hover_cols):
if i != len(hover_cols)-1:
template_str += (col+":%{customdata["+str(i)+"]}<br>")
else:
template_str += (col+":%{customdata["+str(i)+"]}")
for i in range(len(nbr_sizes)):
for j in range(len(mini_dists)):
dd = umap_res[i][j]
hover_trace = dict(type='scatter',\
x=list(dd.iloc[selected_points].x), y=list(dd.iloc[selected_points].y), \
customdata=dd.iloc[selected_points][hover_cols], \
hovertemplate=template_str,\
mode='markers', marker={'symbol':'star', 'color': 'red','size':10}, \
)
fig.append_trace(hover_trace, i+1, j+1)
if j == len(mini_dists)-1:
fig.update_yaxes(side='right', title_text=str(nbr_sizes[i]), row=i+1, col=j+1)
if i == 0:
fig.layout.annotations[j].update(text=str(mini_dists[j]))
fig.update_layout(height=1500, width=1000, showlegend=False, title_text='Min. Distance')
return fig
if __name__ == '__main__':
app.run_server(debug=True, port=port)