-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_pipelines.py
1942 lines (1672 loc) · 81.2 KB
/
main_pipelines.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main experimental pipelines.
"""
import matplotlib
import report_file_object_class as rfo
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import sys
import math
import os
import csv
import copy
import build_cosponsorship as cosponsorship
import build_dblp as dblp
import build_twitch_network as twitch
from sklearn.cluster import KMeans, SpectralClustering
from scipy import stats
from helper_pipelines import read_coauthorship as read
from helper_pipelines import clustering_pipeline as cp
from helper_pipelines import eigengap_calculator as eigen
import pyreadr
import pandas as pd
import build_generic_network as bgn
import statistics
from sklearn.metrics import pairwise_distances
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
from cluster_consistency import cluster_labeling
from karateclub import Role2Vec
from collections import OrderedDict
import cpnet
import numpy as np
# ==== IDENTIFIER: ==== #
# Unique identifier string for each data set.
# Must be either one word (eg. "twitch") or several words using a hyphen
# (eg. "strong-house"). Do NOT use "_" (underscore).
IDENTIFIER_STRING = "twitch"
# ==== PARAMETERS FOR TUNING K = NUMBER OF CLUSTERS: ==== #
MIN_CLUSTERS = 1
MAX_CLUSTERS = 16
N_REFS = 4
# ==== PIPELINE AFTER_VECTORS PARAMETERS: ==== #
K = -1 # Hyperparameter k.
ATTRIBUTE = "" # Node attribute, about which to create distribution or bar graphs.
INPUT_PICKLED_GRAPH = "" # Path to a pickled graph with nodes and relevant attributes.
VECTOR_FILE_INVARIANT = "" # Invariant for the vector txt files for different alpha values.
REPORT_FILE_PATH = "" # File to which write the results of the clustering experiment.
REPORT_FILE = rfo.ReportFileObject(REPORT_FILE_PATH) # Instance of the report file (for convenience in writing to it).
# Alpha values for other data sets:
ALPHA_VALUES = [] # Must match the alpha values used for creating the vector files.
PLOT_PDF = 1 # Whether the attribute is for plotting a PDF or not; if 1, plot_attribute_distributions() will be run;
# if 0, plot_attribute_bar().
PDF_LOG = 0 # If PLOT_PDF = 1, when drawing a PDF, should we take log(attribute)?
LOG_BASE = 10 # If PDF_LOG = 1, what is the base for log used in creating a PDF.
# (Optional) parameter for dataset_pdf(), which plots the PDF of the entire dataset.
DATASET_LOG = 1 # If 0, input numbers for PDF are raw; if 1, log of LOG_BASE is taken of them.
# (Optional) Colors used for the graphs.
COLOR_PALETTE = ["#FFC107", "#1E88E5", "#2ECE54", "#EC09D7", "#DDEC4E", "#D81B50", "#CCD85D", "#3701FA", "#D39CA7", "#27EA9F", "#5D5613", "#DC6464"]
BAR_GRAPH_COLOR_PALETTE = ["#BA65A4", "#1A4D68"]
# ==== PARAMETERS FOR CLUSTERING METHODS BEYOND INFORMATION ACCESS AND SPECTRAL: ==== #
IAC_LABELING_FILE = ""
LABELING_FILE = ""
EXPERIMENT = ""
# Repeated fluid communities clustering pipeline hyperparameters:
SEEDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Seeds used for random number generation states.
# For core-periphery:
CP_THRESHOLD = 0.5 # Threshold for turning continuous "coreness" measure for each node into binary core/periphery data.
def main():
# General experimentation pipeline:
# 1. Pipelines "build_*" to build a relevant graph pickle and edgelist for simulations: in main_pipelines.
# 2. Simulations to generate vector files for each of the alpha values: with run.sh.
# 3. Gap, Silhouette, and/or Elbow methods to find K: in main_pipelines.
# 4. Pipeline "after_vectors" to run clustering Information Access and Spectral Clustering methods
# and generate plots: in main_pipelines.
# 5. Run "repeated_fluidc", "role2vec_pipeline", or "core_periphery" clustering methods and
# use additional methods for deeper analysis.
# ========== #
# 1. Pipelines "build_*":
if sys.argv[1] == "build_twitch":
twitch.main()
elif sys.argv[1] == "build_cosponsorship":
cosponsorship.main()
elif sys.argv[1] == "build_dblp":
dblp.main()
# 2. Files for simulations can be found in output_files directory.
# 3. Methods for finding K.
elif sys.argv[1] == "granger_gap_statistic":
granger_gap_statistic_wrapper()
elif sys.argv[1] == "silhouette_analysis":
silhouette_analysis_wrapper()
elif sys.argv[1] == "elbow_method":
elbow_method_wrapper()
# 4. Pipeline after_vectors for information access and spectral clustering and plotting the relevant graphs.
elif sys.argv[1] == "after_vectors":
pipeline_after_vectors()
# 5. Other clustering methods:
elif sys.argv[1] == "repeated_fluidc":
repeated_fluidc()
elif sys.argv[1] == "fluid_communities":
fluid_communities()
elif sys.argv[1] == "role2vec_pipeline":
role2vec_pipeline()
elif sys.argv[1] == "core_periphery":
core_periphery()
# Additional methods for analysis:
# Outputs the adjusted rand index scores between clusterings of information access and some other method.
elif sys.argv[1] == "iac_vs_x_ari":
iac_vs_x_ari()
# Computes the mean of adjusted rand index scores across repeated fluid communities clusterings for each alpha value.
elif sys.argv[1] == "mean_ari":
mean_ari()
# Runs the Fisher Exact test on the clusters; hardcoded with K=2.
elif sys.argv[1] == "fisher_exact":
fisher_exact()
# Counts the number of connected components in each cluster, given a clustering in a labeling file.
elif sys.argv[1] == "count_cc":
count_cc_wrapper()
# Given some clustering in the LABELING_FILE, runs statistical analyses for one of DBLP, Co-sponsorship, and Twitch
# based on its default attributes and settings.
elif sys.argv[1] == "statistical_analyses":
statistical_analyses()
# Plot the PDF of the entire dataset.
elif sys.argv[1] == "dataset_pdf":
dataset_pdf()
# Calculate the adjusted rand index between two clusterings
elif sys.argv[1] == "calc_ari":
calculate_ari()
# Creates a .csv file that maps each node to its KMeans cluster (reproducible with random_state=1).
elif sys.argv[1] == "clustering_map":
clustering_map()
# Creates a .csv file that maps cluster compositions to clusters.
elif sys.argv[1] == "composition_map":
composition_map()
# Computes the composition of probabilities in the information access vector files.
elif sys.argv[1] == "probability_composition":
probability_composition()
# Generates profiles of nodes in .csv (to be used along with edgelist to reconstruct graphs).
elif sys.argv[1] == "generate_profiles":
generate_profiles()
return
# "granger_gap_statistic"
def granger_gap_statistic_wrapper():
"""Wrapper for granger_gap_statistic. Output will be displayed in terminal."""
for alpha_value in ALPHA_VALUES:
print("\n{}: Gap Statistic for {}".format(IDENTIFIER_STRING, alpha_value))
X = read.read_in_vectors(VECTOR_FILE_INVARIANT.format(str(alpha_value)[2:]))
X = [X[i] for i in X]
X = np.array(X)
gap_statistic_output = granger_gap_statistic(X, alpha_value)
print("Optimal number of clusters is {} among {}".format(gap_statistic_output[0], gap_statistic_output[1]))
return
# Granger Gap Statistic code adapted from https://anaconda.org/milesgranger/gap-statistic/notebook
def granger_gap_statistic(data, alpha_value):
"""
Notes from the source:
Calculates KMeans optimal K using Gap Statistic from Tibshirani, Walther, Hastie
Params:
data: ndarry of shape (n_samples, n_features)
nrefs: number of sample reference datasets to create
maxClusters: Maximum number of clusters to test for
Returns: (gaps, optimalK)
"""
gaps = np.zeros((len(range(1, MAX_CLUSTERS)),))
resultsdf = pd.DataFrame({'clusterCount': [], 'gap': []})
for gap_index, k in enumerate(range(1, MAX_CLUSTERS)):
# Holder for reference dispersion results
refDisps = np.zeros(N_REFS)
# For n references, generate random sample and perform kmeans getting resulting dispersion of each loop
for i in range(N_REFS):
# Create new random reference set
randomReference = np.random.random_sample(size=data.shape)
# Fit to it
km = KMeans(k)
km.fit(randomReference)
refDisp = km.inertia_
refDisps[i] = refDisp
# Fit cluster to original data and create dispersion
km = KMeans(k)
km.fit(data)
origDisp = km.inertia_
# Calculate gap statistic
gap = np.log(np.mean(refDisps)) - np.log(origDisp)
# Assign this loop's gap statistic to gaps
gaps[gap_index] = gap
resultsdf = resultsdf.append({'clusterCount': k, 'gap': gap}, ignore_index=True)
x_data = [i for i in range(1, MAX_CLUSTERS)]
y_data = [gaps[i - 1] for i in x_data]
plt.scatter(x_data, y_data)
plt.plot(x_data, y_data)
plt.xticks(x_data)
plt.title("Value of K vs. Gap Statistic\nNumber of references used: {}".format(N_REFS))
plt.xlabel("Value of K")
plt.ylabel("Gap Statistic")
plt.savefig("output_files/{}_gap_alpha_{}.png".format(IDENTIFIER_STRING, alpha_value), bbox_inches='tight')
plt.close()
return (gaps.argmax() + 1,
resultsdf) # Plus 1 because index of 0 means 1 cluster is optimal, index 2 = 3 clusters are optimal
# "silhouette_analysis"
def silhouette_analysis_wrapper():
"""Wrapper for silhouette_analysis. Output will be displayed in terminal."""
for alpha_value in ALPHA_VALUES:
print("\n{}: Silhouette Analysis for {}".format(IDENTIFIER_STRING, alpha_value))
X = read.read_in_vectors(VECTOR_FILE_INVARIANT.format(str(alpha_value)[2:]))
X = [X[i] for i in X]
X = np.array(X)
silhouette_analysis(X, alpha_value)
return
# Silhouette Analysis code adapted from https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html
def silhouette_analysis(X, alpha_value):
"""
Main function for silhouette_analysis.
:param X: array of information access vectors.
:param alpha_value: alpha value.
:return: None.
"""
for n_clusters in range(2, MAX_CLUSTERS):
# Create a subplot with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1 but in this example all
# lie within [-0.1, 1]
ax1.set_xlim([-0.1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
# seed of 10 for reproducibility.
clusterer = KMeans(n_clusters=n_clusters, random_state=10)
cluster_labels = clusterer.fit_predict(X)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
# Label the silhouette plots with their cluster numbers at the middle
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
# Compute the new y_lower for next plot
y_lower = y_upper + 10 # 10 for the 0 samples
ax1.set_title("The silhouette plot for the various clusters.")
ax1.set_xlabel("The silhouette coefficient values")
ax1.set_ylabel("Cluster label")
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) # Clear the yaxis labels / ticks
ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
# 2nd Plot showing the actual clusters formed
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7,
c=colors, edgecolor='k')
# Labeling the clusters
centers = clusterer.cluster_centers_
# Draw white circles at cluster centers
ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
c="white", alpha=1, s=200, edgecolor='k')
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
s=50, edgecolor='k')
ax2.set_title("The visualization of the clustered data.")
ax2.set_xlabel("Feature space for the 1st feature")
ax2.set_ylabel("Feature space for the 2nd feature")
plt.suptitle(("Silhouette analysis for KMeans clustering on sample data "
"with n_clusters = %d" % n_clusters),
fontsize=14, fontweight='bold')
plt.savefig(
"output_files/{}_sil_alpha_{}_cluster_{}.png".format(IDENTIFIER_STRING, str(alpha_value)[2:], n_clusters))
plt.close(fig)
return
# "elbow_method"
def elbow_method_wrapper():
"""Wrapper for elbow_method. Output will be displayed in terminal."""
print("running!")
for alpha_value in ALPHA_VALUES:
print("\n{}: Elbow Method for {}".format(IDENTIFIER_STRING, alpha_value))
vector_file_path = VECTOR_FILE_INVARIANT.format(str(alpha_value)[2:])
vectors = read.read_in_vectors(vector_file_path)
elbow_method(vector_file_path, vectors, MIN_CLUSTERS, MAX_CLUSTERS)
return
# Elbow_method code adapted from https://towardsdatascience.com/k-means-clustering-with-scikit-learn-6b47a369a83c
def elbow_method(vector_file, vectors, min_k, max_k):
"""
Creates elbow graphs for choosing k (number of clusters) for the clustering methods.
:param vector_file: vector file path.
:param vectors: dict of information access vectors by nodes.
:param min_k: minimum number of clusters to calculate distortion for.
:param max_k: maximum number of clusters to calculate distortion for.
:return: None.
"""
X = np.array(list(vectors.values()))
distortions = []
for i in range(min_k, max_k):
print("On k value " + str(i))
kmeans = KMeans(n_clusters=i, random_state=1).fit(X)
distortions.append(kmeans.inertia_)
print(kmeans.inertia_)
# plot
print(distortions)
plt.plot(range(min_k, max_k), distortions, marker='o')
plt.xticks(range(min_k, max_k))
plt.xlabel('Number of clusters')
plt.ylabel('Distortion')
vector_file_name = vector_file[:-4].split("_")
plt.title("Information Access Clustering Elbow Plot (alpha = 0.{})".format(vector_file_name[-2][1:]))
plt.savefig("output_files/{}_elbow_{}_{}.png".format(IDENTIFIER_STRING, vector_file_name[-2], vector_file_name[-1]),
bbox_inches='tight')
plt.close()
return
# "after_vectors"
def pipeline_after_vectors():
"""Driver function for the after_vectors pipeline.
Runs information access and spectral clustering methods
and the relevant statistical analysis for the given ATTRIBUTE."""
# Loads the input pickled graph into a local variable graph.
with open(INPUT_PICKLED_GRAPH, "rb") as file:
graph = pickle.load(file)
# Begins Information Access Clustering.
# Prints the passed string in the terminal and writes it to the report file.
REPORT_FILE.print("\n================INFORMATION ACCESS==================")
labeling_file = "output_files/{}_K{}_labeling_file_iac.csv".format(IDENTIFIER_STRING, K)
if not os.path.isfile(labeling_file):
# composition_map executes information access clustering and saves a composition_map file.
clustering_file = composition_map()
# cluster_labeling uses that file to create a matrix of relabeled clusters.
cluster_labeling.main(clustering_file, labeling_file)
cluster_dict = read_in_clusters(labeling_file)
# For each alpha value, performs the information access clustering and plots the results.
for alpha_value in ALPHA_VALUES:
graph = assign_clusters(graph, cluster_dict, alpha_value)
vector_file_path = VECTOR_FILE_INVARIANT.format(str(alpha_value)[2:])
REPORT_FILE.print("\n+++++{}+++++\n".format(vector_file_path))
plot_all_attributes(graph, "information_access", vector_file_path=vector_file_path, alpha_value=alpha_value)
# Begins Spectral Clustering.
REPORT_FILE.print("\n================SPECTRAL==================")
spectral_labeling_file = "output_files/{}_K{}_labeling_file_spectral.csv".format(IDENTIFIER_STRING, K)
if not os.path.isfile(spectral_labeling_file):
spectral_clustering_file = spectral_composition()
cluster_labeling_spectral(spectral_clustering_file, spectral_labeling_file)
spectral_cluster_dict = read_in_generic(spectral_labeling_file)
graph = assign_generic_clusters(graph, spectral_cluster_dict)
plot_all_attributes(graph, "spectral")
return
# "composition_map" (placed here for Top-Down Design)
def composition_map():
"""
Creates a file that shows the composition (by nodes) of the information access clusters.
:return: a str path to the output file.
"""
with open(INPUT_PICKLED_GRAPH, "rb") as file:
graph = pickle.load(file)
output_filename = "output_files/{}_K{}_composition_map.csv".format(IDENTIFIER_STRING, K)
with open(output_filename, 'a') as file:
fieldnames = ["Alpha_Values"]
fieldnames.extend(["Cluster {}".format(k) for k in range(K)])
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
user_obj_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
for alpha_value in ALPHA_VALUES:
print("Composition map for alpha = {}".format(alpha_value))
vector_file_path = VECTOR_FILE_INVARIANT.format(str(alpha_value)[2:])
vectors = read.read_in_vectors(vector_file_path)
# Clusters the nodes: the vertices have a "cluster" attribute with a number of the cluster to which they were
# assigned. If the loop has performed the loop one, updates the "cluster" values for the same graph based
# on the clustering from the new vector file corresponding to the current alpha value.
graph = information_access_clustering(vectors, K, graph)
clusters_total = {i: [] for i in range(K)}
for node_int in range(len(graph.nodes)):
j = graph.nodes[node_int]["cluster"]
clusters_total[j].append(node_int)
row = [alpha_value]
row.extend(clusters_total[k] for k in range(K))
user_obj_writer.writerow(row)
return output_filename
def information_access_clustering(vectors, k, graph):
"""
Runs Information Access Clustering on the graph.
:param vectors: dict of information access vectors by nodes.
:param k: number of clusters to enforce.
:param graph: networkx graph.
:return: networkx graph, having nodes with a populated "cluster" attribute.
"""
X = np.array(list(vectors.values()))
labels = KMeans(n_clusters=k, random_state=1).fit_predict(X)
for node in graph.nodes:
graph.nodes[node]["cluster"] = labels[node]
# Although the graph itself is mutated by the function above,
# returns a graph pointer for consistency.
return graph
def read_in_clusters(cluster_label_file):
"""
Reads a labeling file into format: {node: {alpha: cluster, alpha: cluster…}…}}
:param cluster_label_file: path to the lableing file.
:return: clustering dict.
"""
cluster_dict = {}
with open(cluster_label_file, "r") as f:
lines = csv.reader(f)
first = True
for row in lines:
if first:
alpha_values = [float(alpha_value) for alpha_value in row[1:]]
first = False
else:
node = int(row[0])
cluster_dict[node] = {}
for index in range(1, len(row)):
alpha = alpha_values[index - 1]
cluster_dict[node][alpha] = int(row[index])
return cluster_dict
def assign_clusters(graph, cluster_dict, alpha):
"""
From the clustering dict, assigns the cluster label to each node in graph.
:param graph: networkx graph.
:param cluster_dict: clustering dict created by read_in_clusters.
:param alpha: alpha value.
:return: networkx graph, having nodes with a populated "cluster" attribute.
"""
for node in graph.nodes:
cluster = int(cluster_dict[node][alpha])
graph.nodes[node]["cluster"] = cluster
return graph
def plot_all_attributes(graph, cluster_method, vector_file_path=None, alpha_value=None):
"""
Decides which graphs to plot based on whether the ATTRIBUTE is continuous or discrete.
If continuous, Kolmogorov-Smirnov and Kruskal–Wallis tests are also performed.
:param graph: networkx graph.
:param cluster_method: cluster method label (e.g. "iac", "spectral", "role2vec", etc.).
:param vector_file_path: path to vector files (vector file invariant) if "iac".
:param alpha_value: alpha value if "iac".
:return: None.
"""
if PLOT_PDF:
plot_attribute_distributions(graph, cluster_method, vector_file_path=vector_file_path, alpha_value=alpha_value, k_clusters=K)
else:
plot_attribute_bar(graph, cluster_method, vector_file_path=vector_file_path, alpha_value=alpha_value, k_clusters=K)
return
def plot_attribute_distributions(graph, cluster_method, vector_file_path=None, alpha_value=None,
identifier_string=IDENTIFIER_STRING, k_clusters=K, attribute=ATTRIBUTE,
pdf_log=PDF_LOG, log_base=LOG_BASE, color_palette=COLOR_PALETTE,
report_file=REPORT_FILE):
"""
Plots the distribution of the continuous ATTRIBUTE for nodes in each cluster.
:param graph: networkx graph.
:param cluster_method: cluster method label (e.g. "iac", "spectral", "role2vec", etc.).
:param vector_file_path: path to vector files (vector file invariant) if "iac".
:param alpha_value: alpha value if "iac".
:param identifier_string: dataset identifier string (e.g. "dblp", "twitch", etc.)
:param k_clusters: number of clusters to enforce.
:param attribute: attribute to use for plotting the distribution.
:param pdf_log: whether to take the log of the attribute value (boolean: True or False).
:param log_base: if True, the log base.
:param color_palette: color palette to be used for plotting the graphs.
:param report_file: report file object to document the statistical test results (Kolmogorov-Smirnov and Kruskal–Wallis).
:return: None.
"""
if k_clusters < 2:
raise ValueError("k_clusters must be more than 1")
clusters_total = {cluster: [] for cluster in range(k_clusters)}
no_attribute_dict = {cluster: 0.0 for cluster in range(k_clusters)}
# Processes the data -- nodes' available attribute values -- to be used for the analyses.
for node in graph.nodes:
cluster = graph.nodes[node]["cluster"]
# A node can either have the ATTRIBUTE or not: node["attribute"] or node.
# If has ATTRIBUTE, it either has a value for ATTRIBUTE or not: node["attribute"] = value or node["attribute"].
# If it has a value, the value can be either a str type or an int/float type.
# If it's str type, the string can be a word or a str of a number.
# All of these are handled by the "try" section,
# assuming that the attribute value that is unavailable is represented by None.
try:
value = float(graph.nodes[node][attribute])
if pdf_log:
clusters_total[cluster].append(math.log(value, log_base))
else:
clusters_total[cluster].append(value)
except:
no_attribute_dict[cluster] += 1
# Computes and writes cluster sizes, clusters' portions from the total,
# and the percentages of available nodes in them.
summarize_clusters(clusters_total, no_attribute_dict, k_clusters, attribute, report_file)
plt.figure(figsize=(12, 10))
color_counter = 0
for cluster in clusters_total:
input = [i for i in clusters_total[cluster]]
for i in input:
if i < 0:
print(i)
# print(input)
try:
sns.distplot(input, hist=False, kde=True,
kde_kws = {'linewidth': 3},
label=str(cluster), norm_hist=True, color=color_palette[color_counter])
except:
pass
color_counter += 1
# Runs and writes the results of Pairwise Kolmogorov-Smirnov and Kruskal-Wallis tests."""
kolmogorov_smirnov_test(clusters_total, k_clusters, report_file)
kruskal_wallis_test(clusters_total, k_clusters, report_file)
# Settings for x and y ranges for different experiments
# if attribute == "views":
# plt.xlim(-100000, 200000)
# plt.xlim(-100000, 500000)
# plt.xlim(-1000000, 2000000)
# if attribute == "followers_count":
# plt.xlim(-100000, 200000)
# plt.xlim(-50000, 100000)
# if attribute == "average_favorite_count":
# plt.xlim(-1000, 2000)
# plt.xlim(-550, 1000)
# if attribute == "average_retweet_count":
# plt.xlim(-500, 2000)
# plt.xlim(-400, 1000)
# if attribute == "world_system":
# plt.ylim(0, 1.5)
plt.legend()
# Depending on whether we're taking log of the values, writes the corresponding x-axis label.
if pdf_log:
plt.xlabel("log({}) with base {}".format(attribute, log_base))
else:
plt.xlabel(attribute)
# Writes the y-axis label.
plt.ylabel("PDF")
# Depending on the clustering method, writes the corresponding title and saves the plot with a unique name.
if cluster_method == "information_access":
vector_file_name_tokens = vector_file_path[:-4].split("_")
print(vector_file_name_tokens)
if pdf_log:
plt.title("Density at log({}) for different clusters (alpha = {})".format(attribute, alpha_value))
else:
plt.title("Density at {} for different clusters (alpha = {})".format(attribute, alpha_value))
plt.savefig("output_files/{}_PDF_K{}_{}_{}_{}_vs_{}.png".format(identifier_string, k_clusters,
vector_file_name_tokens[-2],
vector_file_name_tokens[-1], attribute,
cluster_method), bbox_inches='tight')
else:
if pdf_log:
plt.title("Density at log({}) for different clusters".format(attribute))
else:
plt.title("Density at {} for different clusters".format(attribute))
plt.savefig(
"output_files/{}_PDF_K{}_{}_vs_{}.png".format(identifier_string, k_clusters, attribute, cluster_method),
bbox_inches='tight')
plt.close()
return
def summarize_clusters(clusters_total, no_attribute_dict, k_clusters, attribute, report_file):
"""
Computes and writes cluster sizes, clusters' portions from the total,
and the percentages of available nodes in them.
:param clusters_total: dict {cluster: [attr_value1, attr_value2, ...]}.
:param no_attribute_dict: dict {cluster: num of nodes with no attribute value}.
:param k_clusters: number of clusters to enforce.
:param attribute: node attribute at hand.
:param report_file: report file object to document the summary.
:return: None.
"""
# Computes and writes the cluster sizes.
cluster_sizes = {cluster: len(clusters_total[cluster]) for cluster in range(k_clusters)}
report_file.print("\nCluster sizes:" + str(cluster_sizes))
# Finds the total number of nodes that have available attribute values.
total_num_of_nodes = 0
for cluster in cluster_sizes:
total_num_of_nodes += cluster_sizes[cluster]
portions = {}
# For each cluster, writes its portion from the total and the percent of available nodes in it.
for cluster in cluster_sizes:
# Finds and writes the portion of the cluster from the total.
portion = cluster_sizes[cluster] / total_num_of_nodes
portions[cluster] = portion
report_file.print("\n" + "Portion of {} from the total: {}".format(cluster, portion))
# Finds and writes the percent available nodes in the cluster.
available_percent = cluster_sizes[cluster] / (cluster_sizes[cluster] + no_attribute_dict[cluster])
report_file.print("\n" + f"Percent with {attribute} available in cluster {cluster}: {available_percent}")
# Run chi2 test to see whether there is a relationship between cluster and having ATTRIBUTE data:
num_with_data = np.array(list(cluster_sizes.values()))
num_without_data = np.array(list(no_attribute_dict.values()))
r_c_table = np.array((num_with_data, num_without_data))
try:
g, p, dof, expctd = stats.chi2_contingency(r_c_table)
report_file.print(
"\n" + f"pvalue from chi2 two-way test of significant relationship between cluster and having {attribute} data: {p}")
except ValueError as e:
report_file.print(str(e))
return
def kolmogorov_smirnov_test(clusters_total, k_clusters, report_file):
"""
Runs and writes the results of Pairwise Kolmogorov-Smirnov test.
:param clusters_total: dict {cluster: [attr_value1, attr_value2, ...]}.
:param k_clusters: number of clusters to enforce.
:param report_file: report file object to document the result.
:return: None.
"""
for i in range(k_clusters):
current_num = k_clusters - 1 - i
for j in range(current_num):
report_file.print("\n{} to {}".format(j, current_num))
test_output = stats.ks_2samp(clusters_total[j], clusters_total[current_num])
report_file.print("\n" + str(test_output))
return
def kruskal_wallis_test(clusters_total, k_clusters, report_file):
"""
Runs and writes the results of Kruskal-Wallis test.
:param clusters_total: dict {cluster: [attr_value1, attr_value2, ...]}.
:param k_clusters: number of clusters to enforce.
:param report_file: report file object to document the result.
:return: None.
"""
arg_list = [clusters_total[i] for i in range(k_clusters)]
report_file.print("\nkruskal-wallis, {}-clusters:\n".format(k_clusters))
test_output = stats.kruskal(*arg_list)
report_file.print(str(test_output) + "\n")
return
def plot_attribute_bar(graph, cluster_method, vector_file_path=None, alpha_value=None,
identifier_string=IDENTIFIER_STRING, k_clusters=K, attribute=ATTRIBUTE,
color_palette=BAR_GRAPH_COLOR_PALETTE, report_file=REPORT_FILE):
"""
Plots a bar graph of the cluster composition for the discrete ATTRIBUTE.
:param graph: networkx graph.
:param cluster_method: cluster method label (e.g. "iac", "spectral", "role2vec", etc.).
:param vector_file_path: path to vector files (vector file invariant) if "iac".
:param alpha_value: alpha value if "iac".
:param identifier_string: dataset identifier string (e.g. "dblp", "twitch", etc.)
:param k_clusters: number of clusters to enforce.
:param attribute: attribute to use for plotting the distribution.
:param color_palette: color palette to be used for plotting the graphs.
:param report_file: report file object to document the statistical test results (Kolmogorov-Smirnov and Kruskal–Wallis).
:return: None.
"""
# Holder for categorical values of the attribute: when we take a set of it,
# we can determine the nodes' values without hard-coding them.
nodes = []
clusters_total = {cluster: [] for cluster in range(k_clusters)}
no_attribute_dict = {cluster: 0.0 for cluster in range(k_clusters)}
for node in graph.nodes:
node_cluster = graph.nodes[node]["cluster"]
try:
if graph.nodes[node][attribute] is not None:
# Since the data type is categorical, there is no need to convert to int or float or take log.
value = graph.nodes[node][attribute]
# Relabels the binary attribute to the attribute name itself for interpretability.
if value == 0 or value == "0" or value == "False" or value is False:
value = "not {}".format(attribute)
elif value == 1 or value == "1" or value == "True" or value is True:
value = attribute
clusters_total[node_cluster].append(value)
nodes.append(value)
except:
no_attribute_dict[node_cluster] += 1
continue
report_file.print(str([("Cluster {}".format(i), len(clusters_total[i])) for i in clusters_total]))
total_size = len(nodes)
if total_size == 0:
raise ValueError("Zero nodes")
set_of_attr_values = set(nodes)
list_of_attr_values = sorted(set_of_attr_values)
x_values = [i for i in range(k_clusters)]
attr_sections = {}
for attr_value in list_of_attr_values:
y_values = [clusters_total[a_cluster].count(attr_value)/len(clusters_total[a_cluster]) for a_cluster in x_values]
attr_sections[attr_value] = y_values
print(y_values)
offset = [0 for i in x_values]
for_legend_values = []
for_legend_labels = []
color_counter = 0
for attr_value in list_of_attr_values:
bar_container_object = plt.bar(x_values, attr_sections[attr_value], bottom=offset,
color=color_palette[color_counter])
for_legend_values.append(bar_container_object[0])
for_legend_labels.append(attr_value)
offset = np.add(offset, attr_sections[attr_value]).tolist()
color_counter += 1
plt.xlabel('Clusters')
plt.xticks(x_values)
plt.ylabel('Probability')
plt.legend(for_legend_values, for_legend_labels)
if cluster_method == "information_access":
vector_file_name_tokens = vector_file_path[:-4].split("_")
print(vector_file_name_tokens)
plt.title('Frequency of {} across\n{} clusters\n(alpha = {})'.format(attribute, cluster_method, alpha_value))
plt.savefig("output_files/{}_BG_K{}_{}_{}_{}_vs_{}.png".format(identifier_string, k_clusters,
vector_file_name_tokens[-2],
vector_file_name_tokens[-1], attribute,
cluster_method),
bbox_inches='tight')
else:
plt.title('Frequency of {} across\n{} clusters'.format(attribute, cluster_method))
plt.savefig(
"output_files/{}_BG_K{}_{}_vs_{}.png".format(identifier_string, k_clusters, attribute, cluster_method),
bbox_inches='tight')
plt.close()
return
def spectral_composition():
"""
Creates a file that shows the composition (by nodes) of the spectral clusters.
:return: a str path to the output file.
"""
with open(INPUT_PICKLED_GRAPH, "rb") as file:
graph = pickle.load(file)
output_filename = "output_files/{}_K{}_composition_map_spectral.csv".format(IDENTIFIER_STRING, K)
with open(output_filename, 'a') as file:
fieldnames = ["Cluster {}".format(k) for k in range(K)]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
user_obj_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
print("Composition map for spectral")
graph = spectral_clustering(graph)
clusters_total = {i: [] for i in range(K)}
for node_int in range(len(graph.nodes)):
j = graph.nodes[node_int]["cluster"]
clusters_total[j].append(node_int)
row = [clusters_total[k] for k in range(K)]
user_obj_writer.writerow(row)
return output_filename
def spectral_clustering(graph):
"""
Runs Spectral Clustering on the graph.
:param graph: networkx graph.
:return: networkx graph, having nodes with a populated "cluster" attribute.
"""
if nx.is_directed(graph):
# nx.Graph is used to make sure the adjacency matrix is symmetric, for that's what spectral clustering accepts.
temp_graph = nx.Graph()
for edge in graph.edges:
temp_graph.add_edge(edge[0], edge[1])
# Extracts only the necessary attribute values to reduce the space complexity.
# Hence, it doesn't call largest_connected_component_transform().
attributes_dict = {}
for node in graph.nodes:
try:
attributes_dict[node] = {ATTRIBUTE: graph.nodes[node][ATTRIBUTE]}
except:
continue
nx.set_node_attributes(temp_graph, attributes_dict)
graph = temp_graph
# Adapted from https://stackoverflow.com/questions/23684746/spectral-clustering-using-scikit-learn-on-graph-generated-through-networkx
node_list = list(graph.nodes())
# Converts graph to an adj matrix with adj_matrix[i][j] represents weight between node i,j.
adj_matrix = nx.to_numpy_matrix(graph, nodelist=node_list)
labels = SpectralClustering(affinity = 'precomputed', assign_labels="discretize",random_state=0,n_clusters=K).fit_predict(adj_matrix)
for node in node_list:
graph.nodes[node]["cluster"] = labels[node]
return graph
def cluster_labeling_spectral(spectral_clustering_file, spectral_labeling_file):
"""
Creates a labeling file for spectral clustering.
:param spectral_clustering_file: path to the clustering file from spectral_composition.
:param spectral_labeling_file: path to the output labeling file.
:return: None.
"""
with open(INPUT_PICKLED_GRAPH, "rb") as file:
graph = pickle.load(file)
cluster_dict = {}
with open(spectral_clustering_file, "r") as f:
lines = csv.reader(f)
first = True
for row in lines:
if first:
first = False
else:
for cluster in range(K):
nodes = row[cluster][1:-1].split(", ")
for node in nodes:
cluster_dict[int(node)] = cluster
with open(spectral_labeling_file, 'a') as file:
fieldnames = ["id", "cluster"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
user_obj_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
for node_int in range(len(graph.nodes)):
row = [node_int, cluster_dict[node_int]]
user_obj_writer.writerow(row)
return
def read_in_generic(labeling_file):
"""
Reads clusters into format: {node: cluster}.
:param labeling_file: labeling file with two columns: node and cluster.
:return: dict {node: cluster}.
"""
cluster_dict = {}
with open(labeling_file, "r") as f:
lines = csv.reader(f)
first = True
for row in lines:
if first:
first = False
else:
cluster_dict[int(row[0])] = int(row[1])
return cluster_dict
def assign_generic_clusters(graph, cluster_dict):
"""
Given a graph, assigns cluster labels to nodes from cluster_dict.
:param graph: networkx graph.
:param cluster_dict: dict {node: cluster}.
:return: networkx graph, having nodes with a populated "cluster" attribute.
"""
for node in graph.nodes:
cluster = int(cluster_dict[node])
graph.nodes[node]["cluster"] = cluster
return graph
# "repeated_fluidc"
def repeated_fluidc():
"""
Runs a repeats fluid communities clustering and determines mean and standard deviation
of the number of connected components in each resulting cluster.
:return: mean and standard deviation.
"""
# Access pickled graph:
with open(INPUT_PICKLED_GRAPH, "rb") as file:
G = pickle.load(file)
# Computing labelings:
seed_to_labeling = {}
for seed in SEEDS:
labeling_dict = fluid_communities(save_labeling=False, seed=seed)
seed_to_labeling[seed] = labeling_dict
# Documenting:
clustering_file = "output_files/{}_K{}_composition_map_fluidcr.csv".format(IDENTIFIER_STRING, K)
with open(clustering_file, 'w') as file:
# Header:
fieldnames = ["Seed_Values"]
fieldnames.extend(["Cluster {}".format(k) for k in range(K)])
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
user_obj_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
for seed in SEEDS:
print("Composition map for seed value = {}".format(seed))
clusters = {i: [] for i in range(K)}
for node in range(len(G)):
cluster = seed_to_labeling[seed][node]
clusters[cluster].append(node)
row = [seed]
row.extend(clusters[i] for i in range(K))
user_obj_writer.writerow(row)
# Relabeling for cluster consistency:
labeling_file = "output_files/{}_K{}_labeling_file_fluidcr.csv".format(IDENTIFIER_STRING, K)
cluster_labeling.main(clustering_file, labeling_file)
# Computation:
# Form: {node: {seed: cluster, seed: cluster…}…}}
cluster_dict = read_in_clusters(labeling_file)
seed_to_counts = {}
seed_to_sizes = {}
for seed in SEEDS:
cluster_dict_by_seed = {node: cluster_dict[node][seed] for node in range(len(G))}
count_dict, cluster_sizes = count_cc(cluster_dict_by_seed)
print("Connected component counts:", count_dict)
seed_to_counts[seed] = count_dict
seed_to_sizes[seed] = cluster_sizes
cluster_to_values = {i: [seed_to_counts[seed][i] for seed in SEEDS] for i in range(K)}