Analysis_final_mult.py 59.7 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
import math
25
26
27
28
29
30

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
31
32
import matplotlib
matplotlib.use('agg')
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
33
34
35
36
import matplotlib.colors as cl
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns # data visualization library  
37
38
39
# 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
40
savedir = '/draco/ptmp/mschuber/PAN/Data/results/'
41
42
43
#path = '../Data/pan19-celebrity-profiling-training-dataset-2019-01-31/stratified_subsample/'

subana_l = ['org/', 'min_tweets_1000/', 'complete_balance/']
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
44
#subana_l = ['org/']
45
46

subsets_l = [200, 500, 1000, 2000]
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
47
#subsets_l = [200]
48
49
50
51
52
53
54
55
56
57
58
59
60
61

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
62
63
64
65
66

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

cmap = cl.LinearSegmentedColormap.from_list("", ["skyblue","cadetblue","darkblue", "steelblue"]) #define colors
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
# 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
93
def plot_confusion_matrix(cm, classes,normalize=True,title='Confusion matrix',cmap=plt.cm.Blues, ax = None):
94
95
96
97
98
99
100
101
   """
   This function prints and plots the confusion matrix.
   Normalization can be applied by setting `normalize=True`.
   """
   if not ax:
       ax = plt.gca()
       
       
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
102
   
103
104
105
106
107
108
   if normalize:
       cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
       print("Normalized confusion matrix")
   else:
       print('Confusion matrix, without normalization')
   #print(cm)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
109
   cm_old = cm
110
111
112


   im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
113
   #plt.title(title)
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
   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'
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
134
   
135
   thresh = cm.max() / 1.3
136
137
138
139
140
141
142

   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")
       
143

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
144
       
145
146
147


    # Start with analysis of precision and recall as well as heatmaps/confusion matrices:
148
149

def plotter(subsets, subana, phases, labels):
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
    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
560

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584


    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':
585
586
                    tmp_sub = []
                    ind_sub = []
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
587
588
589
590
591
592
593
594
595
596
597
598
599
                    
                    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)
                           }
600
601
602
603
                    for ph in phases:
                        df = df_dic[st][an]['df']
                        comp_sub = {'accuracy': accuracy_score(df.loc[df[an+'_'+str(st)+'_life_phase'] == ph][an+'_'+str(st)+'_life_phase'],
                                                  df.loc[df[an+'_'+str(st)+'_life_phase'] == ph][an+'_'+str(st)+'_life_phase_pred']).round(3),
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
604
                            'precision': precision_score(df[an+'_'+str(st)+'_life_phase'],
605
606
607
608
609
610
611
612
613
614
615
616
617
618
                                                  df[an+'_'+str(st)+'_life_phase_pred'], labels = [ph],
                                                     average='weighted').round(3),
                            'recall': recall_score(df[an+'_'+str(st)+'_life_phase'],
                                                  df[an+'_'+str(st)+'_life_phase_pred'],labels = [ph],
                                                     average='weighted').round(3),
                            'f1-score': f1_score(df[an+'_'+str(st)+'_life_phase'],
                                                  df[an+'_'+str(st)+'_life_phase_pred'],labels = [ph],
                                                     average='weighted').round(3)}

                        tmp_sub.append(comp_sub)
                        ind_sub.append('age phase {}'.format(ph))    



Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
619
                    f= plt.figure(figsize=(5,10))
620
                    tmp_df =pd.DataFrame(tmp_sub, index = ind_sub)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
621
622
623
                    tmp_df.plot(kind='bar', colormap = cmap, ax=f.gca())
                    plt.legend(loc='upper right') #legend outside box
                    plt.xlabel(xlabel='Evaluation Measures for Different Groups',fontsize ='large', fontweight='roman')
624
                    ax = plt.gca()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
625
626
627
                    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
                    plt.grid(True, axis ='y')
                    plt.ylim((0,0.6))
628
629
630
631
                    plt.tight_layout()
                    plt.savefig(savedir+'barplots/age_scores_{}_{}.pdf'.format(st, an))
                    plt.savefig(savedir+'barplots/age_scores_{}_{}.png'.format(st, an))                                          

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
632
633
634
635
636
637
638
639
640
                    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
