Analysis_final_mult.py 46.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
import ndjson
import jsonlines
import json
import pickle
import os
import sys
import random as rd
import json
import re, regex
from joblib import dump, load
import collections
import math
import statistics
import itertools
23
import multiprocessing as mp
24
25
26
27
28
29

from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import PassiveAggressiveClassifier, SGDClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
30
31
import matplotlib
matplotlib.use('agg')
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
32
33
34
35
import matplotlib.colors as cl
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns # data visualization library  
36
37
38
# In[2]:

path = '/draco/ptmp/mschuber/PAN/Data/pan19-celebrity-profiling-training-dataset-2019-01-31/stratified_subsample/'
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
39
savedir = '/draco/ptmp/mschuber/PAN/Data/results/'
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#path = '../Data/pan19-celebrity-profiling-training-dataset-2019-01-31/stratified_subsample/'

subana_l = ['org/', 'min_tweets_1000/', 'complete_balance/']

subsets_l = [200, 500, 1000, 2000]

classifiers = ['SVM']

datafolder = 'split_data/'

ml_results = 'ml/'

filebeg = 'stratified_subsample_'

labels_l = ['age', 'gender', 'author']

phases_l = ['child_21', 'young_adult_35', 'adult_50', 'old_adult_65', 'retiree']


Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
59
60
61
62
63

    #get_ipython().run_line_magic('matplotlib', 'inline')
    #import matplotlib

cmap = cl.LinearSegmentedColormap.from_list("", ["skyblue","cadetblue","darkblue", "steelblue"]) #define colors
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
# In[3]:


####tester

#subana = ['org/']

#subsets = [200]

#classifiers = ['SVM']

#datafolder = 'split_data/'

#ml_results = 'ml/'

#filebeg = 'stratified_subsample_'

#labels = ['age', 'gender', 'author']


# In[4]:


def identity_tokenizer(text):
    return text

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
90
def plot_confusion_matrix(cm, classes,normalize=True,title='Confusion matrix',cmap=plt.cm.Blues, ax = None):
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
   """
   This function prints and plots the confusion matrix.
   Normalization can be applied by setting `normalize=True`.
   """
   if not ax:
       ax = plt.gca()
       
       
   cm_old = cm
   if normalize:
       cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
       print("Normalized confusion matrix")
   else:
       print('Confusion matrix, without normalization')
   #print(cm)


   im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
109
   #plt.title(title)
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
   cbar = ax.figure.colorbar(im, ax = ax, ticks=[], label = "Heat per Row (Normalized from 0 to 1)")
   tick_marks = np.arange(len(classes))
   #ax.set_xticks(tick_marks)
   #ax.set_yticks(tick_marks)
   #ax.set_xticklabels(classes, rotation=45)
   #ax.set_yticklabels(classes)
   ax.set(xticks=np.arange(cm.shape[1]),
          yticks=np.arange(cm.shape[0]),
          # ... and label them with the respective list entries
          xticklabels=classes, yticklabels=classes,
          ylabel='True label',
          xlabel='Predicted label')    
   # Rotate the tick labels and set their alignment.
   plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
            rotation_mode="anchor")
   #make it so that text is on minor label and not on edge of boundary (i.e. half cutoff at top and bottom) 
   ax.set_xticks(np.arange(cm.shape[1]+1)-.5, minor=True)
   ax.set_yticks(np.arange(cm.shape[0]+1)-.5, minor=True)
   
   fmt = '.2f' if normalize else 'd'
   fmt = 'd'
   thresh = cm.max() / 1.5

   for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
       ax.text(j, i, format(cm_old[i, j], fmt),
                ha="center",
                va="center",
                color="white" if cm[i, j] > thresh else "black")
       
139

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
140
       
141
142
143


    # Start with analysis of precision and recall as well as heatmaps/confusion matrices:
144
145

