-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_dotproducts_csv.py
448 lines (357 loc) · 22.5 KB
/
generate_dotproducts_csv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
##################################################
## Generates the csv files containig the dot product between compounds' embeddings and 'AML'.
##################################################
## Author: Matheus Vargas Volpon Berto
## Copyright: Copyright 2022, Discovering Latent Knowledge in medical paper on Acute Myeloid Leukemia
## Email: matheusvvb@hotmail.com
##################################################
# IMPORTS:
import os, torch, sys, shutil
from pyspark.sql import functions as F
from pyspark.sql import types as T
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from gensim import models
from gensim.models import Word2Vec, FastText
import numpy as np
from scipy.special import softmax
import pandas as pd
from transformers import AutoTokenizer, AutoModelForMaskedLM
sys.path.append('./pubchem/')
from clean_summaries import ss, get_csv_in_folder, read_csv_table_files, to_csv, get_target_compounds
def clear_hugging_face_cache_folder(dirpath='/home/ac4mvvb/.cache/huggingface/hub/'):
""" Clears the Hugging Face cache folder, to prevent memory error.
Args:
dirpath: the path of the folder.
"""
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
def get_token_embedding(word, embedding_matrix, method='mean'):
"""Access and returns the token embedding from the model's embedding matrix for a given word.
Depending on the method selected, it can returns different composed token embeddings.
Args:
word: token that the user wants to tokenize and access the token embedding;
embedding_matrix: the model's embedding matrix, generated by model.get_input_embeddings();
method: the selected way to compose the token embedding
mean: compute the mean between all the subwords generated by the tokenization of the input;
first: select the token embedding of the first subword generated by the tokenization of the input;
last: select the token embedding of the first subword generated by the tokenization of the input.
Returns:
A torch tensor of 768 dimensions representing the token embedding.
"""
vocab_ids = []
tokenized_word = tokenizer.tokenize(word)
for w in tokenized_word:
vocab_ids.append(tokenizer.vocab[w])
if method == 'mean':
input_ids = torch.tensor(vocab_ids)
word_token_embedding = embedding_matrix(input_ids)
word_token_embedding = word_token_embedding.mean(0)
elif method == 'first':
input_ids = torch.tensor(vocab_ids[0])
word_token_embedding = embedding_matrix(input_ids)
elif method == 'last':
input_ids = torch.tensor(vocab_ids[-1])
word_token_embedding = embedding_matrix(input_ids)
return word_token_embedding
def generate_compound_historical_record(compound):
for method in ['first', 'last', 'mean']:
bert_embeddings_files = sorted([f.path for f in os.scandir(VALIDATION_FOLDER) if f.name.endswith('.pt') and method in f.name])
compound_dict = {
'year': [],
'dot_product_result': [],
'dot_product_result_absolute': [],
'softmax': [],
'normalized_dot_product_absolute': [],
'standartized_dot_product_absolute': [],
'softmax_normalization': [],
'softmax_standartization': [],
}
for be in bert_embeddings_files:
tensor_dict = torch.load(be)
try:
index_compound = tensor_dict['compound'].index(c)
index_AML = tensor_dict['compound'].index('AML')
AML_we = tensor_dict['word_embedding'][index_AML]
compound_we = tensor_dict['word_embedding'][index_compound]
except:
continue
dot_product = torch.dot(compound_we, AML_we).type(torch.DoubleTensor).item()
if dot_product > 0:
dot_product_absolute = dot_product
else:
dot_product_absolute = -1 * dot_product
compound_dict['year'].append(int(be.split('.pt')[0][-4:]))
compound_dict['dot_product_result'].append(dot_product)
compound_dict['dot_product_result_absolute'].append(dot_product_absolute)
print('Dot products computed')
# Softmax:
compound_dict['softmax'] = softmax(compound_dict['dot_product_result_absolute'])
# Normalization:
maximum = np.max(compound_dict['dot_product_result_absolute'])
compound_dict['normalized_dot_product_absolute'] = [x/maximum for x in compound_dict['dot_product_result_absolute']]
compound_dict['softmax_normalization'] = softmax(compound_dict['normalized_dot_product_absolute'])
# Standartization:
#compound_dict['softmax_standartization'] = preprocessing.scale(compound_dict['dot_product_result_absolute'])
mean = np.mean(compound_dict['dot_product_result_absolute'])
standart_deviation = np.std(compound_dict['dot_product_result_absolute'])
compound_dict['standartized_dot_product_absolute'] = [(x - mean)/standart_deviation for x in compound_dict['dot_product_result_absolute']]
compound_dict['softmax_standartization'] = softmax(compound_dict['standartized_dot_product_absolute'])
print("Writing compound's historical record .csv file, method {}".format(method))
pd.DataFrame.from_dict(data=compound_dict).to_csv('./validation/per_compound/bert/{}_{}.csv'.format(compound, method), columns=['year', 'dot_product_result', 'dot_product_result_absolute', 'softmax', 'normalized_dot_product_absolute', 'standartized_dot_product_absolute', 'softmax_normalization', 'softmax_standartization'], index=False)
def get_w2v_output_embedding(word, model, method):
""" Returns the output embedding of a given word from Word2Vec or FastText model.
Args:
word: the token in model's vocabulary that you want the output embedding;
meodel: Word2Vec or FastText model object;
method: how to access the output embedding:
'da': direct access to the token (i.e., model.wv[word]) if it exists in the vocabulary;
'avg': compute the average of all words in vocabulary that contains word as a substring.
"""
if method == 'da':
index_of_word_in_vocab = 0
try:
index_of_word_in_vocab = list(model.wv.vocab).index(word)
except:
words = [x for x in list(model.wv.vocab) if word in x]
if len(words) > 0:
index_of_word_in_vocab = list(model.wv.vocab).index(words[0])
return model.wv.vectors[index_of_word_in_vocab]
elif method == 'avg':
tokens_contaning_the_word = [x for x in list(model.wv.vocab) if word in x]
if len(tokens_contaning_the_word) == 1:
return model.wv.vectors[list(model.wv.vocab).index(tokens_contaning_the_word[0])]
else:
indexes_of_tokens_contaning_the_word = []
for w in tokens_contaning_the_word:
indexes_of_tokens_contaning_the_word.append(list(model.wv.vocab).index(w))
print(len(tokens_contaning_the_word))
print(len(indexes_of_tokens_contaning_the_word))
output_embeddings = []
for idx in indexes_of_tokens_contaning_the_word:
output_embeddings.append(model.wv.vectors[idx])
print(len(output_embeddings))
print(type(output_embeddings[0]))
return np.mean(np.stack([output_embeddings]).reshape((len(output_embeddings), output_embeddings[0].shape[0])), axis=0)
# MAIN PROGRAM:
if __name__ == '__main__':
print('Starting')
# CONSTANTS:
VALIDATION_TYPE = 'ft' # possible values must be: 'bert', 'w2v', or 'ft'
BERT_MODELS_PATH = './bert/distilbert/'
W2V_MODELS_COMB15_PATH = './word2vec/models_yoy_combination15/'
FT_MODELS_COMB16_PATH = '/fastdata/ac4mvvb/fasttext/models_yoy_combination16/'
FIRST_OCCURRENCE_OF_EACH_COMPOUND = {
'arsenictrioxide': 1976,
'azacitidine': 1969,
'cyclophosphamide': 1967,
'cytarabine': 1964,
'daunorubicin': 1965,
'dexamethasone': 1973,
'enasidenib': 2015,
'gemtuzumab-ozogamicin': 1999,
'gilteritinib': 2015,
'glasdegib': 2009,
'idarubicin': 1976,
'ivosidenib': 2017,
'midostaurin': 1990,
'mitoxantrone': 1979,
'pemigatinib': 2020,
'prednisone': 1963,
'rituximab': 1999,
'thioguanine': 1963,
'venetoclax': 2013,
'vincristine': 1963,
'vyxeos': 2009,
}
os.makedirs('./validation/per_compound/', exist_ok=True)
# if the validation is for BERT-based models, some constants must pointer to specific BERT files and the cache folder must be enough memory:
if VALIDATION_TYPE == 'bert':
VALIDATION_FOLDER = './validation/bert/'
tokenizer = AutoTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext")
clear_hugging_face_cache_folder()
os.makedirs('./validation/per_compound/bert/', exist_ok=True)
# if the validation is for Word2Vec models, somen constants must pointer to specific Word2Vec files:
elif VALIDATION_TYPE == 'w2v':
MODELS_COMB15 = sorted([f.path for f in os.scandir(W2V_MODELS_COMB15_PATH) if f.name.endswith('.model')])
os.makedirs('./validation/per_compound/w2v/', exist_ok=True)
dictionary_for_all_compounds = {}
for c in get_target_compounds():
dictionary_for_all_compounds.update({
'{}_comb15'.format(c): {
'year': [],
'dot_product_result': [],
'dot_product_result_absolute': [],
'softmax': [],
'normalized_dot_product_absolute': [],
'standartized_dot_product_absolute': [],
'softmax_normalization': [],
'softmax_standartization': [],
}
}
)
# if the validation is for FastText models, somen constants must pointer to specific FastText files:
elif VALIDATION_TYPE == 'ft':
MODELS_COMB16 = sorted([f.path for f in os.scandir(FT_MODELS_COMB16_PATH) if f.name.endswith('.model')])
os.makedirs('./validation/per_compound/ft/', exist_ok=True)
dictionary_for_all_compounds = {}
for c in get_target_compounds():
dictionary_for_all_compounds.update({
'{}_comb16'.format(c): {
'year': [],
'dot_product_result': [],
'dot_product_result_absolute': [],
'softmax': [],
'normalized_dot_product_absolute': [],
'standartized_dot_product_absolute': [],
'softmax_normalization': [],
'softmax_standartization': [],
}
}
)
# list of years which models were trained (the length of this list is the number of models trained):
years = sorted([int(x) for x in range (1921, 2023)])
########################
# DEBUGGING:
print('VALIDATION_TYPE: ', VALIDATION_TYPE)
print('Years: {} to {}'.format(years[0], years[-1]))
########################
# Step 1: access the token embedding of each compound after it appears for the first time in the corpus and save it into a .pt file
for index_y, y in enumerate(years):
print('\nCurrent year of analysis: {}'.format(y))
if y >= 1963:
print("There are at least one paper published until {} that cotains the word 'AML'".format(y))
compounds_present_in_the_papers = []
for key, value in FIRST_OCCURRENCE_OF_EACH_COMPOUND.items():
if y >= value:
compounds_present_in_the_papers.append(key)
# step (3):
if len(compounds_present_in_the_papers) > 0:
print('There are at least one paper published until {} that contains any of the target compounds'.format(y))
print('The compounds present in the selected papers are:')
print(compounds_present_in_the_papers)
if VALIDATION_TYPE == 'bert':
compounds_token_embeddings_first_subword = {
'compound': [],
'word_embedding': [],
}
compounds_token_embeddings_last_subword = {
'compound': [],
'word_embedding': [],
}
compounds_token_embeddings_mean_subword = {
'compound': [],
'word_embedding': [],
}
compounds_token_embeddings_first_subword['compound'] = compounds_present_in_the_papers
compounds_token_embeddings_last_subword['compound'] = compounds_present_in_the_papers
compounds_token_embeddings_mean_subword['compound'] = compounds_present_in_the_papers
print('Loading BERT-based model')
# cleaning again the cache folder, because it its occupped each time a BERT-based model is loaded from Hugging Face:
clear_hugging_face_cache_folder()
# loading BERT-based model and accessing the embedding matrix:
model = AutoModelForMaskedLM.from_pretrained('matheusvolpon/WE4LKD_AML_distilbert_1921_{}'.format(y))
embedding_matrix = model.get_input_embeddings()
print('Accessing compounds token embeddings')
for c in compounds_present_in_the_papers:
compounds_token_embeddings_first_subword['word_embedding'].append(get_token_embedding(c, embedding_matrix, 'first'))
compounds_token_embeddings_last_subword['word_embedding'].append(get_token_embedding(c, embedding_matrix, 'last'))
compounds_token_embeddings_mean_subword['word_embedding'].append(get_token_embedding(c, embedding_matrix, 'mean'))
print('Acessing AML token embedding')
compounds_token_embeddings_first_subword['compound'].append('AML')
compounds_token_embeddings_first_subword['word_embedding'].append(get_token_embedding('AML', embedding_matrix, 'first'))
compounds_token_embeddings_last_subword['compound'].append('AML')
compounds_token_embeddings_last_subword['word_embedding'].append(get_token_embedding('AML', embedding_matrix, 'last'))
compounds_token_embeddings_mean_subword['compound'].append('AML')
compounds_token_embeddings_mean_subword['word_embedding'].append(get_token_embedding('AML', embedding_matrix, 'mean'))
print('Writing .pt files')
torch.save(compounds_token_embeddings_first_subword, VALIDATION_FOLDER + 'word_embeddings_first_subword_{}.pt'.format(y))
torch.save(compounds_token_embeddings_last_subword, VALIDATION_FOLDER + 'word_embeddings_last_subword_{}.pt'.format(y))
torch.save(compounds_token_embeddings_mean_subword, VALIDATION_FOLDER + 'word_embeddings_mean_subword_{}.pt'.format(y))
for c in get_target_compounds():
print("Generating historical record for: {}".format(c))
generate_compound_historical_record(c)
elif VALIDATION_TYPE == 'w2v':
# loading Word2Vec model from file:
print('Loading Word2Vec model')
model_comb15 = Word2Vec.load([x for x in MODELS_COMB15 if str(y) in x][0])
# accessing the word embedding of AML:
try:
AML_we_comb15 = model_comb15.wv['aml']
print("Acessing the word embedding of 'AML'")
except:
print('AML is not in the vocabulary')
continue
# acessing the output embedding of each of the compounds present in the papers published until year y:
for compound in compounds_present_in_the_papers:
# METHOD 1: Direct Access to the token in the model's vocab
print('Acessing the output embedding of {}'.format(compound))
compound_we_comb15 = get_w2v_output_embedding(compound, model_comb15, method='da')
dot_product_comb15 = np.dot(compound_we_comb15, AML_we_comb15).item()
dictionary_for_all_compounds['{}_comb15'.format(compound)]['year'].append(y)
dictionary_for_all_compounds['{}_comb15'.format(compound)]['dot_product_result'].append(dot_product_comb15)
dictionary_for_all_compounds['{}_comb15'.format(compound)]['dot_product_result_absolute'].append(abs(dot_product_comb15))
elif VALIDATION_TYPE == 'ft':
# loading FastText model from file:
print('Loading FastText model')
model_comb16 = FastText.load([x for x in MODELS_COMB16 if str(y) in x][0])
# accessing the word embedding of AML:
try:
AML_we_comb16 = model_comb16.wv['aml']
print("Acessing the word embedding of 'AML'")
except:
print('AML is not in the vocabulary')
continue
# acessing the output embedding of each of the compounds present in the papers published until year y:
for compound in compounds_present_in_the_papers:
print('Acessing the output embedding of {}'.format(compound))
compound_we_comb16 = get_w2v_output_embedding(compound, model_comb16, method='da')
dot_product_comb16 = np.dot(compound_we_comb16, AML_we_comb16).item()
dictionary_for_all_compounds['{}_comb16'.format(compound)]['year'].append(y)
dictionary_for_all_compounds['{}_comb16'.format(compound)]['dot_product_result'].append(dot_product_comb16)
dictionary_for_all_compounds['{}_comb16'.format(compound)]['dot_product_result_absolute'].append(abs(dot_product_comb16))
else:
print('There are no papers published until {} that contains any of the target compounds'.format(y))
else:
print("There are no papers published until {} that contains the word 'AML', mandatory for the validation process".format(y))
continue
if VALIDATION_TYPE == 'w2v':
print('Generating historical record for each compound')
for c in get_target_compounds():
for comb in ['comb15']:
key = '{}_{}'.format(c, comb)
# Softmax:
dictionary_for_all_compounds[key]['softmax'] = softmax(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
# Normalization:
maximum = np.max(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
dictionary_for_all_compounds[key]['normalized_dot_product_absolute'] = [x/maximum for x in dictionary_for_all_compounds[key]['dot_product_result_absolute']]
dictionary_for_all_compounds[key]['softmax_normalization'] = softmax(dictionary_for_all_compounds[key]['normalized_dot_product_absolute'])
# Standartization:
mean = np.mean(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
standart_deviation = np.std(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
dictionary_for_all_compounds[key]['standartized_dot_product_absolute'] = [(x - mean)/standart_deviation for x in dictionary_for_all_compounds[key]['dot_product_result_absolute']]
dictionary_for_all_compounds[key]['softmax_standartization'] = softmax(dictionary_for_all_compounds[key]['standartized_dot_product_absolute'])
print('Writing file {}.csv'.format(key))
pd.DataFrame.from_dict(data=dictionary_for_all_compounds[key]).to_csv('./validation/per_compound/w2v/{}.csv'.format(key), columns=['year', 'dot_product_result', 'dot_product_result_absolute', 'softmax', 'normalized_dot_product_absolute', 'standartized_dot_product_absolute', 'softmax_normalization', 'softmax_standartization'], index=False)
elif VALIDATION_TYPE == 'ft':
print('Generating historical record for each compound')
for c in get_target_compounds():
key = '{}_comb16'.format(c)
# Softmax:
dictionary_for_all_compounds[key]['softmax'] = softmax(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
# Normalization:
maximum = np.max(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
dictionary_for_all_compounds[key]['normalized_dot_product_absolute'] = [x/maximum for x in dictionary_for_all_compounds[key]['dot_product_result_absolute']]
dictionary_for_all_compounds[key]['softmax_normalization'] = softmax(dictionary_for_all_compounds[key]['normalized_dot_product_absolute'])
# Standartization:
mean = np.mean(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
standart_deviation = np.std(dictionary_for_all_compounds[key]['dot_product_result_absolute'])
dictionary_for_all_compounds[key]['standartized_dot_product_absolute'] = [(x - mean)/standart_deviation for x in dictionary_for_all_compounds[key]['dot_product_result_absolute']]
dictionary_for_all_compounds[key]['softmax_standartization'] = softmax(dictionary_for_all_compounds[key]['standartized_dot_product_absolute'])
print('Writing file {}.csv'.format(key))
pd.DataFrame.from_dict(data=dictionary_for_all_compounds[key]).to_csv('./validation/per_compound/ft/{}.csv'.format(key), columns=['year', 'dot_product_result', 'dot_product_result_absolute', 'softmax', 'normalized_dot_product_absolute', 'standartized_dot_product_absolute', 'softmax_normalization', 'softmax_standartization'], index=False)
print('END!')