641
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
642
643
                    plt.tight_layout()
                    #plt.show()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
644
                    #f.savefig('../Data/results/heatmaps/test.png')
645
646
647
648
                    f.savefig(savedir+ 'heatmaps/cm_{st}_{an}_{label}_{group}.pdf'.format(st = st,
                                                                                                  an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
649
                    f.savefig(savedir+ 'heatmaps/cm_{st}_{an}_{label}_{group}.png'.format(st = st,
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
650
651
652
                                                                                                  an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
653
                    
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
654
655
656
657
                    
                    
                        
                if label == 'author':
658
659
660
661
                    tmp_sub = []
                    ind_sub = []


Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
662
663
664
665
666
667
668
669
670
671
672
                    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'])
673

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
674
675
                    df_dic[st][an]['df'][an+'_'+str(st)+'_gender_pred_auth'] = gen_pred_auth
                    df_dic[st][an]['df'][an+'_'+str(st)+'_life_phase_pred_auth'] = life_ph_pred_auth
676

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
                        
                    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)
                           }
695
696
697
698
                    for ph in phases:
                        df = df_dic[st][an]['df']
                        comp_sub = {'accuracy': accuracy_score(df.loc[df[an+'_'+str(st)+'_life_phase'] == ph][an+'_'+str(st)+'_life_phase'],
                                                  df.loc[df[an+'_'+str(st)+'_life_phase'] == ph][an+'_'+str(st)+'_life_phase_pred_auth']).round(3),
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
699
                            'precision': precision_score(df[an+'_'+str(st)+'_life_phase'],
700
701
702
703
704
705
706
707
708
709
                                                  df[an+'_'+str(st)+'_life_phase_pred_auth'], labels = [ph],
                                                     average='weighted').round(3),
                            'recall': recall_score(df[an+'_'+str(st)+'_life_phase'],
                                                  df[an+'_'+str(st)+'_life_phase_pred_auth'],labels = [ph],
                                                     average='weighted').round(3),
                            'f1-score': f1_score(df[an+'_'+str(st)+'_life_phase'],
                                                  df[an+'_'+str(st)+'_life_phase_pred_auth'],labels = [ph],
                                                     average='weighted').round(3)}

                        tmp_sub.append(comp_sub)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
710
711
712
                        ind_sub.append('age phase {}'.format(ph))


713
714
715



Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
716
                    f= plt.figure(figsize=(5, 10))
717
                    tmp_df =pd.DataFrame(tmp_sub, index = ind_sub)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
718
719
720
                    tmp_df.plot(kind='bar', colormap = cmap, ax=f.gca())
                    plt.legend(loc='upper right')
                    plt.xlabel(xlabel='Evaluation Measures for Different Groups',fontsize ='large', fontweight='roman')
721
                    ax = plt.gca()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
722
723
724
                    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
                    plt.grid(True, axis ='y')
                    plt.ylim((0,0.6))
725
726
727
728
                    plt.tight_layout()
                    plt.savefig(savedir+'barplots/author_scores_{}_{}.pdf'.format(st, an))
                    plt.savefig(savedir+'barplots/author_scores_{}_{}.png'.format(st, an)) 

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
729
730
731
732
733
734
                    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)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
735

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
736
                    f = plt.figure()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
737
                    ax = f.subplots()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
738
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
739
                    plt.show()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
740
                    plt.tight_layout()
741
742
743
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}.pdf'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
                    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)
                           }
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

                    gend = [comp]
                    ind2 = ['author by gender']

                    gend_an = {'accuracy': accuracy_score(df_dic[st][an]['df'].loc[df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'] == 'male'][an+'_'+str(st)+'_SVM_gender'],
                                              df_dic[st][an]['df'].loc[df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'] == 'male'][an+'_'+str(st)+'_gender_pred_auth']).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'male',
                                                 average='binary').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'male',
                                                 average='binary').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'male',
                                                 average='binary').round(3)
                           }
                    gend.append(gend_an)
                    ind2.append('author by gender\n male')

                    gend_an = {'accuracy': accuracy_score(df_dic[st][an]['df'].loc[df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'] == 'female'][an+'_'+str(st)+'_SVM_gender'],
                                              df_dic[st][an]['df'].loc[df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'] == 'female'][an+'_'+str(st)+'_gender_pred_auth']).round(3),
                        'precision': precision_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'female',
                                                 average='binary').round(3),
                        'recall': recall_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'female',
                                                 average='binary').round(3),
                        'f1-score': f1_score(df_dic[st][an]['df'][an+'_'+str(st)+'_SVM_gender'],
                                              gen_pred_auth, pos_label = 'female',
                                                 average='binary').round(3)
                           }
                    ind2.append('author by gender\n female')
                    gend.append(gend_an)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
793
794
795
796
797
798
799
                    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
800
                    ax = f.subplots()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
801
                    plot_confusion_matrix(cnf_matrix, classes=['female', 'male'],title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
802
                    plt.tight_layout()
803
804
805
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}.pdf'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='gender'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
806
807
808
809
810
811
812
813
814
815
                    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
816
                    ax = f.subplots()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
817
                    plot_confusion_matrix(cnf_matrix, classes=phases,title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
818
                    plt.tight_layout()
819
820
821
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}_false.pdf'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='life_phase')) 
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
822
823
824
825
826
827
828
829
830
                    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
831
                    ax = f.subplots()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
832
                    plot_confusion_matrix(cnf_matrix, classes=['female', 'male'],title=None, ax=ax)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
833
                    plt.tight_layout()
834
835
836
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}_false.pdf'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='gender'))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
837
838
839
840
841
842
843
844
845
                    f.savefig(savedir+'heatmaps/cm_{st}_{an}_{label}_{group}_false.png'.format(st = st, an=an,
                                                                                                  label=label,
                                                                                                  group='gender'))                
                                    
                    
                    
                    
                    
                    
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
846
            f= plt.figure(figsize=(5,10))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