def plotter(subsets, subana, phases, labels):
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
    df_dic = {}
    res_dic = {}
    author_dic = {}

    for st in subsets:

        res_dic[st] = {}
       
        df_dic[st] = {}
        author_dic[st] = {}
        for ana in subana:
            
            res_dic[st][ana.split('/')[0]] = {}
            df_dic[st][ana.split('/')[0]] = {}
            author_dic[st][ana.split('/')[0]] = {}
            ###make dic with all authors
            with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_author_train.json', 'r', encoding='utf-8') as f:
                authors = json.load(f)
            with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_gender_train.json', 'r', encoding='utf-8') as f:
                gender = json.load(f)            
            with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_age_train.json', 'r', encoding='utf-8') as f:
                year = json.load(f)
            

            for i in range(0, len(year)):
                age = 2019 - year[i]
                
                if age <22:
                    lifePhase = 'child_21'
                elif age <36:
                    lifePhase = 'young_adult_35'
                elif age < 51:
                    lifePhase = 'adult_50'
                elif age <66:
                    lifePhase = 'old_adult_65'
                else:
                    lifePhase = 'retiree'
                
                author_dic[st][ana.split('/')[0]][authors[i]] = {}
                author_dic[st][ana.split('/')[0]][authors[i]]['life_phase'] = lifePhase
                author_dic[st][ana.split('/')[0]][authors[i]]['age'] = year[i]
                author_dic[st][ana.split('/')[0]][authors[i]]['gender'] = gender[i]
                      
            
            df = pd.DataFrame()
            with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_bigram_vocab.json', 'r', encoding='utf-8') as f:
                vocab = json.load(f)
                
                res_dic[st][ana.split('/')[0]]['vocab'] = vocab
                res_dic[st][ana.split('/')[0]]['vocab_inverse'] = {v:k for k,v in vocab.items()}
            ##update  "vocab" to include the tweet length as feature to display
            if len(vocab) not in res_dic[st][ana.split('/')[0]]['vocab_inverse']:
                leng = len(vocab)
                res_dic[st][ana.split('/')[0]]['vocab']['§LENGTH§'] = leng
                res_dic[st][ana.split('/')[0]]['vocab_inverse'][leng] = '§LENGTH§'
            else:
                print('error; key already exists')
                print(res_dic[st][ana.split('/')[0]]['vocab_inverse'][len(vocab)])
                sys.exit(1)
            
            
            for label in labels:
                
                res_dic[st][ana.split('/')[0]][label] = {}
                
                enc = load(path+ana+str(st)+'/'+ml_results+filebeg+label+'_'+str(st)+'_encoder.jlib')
                res_dic[st][ana.split('/')[0]][label]['label_encoder'] = enc          
                
                for clf in classifiers:
                    
                    clf_l = load(path+ana+str(st)+'/'+ml_results+filebeg+clf+'_'+label+'_'+str(st)+'_svm_out_count.jlib')
                    
                    with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_'+label+'_test.json') as f:
                        lab = json.load(f)
                        df[ana.split('/')[0]+'_'+str(st)+'_'+clf+'_'+label] = lab
                        print(str(st)+'_'+ana+'_'+label+'_'+clf)
                        if label == 'age':
                            phase = []
                            for el in lab:
                                age = 2019 - el
                                if age <22:
                                    lifePhase = 'child_21'
                                elif age <36:
                                    lifePhase = 'young_adult_35'
                                elif age < 51:
                                    lifePhase = 'adult_50'
                                elif age <66:
                                    lifePhase = 'old_adult_65'
                                else:
                                    lifePhase = 'retiree'
                                phase.append(lifePhase)
                            df[ana.split('/')[0]+'_'+str(st)+'_life_phase'] = phase
                            
                        
                        
                        #print(len(json.load(f)))
                    
                    res_dic[st][ana.split('/')[0]][label][clf] = clf_l.coef_
       
                    
                    
                    df[ana.split('/')[0]+'_'+str(st)+'_'+clf+'_'+label+'_pred_enc'] = list(load(path+ana+str(st)+'/'+ml_results+filebeg+clf+'_'+label+'_'+str(st)+'_predictions_count.jlib'))
                    rev_enc = list(enc.inverse_transform(load(path+ana+str(st)+'/'+ml_results+filebeg+clf+'_'+label+'_'+str(st)+'_predictions_count.jlib')))
                    df[ana.split('/')[0]+'_'+str(st)+'_'+clf+'_'+label+'_pred'] = rev_enc
                    if label == 'age':
                        phase = []
                        for el in rev_enc:
                            age = 2019 - el
                            if age <22:
                                lifePhase = 'child_21'
                            elif age <36:
                                lifePhase = 'young_adult_35'
                            elif age < 51:
                                lifePhase = 'adult_50'
                            elif age <66:
                                lifePhase = 'old_adult_65'
                            else:
                                lifePhase = 'retiree'
                            phase.append(lifePhase)
                                
                        df[ana.split('/')[0]+'_'+str(st)+'_life_phase_pred'] = phase
                        
                        
                    res_dic[st][ana.split('/')[0]][label]['labels'] = {}
                    for l in lab:
                        res_dic[st][ana.split('/')[0]][label]['labels'][l] = {}
                    
                    
                    
            df_dic[st][ana.split('/')[0]]['df'] = df


    # In[ ]:





    # In[ ]:





    # In[ ]:


    for st in subsets:
        for ana in subana:
            an = ana.split('/')[0]
            for label in labels:
                
                enc = res_dic[st][an][label]['label_encoder']
                coef = res_dic[st][an][label]['SVM']
                key_len = len(res_dic[st][an][label]['labels'].keys())
                df = df_dic[st][an]['df']
                res_dic[st][an][label]['acc'] = accuracy_score(df[an+'_'+str(st)+'_SVM_'+label], df[an+'_'+str(st)+'_SVM_'+label+'_pred']).round(3)
                res_dic[st][an][label]['prec'] = precision_score(df[an+'_'+str(st)+'_SVM_'+label], df[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)
                res_dic[st][an][label]['rec'] = recall_score(df[an+'_'+str(st)+'_SVM_'+label], df[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)
                res_dic[st][an][label]['f1'] = f1_score(df[an+'_'+str(st)+'_SVM_'+label], df[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)
                
                for key in res_dic[st][an][label]['labels'].keys():
                    key_enc = enc.transform([key])[0]
        
                    subDf = df.loc[df[an+'_'+str(st)+'_SVM_'+label] == key]
                    if label == 'author':
                        row = df.loc[df[an+'_'+str(st)+'_'+'SVM'+'_'+'author'] == key].iloc[0]
                        res_dic[st][an][label]['labels'][key]['gender'] = row[an+'_'+str(st)+'_'+'SVM'+'_'+'gender']
                        res_dic[st][an][label]['labels'][key]['age'] = row[an+'_'+str(st)+'_'+'SVM'+'_'+'age']
                        res_dic[st][an][label]['labels'][key]['life_phase'] = row[an+'_'+str(st)+'_'+'life_phase']
                    elif label == 'age':
                        age = 2019 -key
                        if age <22:
                            lifePhase = 'child_21'
                        elif age <36:
                            lifePhase = 'young_adult_35'
                        elif age < 51:
                            lifePhase = 'adult_50'
                        elif age <66:
                            lifePhase = 'old_adult_65'
                        else:
                            lifePhase = 'retiree'

                            
                        res_dic[st][an][label]['labels'][key]['life_phase'] = lifePhase
                        
                        
                    res_dic[st][an][label]['labels'][key]['acc'] = accuracy_score(subDf[an+'_'+str(st)+'_SVM_'+label], subDf[an+'_'+str(st)+'_SVM_'+label+'_pred']).round(3)
                    ##no second category for subanalysis: prec = 1
                    #res_dic[st][an][label]['labels'][key]['prec'] = precision_score(subDf[an+'_'+str(st)+'_SVM_'+label], subDf[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)
                    ## precision always equals recall in subanalyis
                    #res_dic[st][an][label]['labels'][key]['rec'] = recall_score(subDf[an+'_'+str(st)+'_SVM_'+label], subDf[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)
                    ##f1 score is ill defined
                    #res_dic[st][an][label]['labels'][key]['f1'] = f1_score(subDf[an+'_'+str(st)+'_SVM_'+label], subDf[an+'_'+str(st)+'_SVM_'+label+'_pred'], average='weighted').round(3)

                    if key_len > 2:
                        res_dic[st][an][label]['labels'][key]['feature_vec'] = coef[key_enc]
                    
                    elif key_enc > 0:
                        res_dic[st][an][label]['labels'][key]['feature_vec'] = coef[0]
                        



    ###save top 25 most predictive labels for each set and each subset in groups


    most_pred = {}


    for st in subsets:
        most_pred[st] = {}
        for ana in subana:
            an = ana.split('/')[0]
            most_pred[st][an] = {}
            for label in labels:
                most_pred[st][an][label] = {'feature_vecs':[]}
                for ph in phases:
                    most_pred[st][an][label][ph] = {'feature_vecs_pos': [], 'feature_vecs_neg': [], 'val_array': []}
                    if label in ['author']:
                        for sex in ['male', 'female']:
                            most_pred[st][an][label][ph][sex] = {'feature_vecs_pos':[], 'feature_vecs_neg':[],
                                                                    'val_array': []}
                            most_pred[st][an][label][sex] = {'feature_vecs_pos':[], 'feature_vecs_neg':[],
                                                             'val_array': []}

                with open(path+ana+str(st)+'/'+datafolder+filebeg+str(st)+'_bigram_vocab.json' , 'r', encoding = 'utf-8') as f:
                    most_pred[st][an]['vocab'] = json.load(f) 
                ##author and age to have different depth than gender and can be used for life phases
                if label in ['age']:
                    for key in res_dic[st][an][label]['labels'].keys():
                        ph = res_dic[st][an][label]['labels'][key]['life_phase']
                        sort = list(np.argsort(res_dic[st][an][label]['labels'][key]['feature_vec']))
                        array = res_dic[st][an][label]['labels'][key]['feature_vec']
                        most_pred[st][an][label][ph]['feature_vecs_pos'].append([i for i in sort if array[i] > 0 ])

                        most_pred[st][an][label][ph]['feature_vecs_neg'].append([i for i in sort if array[i] < 0 ])
                        if type(most_pred[st][an][label][ph]['val_array']) != type([]):
                            A = most_pred[st][an][label][ph]['val_array']
                            most_pred[st][an][label][ph]['val_array'] = np.vstack((A, array))
                        
                        else:
                            most_pred[st][an][label][ph]['val_array'] = array
                    for ph in phases:
                        most_pred[st][an][label][ph]['min_array'] = np.amin(most_pred[st][an][label][ph]['val_array'], axis=0)
                        most_pred[st][an][label][ph]['max_array'] = np.amax(most_pred[st][an][label][ph]['val_array'], axis=0)
                        most_pred[st][an][label][ph]['number'] = most_pred[st][an][label][ph]['val_array'].shape[0]
                        most_pred[st][an][label][ph]['val_array'] = np.mean(most_pred[st][an][label][ph]['val_array'], axis = 0)
      
                            
                elif label in ['author']:
                    for key in res_dic[st][an][label]['labels'].keys():
                        ph = res_dic[st][an][label]['labels'][key]['life_phase']
                        sex = res_dic[st][an][label]['labels'][key]['gender']
                        sort = list(np.argsort(res_dic[st][an][label]['labels'][key]['feature_vec']))
                        array = res_dic[st][an][label]['labels'][key]['feature_vec']
                        m_pred_pos = [i for i in sort if array[i] > 0 ]
                        m_pred_neg = [i for i in sort if array[i] < 0 ]
                        most_pred[st][an][label][ph]['feature_vecs_pos'].append(m_pred_pos)
                        most_pred[st][an][label][sex]['feature_vecs_pos'].append(m_pred_pos)
                        most_pred[st][an][label][ph][sex]['feature_vecs_pos'].append(m_pred_pos)
                        most_pred[st][an][label][ph]['feature_vecs_neg'].append(m_pred_neg)
                        most_pred[st][an][label][sex]['feature_vecs_neg'].append(m_pred_neg)
                        most_pred[st][an][label][ph][sex]['feature_vecs_neg'].append(m_pred_neg)
                        
                        if type(most_pred[st][an][label][ph]['val_array']) != type([]):
                            A = most_pred[st][an][label][ph]['val_array']
                            most_pred[st][an][label][ph]['val_array'] = np.vstack((A, array))
                        
                        else:
                            most_pred[st][an][label][ph]['val_array'] = array
                            
                        if type(most_pred[st][an][label][sex]['val_array']) != type([]):
                            A = most_pred[st][an][label][sex]['val_array']
                            most_pred[st][an][label][sex]['val_array'] = np.vstack((A, array))
                        
                        else:

                            most_pred[st][an][label][sex]['val_array'] = array
                            
                        if type(most_pred[st][an][label][ph][sex]['val_array']) != type([]):
                            A = most_pred[st][an][label][ph][sex]['val_array']
                            most_pred[st][an][label][ph][sex]['val_array'] = np.vstack((A, array))
                        
                        else:
                            most_pred[st][an][label][ph][sex]['val_array'] = array
                            
                            
                    check = True
                    for ph in phases:        
                        most_pred[st][an][label][ph]['min_array'] = np.amin(most_pred[st][an][label][ph]['val_array'], axis = 0)
                        most_pred[st][an][label][ph]['max_array'] = np.amax(most_pred[st][an][label][ph]['val_array'], axis = 0)
                        most_pred[st][an][label][ph]['number'] = most_pred[st][an][label][ph]['val_array'].shape[0]
                        most_pred[st][an][label][ph]['val_array'] = np.mean(most_pred[st][an][label][ph]['val_array'], axis = 0)
                        for sex in ['female', 'male']:
                            if check:
                                #print(sex)
                                #print(most_pred[st][an][label][sex]['val_array'])
                                most_pred[st][an][label][sex]['min_array'] = np.amin(most_pred[st][an][label][sex]['val_array'], axis = 0)
                                most_pred[st][an][label][sex]['max_array'] = np.amax(most_pred[st][an][label][sex]['val_array'], axis = 0)
                                most_pred[st][an][label][sex]['number'] = most_pred[st][an][label][sex]['val_array'].shape[0]
                                most_pred[st][an][label][sex]['val_array'] = np.mean(most_pred[st][an][label][sex]['val_array'], axis = 0)
                                #print(most_pred[st][an][label][sex]['val_array'])
                                #print(most_pred[st][an][label][sex]['min_array'])
                                #print(most_pred[st][an][label][sex]['max_array'])
        
                            most_pred[st][an][label][ph][sex]['min_array']= np.amin(most_pred[st][an][label][ph][sex]['val_array'], axis = 0)
                            most_pred[st][an][label][ph][sex]['max_array'] =np.amax(most_pred[st][an][label][ph][sex]['val_array'], axis = 0)
                            most_pred[st][an][label][ph][sex]['number'] = most_pred[st][an][label][ph][sex]['val_array'].shape[0]
                            most_pred[st][an][label][ph][sex]['val_array'] = np.mean(most_pred[st][an][label][ph][sex]['val_array'], axis = 0)
                        check = False
                         
                
                else:
                    
                    most_pred[st][an][label]['feature_vecs'].append(list(np.argsort(res_dic[st][an][label]['labels']['male']['feature_vec'])))


    #sys.exit(1)                
    for st in subsets:
        for ana in subana:
            an = ana.split('/')[0]
            for label in labels:
                if label == 'age':
                    for ph in phases:

                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_pos']:
                            c.update(list(vec))
                        most_pred[st][an][label][ph]['count_tot_pos'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_pos']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][ph]['count_top25_pos'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_neg']:
                            c.update(list(vec))
                        most_pred[st][an][label][ph]['count_tot_neg'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_neg']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][ph]['count_top25_neg'] = c.most_common()
          
                if label == 'author':
                    for ph in phases:
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_pos']:
                            c.update(list(vec))
                        most_pred[st][an][label][ph]['count_tot_pos'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_pos']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][ph]['count_top25_pos'] = c.most_common()
                        for sex in ['male', 'female']:
                            c = collections.Counter()
                            for vec in most_pred[st][an][label][ph][sex]['feature_vecs_pos']:
                                c.update(list(vec))
                            most_pred[st][an][label][ph][sex]['count_tot_pos'] = c.most_common()
                            c = collections.Counter()
                            for vec in most_pred[st][an][label][ph][sex]['feature_vecs_pos']:
                                c.update(list(vec[-25:]))
                            most_pred[st][an][label][ph][sex]['count_top25_pos'] = c.most_common()
                            
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_neg']:
                            c.update(list(vec))
                        most_pred[st][an][label][ph]['count_tot_neg'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][ph]['feature_vecs_neg']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][ph]['count_top25_neg'] = c.most_common()
                        for sex in ['male', 'female']:
                            c = collections.Counter()
                            for vec in most_pred[st][an][label][ph][sex]['feature_vecs_neg']:
                                c.update(list(vec))
                            most_pred[st][an][label][ph][sex]['count_tot_neg'] = c.most_common()
                            c = collections.Counter()
                            for vec in most_pred[st][an][label][ph][sex]['feature_vecs_neg']:
                                c.update(list(vec[-25:]))
                            most_pred[st][an][label][ph][sex]['count_top25_neg'] = c.most_common()                        
                    for sex in ['male', 'female']:
                        
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][sex]['feature_vecs_pos']:
                            c.update(list(vec))
                        most_pred[st][an][label][sex]['count_tot_pos'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][sex]['feature_vecs_pos']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][sex]['count_top25_pos'] = c.most_common()                       
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][sex]['feature_vecs_neg']:
                            c.update(list(vec))
                        most_pred[st][an][label][sex]['count_tot_neg'] = c.most_common()
                        c = collections.Counter()
                        for vec in most_pred[st][an][label][sex]['feature_vecs_neg']:
                            c.update(list(vec[-25:]))
                        most_pred[st][an][label][sex]['count_top25_neg'] = c.most_common()                           
              
                    










Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
556

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
557
558


559
    
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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


    for st in subsets:
        for ana in subana:
            an = ana.split('/')[0]
            tmp = []
            index = []
            for label in labels:
                comp = {'accuracy': accuracy_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label+'_pred']).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label+'_pred'],
                                                 average='weighted').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label+'_pred'],
                                                 average='weighted').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_'+label+'_pred'],
                                                 average='weighted').round(3),
                       }
                tmp.append(comp)
                index.append(label)
                
                if label == 'age':
                    
                    comp = {'accuracy': accuracy_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred']).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred'],
                                                 average='weighted').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred'],
                                                 average='weighted').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred'],
                                                 average='weighted').round(3)
                           }
                        
                    tmp.append(comp)
                    index.append('age by life_phase')
                    
                    np.set_printoptions(precision=2)
                    cnf_matrix = confusion_matrix(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                                 df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred'],
                                                 labels=phases)
                    f = plt.figure()
                    ax = f.subplots()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
