-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster.py
594 lines (459 loc) · 18.3 KB
/
cluster.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: topicpca.py
# Author: #cf
"""
Set of functions to perform clustering on data.
Built for topic probabilities or word frequencies as input.
Performs Principal Component Analysis or distance-based clustering.
"""
import os, glob, re
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
import pygal
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering as AC
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.cluster.hierarchy import cophenet
from scipy.spatial.distance import pdist
from sklearn import metrics
from scipy.cluster.hierarchy import fcluster
##################################
# Shared functions
##################################
def get_mastermatrix(MastermatrixFile):
with open(MastermatrixFile, "r") as InFile:
Mastermatrix = pd.read_csv(InFile)
#print(Mastermatrix.head())
return Mastermatrix
def get_topicdata(Mastermatrix):
Grouped = Mastermatrix.groupby(by=["idno"])
TopicData = Grouped.agg(np.mean)
TopicData = TopicData.iloc[:,5:-1]
Identifiers = TopicData.index.values
#print(TopicData)
#print(Identifiers)
return TopicData, Identifiers
def get_wordfreqs(WordfreqsFile):
with open(WordfreqsFile, "r") as InFile:
Wordfreqs = pd.read_csv(InFile, sep=";")
#print(Wordfreqs.head())
return Wordfreqs
def get_freqdata(Wordfreqs, MFW):
FreqData = Wordfreqs.iloc[0:MFW,1:]
FreqDataMean = np.mean(FreqData, axis=1)
FreqDataStd = np.std(FreqData, axis=1)
FreqData = FreqData.subtract(FreqDataMean, axis=0)
FreqData = FreqData.divide(FreqDataStd, axis=0)
FreqData = FreqData.T
#print(FreqData.head())
Identifiers = list(FreqData.index.values)
#print(Identifiers)
return FreqData, Identifiers
##################################
# Cluster Analysis with topics
##################################
tc_style = pygal.style.Style(
background='white',
plot_background='white',
font_family = "FreeSans",
title_font_size = 20,
legend_font_size = 16,
label_font_size = 12,
colors=["#1d91c0","#225ea8","#253494","#081d58", "#071746"])
def get_labels_tc(Identifiers, MetadataFile):
with open(MetadataFile, "r") as InFile:
Metadata = pd.read_csv(InFile, sep=",")
Metadata.set_index("idno", inplace=True)
#print(Metadata.head())
#print(Identifiers)
Labels = []
Colors = []
GroundTruth = []
for Item in Identifiers:
Labels.append(Item)
Colors.append("darkred")
GroundTruth.append(0)
"""
if Metadata.loc[Item,"tc_subgenre"] == "Comédie":
Labels.append(Item+"-CO")
Colors.append("darkred")
GroundTruth.append(0)
if Metadata.loc[Item,"tc_subgenre"] == "Tragi-comédie":
Labels.append(Item+"-TC")
Colors.append("darkgreen")
GroundTruth.append(1)
elif Metadata.loc[Item,"tc_subgenre"] == "Tragédie":
Labels.append(Item+"-TR")
Colors.append("darkblue")
GroundTruth.append(2)
"""
#print(Labels)
return Labels, Colors, GroundTruth
def clusteranalysis(TopicData, Method, Metric):
"""
docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html
"""
# perform the cluster analysis
LinkageMatrix = linkage(TopicData, method=Method, metric=Metric)
#print(LinkageMatrix[0:10])
return LinkageMatrix
def make_dendrogram(LinkageMatrix, GraphFolder,
Method, Metric, CorrCoeff, Labels, Colors,
DisplayLevels):
import matplotlib
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
plt.figure(figsize=(12,24))
plt.title("Plays clustered by topic probabilities", fontsize=14)
#plt.ylabel("Parameters: "+Method+" method, "+Metric+" metric. CorrCoeff: "+str(CorrCoeff)+".")
plt.xlabel("Distance\n(Parameters: "+Method+" / "+Metric+")", fontsize=12)
matplotlib.rcParams['lines.linewidth'] = 1.2
dendrogram(
LinkageMatrix,
p = DisplayLevels,
truncate_mode="level",
color_threshold = 1.3,
show_leaf_counts = True,
no_labels = False,
orientation="left",
labels = Labels,
leaf_rotation = 0, # rotates the x axis labels
leaf_font_size = 4, # font size for the x axis labels
)
#plt.show()
plt.savefig(GraphFolder+"dendrogram_"+Method+"-"+Metric+"-"+str(DisplayLevels)+".png", dpi=300, figsize=(12,18), bbox_inches="tight")
plt.close()
def evaluate_cluster(TopicData, LinkageMatrix, GroundTruth):
# check the correlation coefficient
CorrCoeff, coph_dists = cophenet(LinkageMatrix, pdist(TopicData))
## check several cluster evaluation metrics
Threshold = 2
FlatClusterNumbers = fcluster(LinkageMatrix, Threshold)
#print(GroundTruth)
#print(FlatClusterNumbers)
ARI = metrics.adjusted_rand_score(GroundTruth, FlatClusterNumbers)
Homog = metrics.homogeneity_score(GroundTruth, FlatClusterNumbers)
Compl = metrics.completeness_score(GroundTruth, FlatClusterNumbers)
VMeasure = metrics.v_measure_score(GroundTruth, FlatClusterNumbers)
print("Evaluation metrics with threshold "+str(Threshold))
print("CorrCoeff:", CorrCoeff)
print("adjustedRI:", ARI)
print("Homogeneity:", Homog)
print("Completeness:", Compl)
print("V-Measure:", VMeasure)
return CorrCoeff, ARI, Homog, Compl, VMeasure
def topiccluster(MastermatrixFile,
MetadataFile,
Method,
Metric,
GraphFolder,
DisplayLevels):
print("Launched topiccluster.")
Mastermatrix = get_mastermatrix(MastermatrixFile)
TopicData, Identifiers = get_topicdata(Mastermatrix)
Labels, Colors, GroundTruth = get_labels_tc(Identifiers, MetadataFile)
LinkageMatrix = clusteranalysis(TopicData, Method, Metric)
CorrCoeff, ARI, Homog, Compl, VMeasure = evaluate_cluster(TopicData,
LinkageMatrix,
GroundTruth)
make_dendrogram(LinkageMatrix, GraphFolder,
Method, Metric,
CorrCoeff, Labels, Colors,
DisplayLevels)
print("Done.")
##################################
# Cluster Analysis with words
##################################
tc_style = pygal.style.Style(
background='white',
plot_background='white',
font_family = "FreeSans",
title_font_size = 20,
legend_font_size = 16,
label_font_size = 12,
colors=["#1d91c0","#225ea8","#253494","#081d58", "#071746"])
def get_labels_wc(Identifiers, MetadataFile):
with open(MetadataFile, "r") as InFile:
Metadata = pd.read_csv(InFile, sep=";")
Metadata.set_index("idno", inplace=True)
#print(Metadata.head())
#print(Identifiers)
Labels = []
Colors = []
GroundTruth = []
for Item in Identifiers:
if Metadata.loc[Item,"tc_subgenre"] == "Comédie":
Labels.append(Item+"-CO")
Colors.append("darkred")
GroundTruth.append(0)
if Metadata.loc[Item,"tc_subgenre"] == "Tragi-comédie":
Labels.append(Item+"-TC")
Colors.append("darkgreen")
GroundTruth.append(1)
elif Metadata.loc[Item,"tc_subgenre"] == "Tragédie":
Labels.append(Item+"-TR")
Colors.append("darkblue")
GroundTruth.append(2)
#print(Labels)
return Labels, Colors, GroundTruth
def clusteranalysis_w(TopicData, Method, Metric):
"""
docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html
"""
# perform the cluster analysis
LinkageMatrix = linkage(TopicData, method=Method, metric=Metric)
#print(LinkageMatrix[0:10])
return LinkageMatrix
def make_dendrogram_w(LinkageMatrix, GraphFolder,
Method, Metric, CorrCoeff, Labels, Colors,
DisplayLevels):
import matplotlib
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
plt.figure(figsize=(12,24))
plt.title("Plays clustered by topic probabilities", fontsize=14)
#plt.ylabel("Parameters: "+Method+" method, "+Metric+" metric. CorrCoeff: "+str(CorrCoeff)+".")
plt.xlabel("Distance\n(Parameters: "+Method+" / "+Metric+")", fontsize=12)
matplotlib.rcParams['lines.linewidth'] = 1.2
dendrogram(
LinkageMatrix,
p = DisplayLevels,
truncate_mode="level",
color_threshold = 30,
show_leaf_counts = True,
no_labels = False,
orientation="left",
labels = Labels,
leaf_rotation = 0, # rotates the x axis labels
leaf_font_size = 4, # font size for the x axis labels
)
#plt.show()
plt.savefig(GraphFolder+"dendrogram_"+Method+"-"+Metric+"-"+str(DisplayLevels)+".png", dpi=300, figsize=(12,18), bbox_inches="tight")
plt.close()
def evaluate_cluster_w(TopicData, LinkageMatrix, GroundTruth):
# check the correlation coefficient
CorrCoeff, coph_dists = cophenet(LinkageMatrix, pdist(TopicData))
## check several cluster evaluation metrics
Threshold = 2
FlatClusterNumbers = fcluster(LinkageMatrix, Threshold)
#print(GroundTruth)
#print(FlatClusterNumbers)
ARI = metrics.adjusted_rand_score(GroundTruth, FlatClusterNumbers)
Homog = metrics.homogeneity_score(GroundTruth, FlatClusterNumbers)
Compl = metrics.completeness_score(GroundTruth, FlatClusterNumbers)
VMeasure = metrics.v_measure_score(GroundTruth, FlatClusterNumbers)
print("Evaluation metrics with threshold "+str(Threshold))
print("CorrCoeff:", CorrCoeff)
print("adjustedRI:", ARI)
print("Homogeneity:", Homog)
print("Completeness:", Compl)
print("V-Measure:", VMeasure)
return CorrCoeff, ARI, Homog, Compl, VMeasure
def wordcluster(WordfreqsFile,
AllMFW,
MetadataFile,
Method,
Metric,
GraphFolder,
DisplayLevels):
print("Launched wordcluster.")
Wordfreqs = get_wordfreqs(WordfreqsFile)
for MFW in AllMFW:
FreqData, Identifiers = get_freqdata(Wordfreqs, MFW)
Labels, Colors, GroundTruth = get_labels_tc(Identifiers, MetadataFile)
LinkageMatrix = clusteranalysis(FreqData, Method, Metric)
CorrCoeff, ARI, Homog, Compl, VMeasure = evaluate_cluster(FreqData,
LinkageMatrix,
GroundTruth)
make_dendrogram_w(LinkageMatrix, GraphFolder,
Method, Metric,
CorrCoeff, Labels, Colors,
DisplayLevels)
print("Done.")
##################################
# PCA with topics
##################################
tp_style = pygal.style.Style(
background='white',
plot_background='white',
font_family = "FreeSans",
title_font_size = 20,
legend_font_size = 16,
label_font_size = 12,
colors=["#1d91c0","#225ea8","#253494","#081d58", "#071746"])
def get_colors_t(Identifiers, MetadataFile):
with open(MetadataFile, "r") as InFile:
Metadata = pd.read_csv(InFile, sep=";")
Labels = list(Metadata.loc[:,"tc_subgenre"])
Colors = []
for item in Labels:
if item == "Comédie":
Colors.append("darkred")
if item == "Tragi-comédie":
Colors.append("darkgreen")
elif item == "Tragédie":
Colors.append("navy")
#print(Colors)
return Colors
def apply_pca_t(TopicData):
pca = PCA(n_components=60)
pca.fit(TopicData)
Variance = pca.explained_variance_ratio_
Transformed = pca.transform(TopicData)
#print(Transformed)
CumVar = 0
DimCount = 0
for item in Variance:
CumVar = item+CumVar
DimCount +=1
#print("{:02d}".format(DimCount), "{:3f}".format(CumVar))
return Transformed, Variance
def make_2dscatterplot_t(Transformed, GraphFolder):
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
plot = pygal.XY(style=tp_style,
stroke=False)
Data = []
for i in range(0,391):
Point = (Transformed[i][0], Transformed[i][1])
Data.append(Point)
plot.add("test", Data)
plot.render_to_file(GraphFolder+"2dscatter.svg")
def make_3dscatterplot_t(Transformed, Variance, Colors, GraphFolder):
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
azims = range(200,300,10)
elevs = range(200,300,10)
for azim in azims:
for elev in elevs:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
allx = []
ally = []
allz = []
for i in range(0,391):
allx.append(Transformed[i][0])
ally.append(Transformed[i][1])
allz.append(Transformed[i][2])
ax.scatter(allx, ally, allz, c=Colors, marker="o", s=10, linewidth=0.3)
plt.setp(ax.get_xticklabels(), fontsize=5)
plt.setp(ax.get_yticklabels(), fontsize=5)
plt.setp(ax.get_zticklabels(), fontsize=5)
ax.set_xlabel("PC1 "+"{:03.2f}".format(Variance[0]), fontsize=8)
ax.set_ylabel("PC2 "+"{:03.2f}".format(Variance[1]), fontsize=8)
ax.set_zlabel("PC3 "+"{:03.2f}".format(Variance[2]), fontsize=8)
ax.azim = azim
ax.elev = elev
#plt.show()
fig.savefig(GraphFolder+"3dscatter_"+"{:03d}".format(azim)+"-"+"{:03d}".format(elev)+".png", dpi=600, figsize=(3,3), bbox_inches="tight", facecolor="white", transparent=True)
plt.close()
### Main function ###
def topicpca(MastermatrixFile,
MetadataFile,
GraphFolder):
"""
Coordinating function.
"""
print("Launched topicpca.")
Mastermatrix = get_mastermatrix(MastermatrixFile)
TopicData, Identifiers = get_topicdata(Mastermatrix)
Colors = get_colors_t(Identifiers, MetadataFile)
Transformed, Variance = apply_pca_t(TopicData)
#make_2dscatterplot_t(Transformed, GraphFolder)
make_3dscatterplot_t(Transformed, Variance, Colors, GraphFolder)
print("Done.")
################################
# PCA with word frequencies
################################
wd_style = pygal.style.Style(
background='white',
plot_background='white',
font_family = "FreeSans",
title_font_size = 20,
legend_font_size = 16,
label_font_size = 12,
colors=["#1d91c0","#225ea8","#253494","#081d58", "#071746"])
def get_colors_w(Identifiers, MetadataFile):
with open(MetadataFile, "r") as InFile:
Metadata = pd.read_csv(InFile, sep=";")
Metadata.set_index("idno", inplace=True)
#print(Metadata.head())
Colors = []
for Item in Identifiers:
Label = Metadata.loc[Item,"tc_subgenre"]
#print(Item, Label)
if Label == "Comédie":
Colors.append("darkred")
if Label == "Tragi-comédie":
Colors.append("darkgreen")
elif Label == "Tragédie":
Colors.append("navy")
#print(Colors)
return Colors
def apply_pca_w(FreqData):
pca = PCA(n_components=3)
pca.fit(FreqData)
Variance = pca.explained_variance_ratio_
Transformed = pca.transform(FreqData)
#print(Transformed)
#print(Variance)
return Transformed, Variance
def make_2dscatterplot_w(Transformed, GraphFolder):
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
plot = pygal.XY(style=wd_style,
stroke=False)
Data = []
for i in range(0,391):
Point = (Transformed[i][0], Transformed[i][1])
Data.append(Point)
plot.add("test", Data)
plot.render_to_file(GraphFolder+"2dscatter.svg")
def make_3dscatterplot_w(Transformed, Variance, Colors, GraphFolder, MFW):
if not os.path.exists(GraphFolder):
os.makedirs(GraphFolder)
azims = range(0,350,10)
elevs = range(180,350,10)
for azim in azims:
for elev in elevs:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
allx = []
ally = []
allz = []
for i in range(0,391):
allx.append(Transformed[i][0])
ally.append(Transformed[i][1])
allz.append(Transformed[i][2])
ax.scatter(allx, ally, allz, c=Colors, marker="o", s=6, linewidth=0.3)
plt.setp(ax.get_xticklabels(), fontsize=3)
plt.setp(ax.get_yticklabels(), fontsize=3)
plt.setp(ax.get_zticklabels(), fontsize=3)
ax.set_xlabel("PC1 "+"{:03.2f}".format(Variance[0]), fontsize=4)
ax.set_ylabel("PC2 "+"{:03.2f}".format(Variance[1]), fontsize=4)
ax.set_zlabel("PC3 "+"{:03.2f}".format(Variance[2]), fontsize=4)
ax.azim = azim
ax.elev = elev
#plt.show()
fig.savefig(GraphFolder+"3dscatter_"+"{:04d}".format(MFW)+"mfw-"+"{:03d}".format(azim)+"-"+"{:03d}".format(elev)+".png", dpi=600, figsize=(3,3), bbox_inches="tight")
plt.close()
### Main function ###
def wordpca(WordfreqsFile,
MetadataFile,
GraphFolder,
AllMFW):
"""
Coordinating function.
"""
print("Launched wordpca.")
WordFreqs = get_wordfreqs(WordfreqsFile)
for MFW in AllMFW:
FreqData, Identifiers = get_freqdata(WordFreqs, MFW)
Colors = get_colors_w(Identifiers, MetadataFile)
Transformed, Variance = apply_pca_w(FreqData)
#make_2dscatterplot_w(Transformed, GraphFolder)
make_3dscatterplot_w(Transformed, Variance, Colors, GraphFolder, MFW)
print("Done.")