847
            tmp_df =pd.DataFrame(tmp, index = index)
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
848
849
            tmp_df.plot(kind='bar', colormap = cmap, ax=f.gca())
            #plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) #legend outside box
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
850
            plt.legend(loc='upper left')
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
851
            plt.xlabel(xlabel='Evaluation Measures for Different Subsets',fontsize ='large', fontweight='roman')
852
            ax = plt.gca()
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
853
854
            plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
            plt.grid(True, axis ='y')
855
            plt.ylim((0,.7))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
856
            plt.tight_layout()
857
            plt.savefig(savedir+'barplots/overall_scores_{}_{}.pdf'.format(st, an))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
858
            plt.savefig(savedir+'barplots/overall_scores_{}_{}.png'.format(st, an))
859
860
861
862
863
864


            f= plt.figure(figsize=(10,5))
            tmp_df =pd.DataFrame(gend, index = ind2)
            tmp_df.plot(kind='barh', colormap = cmap, ax=f.gca())
            plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
865
            plt.xlabel(xlabel='Evaluation Measures for Author Scores by Gender',fontsize ='large', fontweight='roman')
866
867
            #ax = plt.gca()
            #plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
868
            plt.grid(True, axis ='y')
869
            plt.ylim((0,.7))
870
871
872
            plt.tight_layout()
            plt.savefig(savedir+'barplots/author_gender_scores_{}_{}.pdf'.format(st, an))
            plt.savefig(savedir+'barplots/author_gender_scores_{}_{}.png'.format(st, an))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
873
874
875
876
877
878
879
880
881
882
883
                


    # 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
884

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
    #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])
922
923
924
925
926
927
928
929
930
931
932
933
934
                    ind = [vocab[el].replace('§', '') for el in ind_pos+ind_neg]
                    ind = [re.sub(r'\s', 'BLANK', el) for el in ind]
                    ind = [el.replace('$', r'\$') for el in ind]
                    ind = [el.replace('\n', 'BREAK') for el in ind]
                    #print(ind)
                    for i in range(0, len(ind)):
                        try:
                            ind[i].encode('ascii')
                        except:
                            ind[i] = ind[i].encode('unicode-escape')
                    
                        
                    df = pd.DataFrame(tmp , index = ind)