607
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
608
609
                    plt.tight_layout()
                    #plt.show()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
610
                    #f.savefig('../Data/results/heatmaps/test.png')
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
611
                    f.savefig(savedir+ 'heatmaps/cm_{st}_{an}_{label}_{group}.png'.format(st = st,
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
612
613
614
                                                                                                  an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
615
                    plt.close()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
                    
                    
                        
                if label == 'author':
                    gen_pred_auth = []
                    life_ph_pred_auth = []
                    gen_pred_auth_wrong = []
                    life_ph_pred_auth_wrong = []
                    auth = list(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_author_pred'])
                    sub_wrong = df_dic[st][an]['df'].loc[df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_author_pred'] != df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_author']]                
                    auth_sub_wrong = list(sub_wrong[an+'_'+str(st)+'_SVM_author_pred'])
                    
                    for au in auth:
                        gen_pred_auth.append(author_dic[st][an][au]['gender'])
                        life_ph_pred_auth.append(author_dic[st][an][au]['life_phase'])
                        
                    for au in auth_sub_wrong:
                        gen_pred_auth_wrong.append(author_dic[st][an][au]['gender'])
                        life_ph_pred_auth_wrong.append(author_dic[st][an][au]['life_phase']) 
                        
                        
                    comp = {'accuracy': accuracy_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              life_ph_pred_auth).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              life_ph_pred_auth,
                                                 average='weighted').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              life_ph_pred_auth,
                                                 average='weighted').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                              life_ph_pred_auth,
                                                 average='weighted').round(3)
                           }
                        
                    tmp.append(comp)
                    index.append('author by life_phase')
                    
                    cnf_matrix = confusion_matrix(df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase'],
                                                 life_ph_pred_auth,
                                                 labels=phases)
                    f = plt.figure()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