935
936
937
938
                    ##select only informative features (i.e. those which are 0 across less than all columns of type)
                    mask = (df == 0.0).T
                    ls = []
                    for col in mask.columns:
939
                        if collections.Counter(mask[col])[True] < 1:
940
941
                            ls.append(col)
                    df.drop(ls, inplace = True)
942
943
944
945
946
947
948
949
950
951
952
953
954
955


                    ####plot is too long - half it
                    half = math.floor(len(df.index))
                    sub = df[0:half]
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/5))
                    sns.heatmap(sub, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases_1.pdf'.format(st, an, label))
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases_1.png'.format(st, an, label))
                    sub = df[half:]
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/5))
                    sns.heatmap(sub, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases_2.pdf'.format(st, an, label))
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases_2.png'.format(st, an, label))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
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
                    
                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
                                          
996

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
997
                    #print([vocab[el] for el in ind_pos + ind_neg])
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
                    ind = [vocab[el].replace('§', '') for el in ind_pos+ind_neg]
                    ind = [re.sub(r'\s', 'BLANK', el) for el in ind]       
                    ind = [el.replace('$', r'\$') for el in ind]
                    ind = [el.replace('\n', 'BREAK') for el in ind]
                    #print(ind)
                    for i in range(0, len(ind)):
                        try:
                            ind[i].encode('ascii')
                        except:
                            ind[i] = ind[i].encode('unicode-escape')
                    #print([vocab[el] for el in ind_pos + ind_neg])
                    df = pd.DataFrame(tmp, index = ind)
1010
1011
1012
1013
1014

                    ##select only informative features (i.e. those which are 0 across less than all columns of type)
                    mask = (df == 0.0).T
                    ls = []
                    for col in mask.columns:
1015
                        if collections.Counter(mask[col])[True] < 1:
1016
1017
1018
1019
                            ls.append(col)
                    df.drop(ls, inplace = True)   


1020
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/5))
1021
                    sns.heatmap(df, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
1022
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases.pdf'.format(st, an, label))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
1023
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_phases.png'.format(st, an, label))
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
                    
                    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                                    
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
                    #print([vocab[el] for el in ind_pos + ind_neg])
                    ind = [vocab[el].replace('§', '') for el in ind_pos+ind_neg]
                    ind = [re.sub(r'\s', 'BLANK', el) for el in ind]
                    ind = [el.replace('$', r'\$') for el in ind]
                    ind = [el.replace('\n', 'BREAK') for el in ind]
                    #print(ind)
                    for i in range(0, len(ind)):
                        try:
                            ind[i].encode('ascii')
                        except:
                            ind[i] = ind[i].encode('unicode-escape')
                    df = pd.DataFrame(tmp, index = ind)
1065
1066
1067
1068
1069

                    ##select only informative features (i.e. those which are 0 across less than all columns of type)
                    mask = (df == 0.0).T
                    ls = []
                    for col in mask.columns:
1070
                        if collections.Counter(mask[col])[True] < 1:
1071
1072
1073
                            ls.append(col)
                    df.drop(ls, inplace = True)

Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
1074
                    f,ax = plt.subplots(figsize=(18, len(ind_pos+ind_neg)/6))
1075
                    sns.heatmap(df, fmt= '.1f',ax=ax, center = 0, yticklabels = True)
1076
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_gender_phases.pdf'.format(st, an, label)) 
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
1077
                    f.savefig(savedir+'featureplots/features_heat_{}_{}_{}_gender_phases.png'.format(st, an, label))                      
1078
                                               
Marcel Henrik Schubert's avatar
Marcel Henrik Schubert committed
1079
    return 1
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092


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
1093
1094
1095
        for subana in subana_l:
            job = pool.apply_async(plotter,([subsets], [subana], phases_l, labels_l))
            jobs.append(job)
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

    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()