657
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
658
                    plt.tight_layout()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}.png'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))
                    
                    comp = {'accuracy': accuracy_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth,
                                                 average='weighted').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth,
                                                 average='weighted').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth,
                                                 average='weighted').round(3)
                           }
                        
                    tmp.append(comp)
                    index.append('author by gender')
                        
                    cnf_matrix = confusion_matrix(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                                 gen_pred_auth,
                                                 labels=['female', 'male'])
                    f = plt.figure()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
683
                    plot_confusion_matrix(cnf_matrix, classes=['female', 'male'],title=None)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
684
                    plt.tight_layout()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
685
686
687
688
689
690
691
692
693
694
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}.png'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='gender'))
                    
                    ###make author cmap showing whether the author missclassified
                    ##were confused with authors of similar gender or life_phase
                    cnf_matrix = confusion_matrix(sub_wrong[an+'_'+str(st)+'_life_phase'],
                                                 life_ph_pred_auth_wrong,
                                                 labels=phases)
                    f = plt.figure()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
695
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
696
                    plt.tight_layout()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
697
698
699
700
701
702
703
704
705
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}_false.png'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))                
                    
                    
                    cnf_matrix = confusion_matrix(sub_wrong[an+'_'+str(st)+'_SVM_gender'],
                                                 gen_pred_auth_wrong,
                                                 labels=['female', 'male'])
                    f = plt.figure()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
706
                    plot_confusion_matrix(cnf_matrix, classes=['female', 'male'],title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
707
                    plt.tight_layout()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}_false.png'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='gender'))                
                                    
                    
                    
                    
                    
                    
            f= plt.figure(figsize=(10,5))
            tmp_df =pd.DataFrame(tmp, index = index)
            tmp_df.plot(kind='barh', colormap = cmap, ax=f.gca())
            plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) #legend outside box
            plt.ylabel(ylabel='Evaluation Measures for Different Subsets',fontsize ='large', fontweight='roman')
            plt.tight_layout()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
723
            plt.savefig(savedir+'barplots/overall_scores_{}_{}.png'.format(st, an))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
724
725
726
727
728
729
730
731
732
733
734
                


    # Make plots with most predicitve features

    # In[ ]:


    #import matplotlib as mpl
    #mpl.rcParams['font.sans-serif'] = ['Segoe UI Emoji']
    #mpl.rcParams['font.serif'] = ['Segoe UI Emoji']
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
735

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
    #sns.set_style({"font.sans-serif":['Segoe UI Emoji']}) 
    for st in subsets:
        for ana in subana:
            an = ana.split('/')[0]
            vocab = res_dic[st][an]['vocab_inverse']
            for label in labels:
                dic = {}
                ind_pos = []
                ind_neg = []
                if label == 'age':
                    phase_key = []
                    for ph in phases:
                        
                        leng = most_pred[st][an][label][ph]['number']
                        arr = most_pred[st][an][label][ph]['val_array']
                        maxi = most_pred[st][an][label][ph]['max_array']
                        mini = most_pred[st][an][label][ph]['min_array']
                        ##make it so that the values of heat are relatively to the min and max values of the feature
                        dic[ph+'\n({})'.format(leng)] = {el[0]:(arr[el[0]]/maxi[el[0]]).round(3) for el in most_pred[st][an][label][ph]['count_tot_pos'] if (el[1]/leng) >= .95}
                        dic[ph+'\n({})'.format(leng)].update({el[0]:-(abs(arr[el[0]])/abs(mini[el[0]])).round(3) for el in most_pred[st][an][label][ph]['count_tot_neg'] if (el[1]/leng) >= .95})        
                        ind_pos.extend([el[0] for el in most_pred[st][an][label][ph]['count_tot_pos'] if (el[1]/leng) >= .95])
                        ind_neg.extend([el[0] for el in most_pred[st][an][label][ph]['count_tot_neg'] if (el[1]/leng) >= .95]) 
                        phase_key.append(ph+'\n({})'.format(leng))
                    ind_pos = list(np.unique(ind_pos))
                    ind_neg = list(np.unique(ind_neg))
                        
                    tmp = {}
                    for ph in phase_key:
                        tmp_l = []
                        for el in ind_pos+ind_neg:
                            try:
                                tmp_l.append(dic[ph][el])
                            except:
                                tmp_l.append(0)
                        tmp[ph] = tmp_l
                    
                    #print([vocab[el] for el in ind_pos + ind_neg])
                    df = pd.DataFrame(tmp, index = [vocab[el].replace('§', '').encode('unicode-escape') for el in ind_pos + ind_neg])
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/6))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
775
                    ax = sns.heatmap(df, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases.png'.format(st, an, label))
                    
                elif label == 'author':
                    sex_key = []
                    phase_key = []
                    for sex in ['male', 'female']:
                        leng = most_pred[st][an][label][sex]['number']
                        arr = most_pred[st][an][label][sex]['val_array']
                        maxi = most_pred[st][an][label][sex]['max_array']
                        mini = most_pred[st][an][label][sex]['min_array']
                        ##make it so that the values of heat are relatively to the min and max values of the feature
                        dic[sex+'\n({})'.format(leng)] = {el[0]:(arr[el[0]]/maxi[el[0]]).round(3) for el in most_pred[st][an][label][sex]['count_tot_pos'] if (el[1]/leng) >= .95}
                        dic[sex+'\n({})'.format(leng)].update({el[0]:-(abs(arr[el[0]])/abs(mini[el[0]])).round(3) for el in most_pred[st][an][label][sex]['count_tot_neg'] if (el[1]/leng) >= .95})        
                        ind_pos.extend([el[0] for el in most_pred[st][an][label][sex]['count_tot_pos'] if (el[1]/leng) >= .95])
                        ind_neg.extend([el[0] for el in most_pred[st][an][label][sex]['count_tot_neg'] if (el[1]/leng) >= .95]) 
                        sex_key.append(sex+'\n({})'.format(leng))

                    for ph in phases:
                        leng = most_pred[st][an][label][ph]['number']
                        arr = most_pred[st][an][label][ph]['val_array']
                        maxi = most_pred[st][an][label][ph]['max_array']
                        mini = most_pred[st][an][label][ph]['min_array']
                        ##make it so that the values of heat are relatively to the min and max values of the feature
                        dic[ph+'\n({})'.format(leng)] = {el[0]:(arr[el[0]]/maxi[el[0]]).round(3) for el in most_pred[st][an][label][ph]['count_tot_pos'] if (el[1]/leng) >= 0.95}
                        dic[ph+'\n({})'.format(leng)].update({el[0]:-(abs(arr[el[0]])/abs(mini[el[0]])).round(3) for el in most_pred[st][an][label][ph]['count_tot_neg'] if (el[1]/leng) >= .95})        
                        ind_pos.extend([el[0] for el in most_pred[st][an][label][ph]['count_tot_pos'] if (el[1]/leng) >= .95])
                        ind_neg.extend([el[0] for el in most_pred[st][an][label][ph]['count_tot_neg'] if (el[1]/leng) >= .95]) 
                        phase_key.append(ph+'\n({})'.format(leng))
                    ind_pos = list(np.unique(ind_pos))
                    ind_neg = list(np.unique(ind_neg))
                    
                    tmp = {}
                    for ph in phase_key+sex_key:
                        tmp_l = []
                        for el in ind_pos+ind_neg:
                            try:
                                tmp_l.append(dic[ph][el])
                            except:
                                tmp_l.append(0)
                        tmp[ph] = tmp_l
                                          
                        
                    ind = ind_pos+ind_neg
                    #print([vocab[el] for el in ind_pos + ind_neg])
                    df = pd.DataFrame(tmp, index = [vocab[el].replace('§', '').encode('unicode-escape') for el in ind])
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/6))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
822
                    ax = sns.heatmap(df, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases.png'.format(st, an, label))
                    
                    dic = {}
                    ind_pos = []
                    ind_neg = []
                    phase_key = []
                    for ph in phases:
                        for sex in ['female', 'male']:
                            leng = most_pred[st][an][label][ph][sex]['number']
                            arr = most_pred[st][an][label][ph][sex]['val_array']
                            maxi = most_pred[st][an][label][ph][sex]['max_array']
                            mini = most_pred[st][an][label][ph][sex]['min_array']
                            ##make it so that the values of heat are relatively to the min and max values of the feature
                            dic[sex+'_'+ph+'\n({})'.format(leng)] = {el[0]:(arr[el[0]]/maxi[el[0]]).round(3) for el in most_pred[st][an][label][ph][sex]['count_tot_pos'] if (el[1]/leng) >= 0.95}
                            dic[sex+'_'+ph+'\n({})'.format(leng)].update({el[0]:-(abs(arr[el[0]])/abs(mini[el[0]])).round(3) for el in most_pred[st][an][label][ph][sex]['count_tot_neg'] if (el[1]/leng) >= .95})        
                            ind_pos.extend([el[0] for el in most_pred[st][an][label][ph][sex]['count_tot_pos'] if (el[1]/leng) >= .95])
                            ind_neg.extend([el[0] for el in most_pred[st][an][label][ph][sex]['count_tot_neg'] if (el[1]/leng) >= .95])                
                            phase_key.append(sex+'_'+ph+'\n({})'.format(leng))
                    ind_pos = list(np.unique(ind_pos))
                    ind_neg = list(np.unique(ind_neg))
                    
                    tmp = {}
                    for ph in phase_key:
                        tmp_l = []
                        for el in ind_pos+ind_neg:
                            try:
                                tmp_l.append(dic[ph][el])
                            except:
                                tmp_l.append(0)
                        tmp[ph] = tmp_l                                    
                    ind = ind_pos+ind_neg
                    df = pd.DataFrame(tmp, index = [vocab[el].replace('§', '').encode('unicode-escape') for el in ind])
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/6))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
856
                    ax = sns.heatmap(df, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
857
858
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_gender_phases.png'.format(st, an, label))                      
    return 1
859
860
861
862
863
864
865
866
867
868
869
870
871


def main():
                        
    cpus = mp.cpu_count()
    pool = mp.Pool(cpus)
    #fire off workers
    jobs = []
    #create jobs
    print('make job queue...')
    sys.stdout.flush()
    print('enter cycle...')
    for subsets in subsets_l:
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
872
873
874
        for subana in subana_l:
            job = pool.apply_async(plotter,([subsets], [subana], phases_l, labels_l))
            jobs.append(job)
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897

    print('collect results from jobs...')
    sys.stdout.flush()
    # collect results from the workers through the pool result queue
    for j in range(0, len(jobs)):
        tmp = jobs.pop(0)
        tmp = tmp.get()
        del tmp

    print('kill all remaining workers...')
    sys.stdout.flush()
    print('closing down the pool')
    sys.stdout.flush()
    pool.close()   
    pool.join()
    print('done and exit :)')
    sys.stdout.flush()




if __name__ == "__main__":
    main()