-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembedding.py
153 lines (124 loc) · 6.64 KB
/
embedding.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
import numpy as np
import gensim
import math
import torch
class Create_Embedding:
def __init__(self, file_path=None, embd_file_mimic=None, word2index=None, custom=0,
final_list=None, one_hot_pos=True, one_hot_medical=True, custom_medical=0, upos=False, umed=False,
seed=42, one_hot_word=False, embedding_size=300):
self.use_cuda = torch.cuda.is_available()
self.embd_file_mimic = embd_file_mimic
self.file_path = file_path
self.embedding_size = embedding_size # Dimensionality of Google News' Word2Vec
self.embedding_matrix = None
self.embedding_matrix_pos = None
self.embedding_matrix_medical = None
self.seed = seed
if one_hot_word:
self.embedding_matrix = self.create_one_hot_embed_matrix(word2index[0])
else:
if custom == 1:
self.embedding_matrix = self.create_embed_matrix_google(file_path, word2index[0], final_list[0])
elif custom == 2:
self.embedding_matrix = self.create_embed_matrix_mimic(embd_file_mimic, word2index[0], final_list[0])
elif custom == 3:
self.embedding_matrix = torch.Tensor(len(word2index[0]) + 1, self.embedding_size).uniform_(
-math.sqrt(float(3 / self.embedding_size)), math.sqrt(float(3 / self.embedding_size)))
if upos:
self.embedding_matrix_pos = self.create_pos_embed_matrix(word2index[1], one_hot_pos)
if umed:
self.embedding_matrix_medical = self.create_medical_embed_matrix(word2index[2], final_list[2],
one_hot_medical,
custom_medical)
return
def create_one_hot_embed_matrix(self, word_index):
one_hot_dimension = len(word_index)
one_hot = torch.FloatTensor(one_hot_dimension, one_hot_dimension).zero_()
target = one_hot.fill_diagonal_(1)
embedding_matrix = torch.autograd.Variable(target)
if self.use_cuda: embedding_matrix = embedding_matrix.cuda()
return embedding_matrix
def create_pos_embed_matrix(self, word_index_pos, one_hot_pos):
if one_hot_pos:
if self.embedding_size < len(word_index_pos) + 1:
raise Exception("the embedding size should be higher")
else:
one_hot_dimension = self.embedding_size
one_hot = torch.FloatTensor(one_hot_dimension, one_hot_dimension).zero_()
target = one_hot.fill_diagonal_(1)
embedding_matrix = torch.autograd.Variable(target)
else:
embedding_matrix = torch.Tensor(len(word_index_pos) + 1, self.embedding_size).uniform_(
-math.sqrt(float(3 / self.embedding_size)), math.sqrt(float(3 / self.embedding_size)))
if self.use_cuda: embedding_matrix = embedding_matrix.cuda()
return embedding_matrix
def create_medical_embed_matrix(self, word_index, final_list, one_hot_medical, custom):
if one_hot_medical:
if self.embedding_size < len(word_index) + 1:
raise Exception("the embedding size should be higher")
else:
one_hot_dimension = self.embedding_size
one_hot = torch.FloatTensor(one_hot_dimension, one_hot_dimension).zero_()
target = one_hot.fill_diagonal_(1)
embedding_matrix = torch.autograd.Variable(target)
else:
name = "medical"
if custom == 1:
embedding_matrix = self.create_embed_matrix_google(self.file_path, word_index, final_list,
name)
elif custom == 2:
embedding_matrix = self.create_embed_matrix_mimic(self.embd_file_mimic, word_index, final_list,
name)
elif custom == 3:
embedding_matrix = torch.Tensor(len(word_index) + 1, self.embedding_size).uniform_(
-math.sqrt(float(3 / self.embedding_size)), math.sqrt(float(3 / self.embedding_size)))
return embedding_matrix
def create_embed_matrix_google(self, file_path, word_index, final_list, name="word"):
"""
use a mimic or google embedding in order to get a better representation
:param file_path: of the google embedding
:param word_index: for words not in the dataset (this will not effect)
:param final_list: dataset list
:param pretrained: get a pretrained embeding
:return:
"""
# train model
print("start google embedding")
model = gensim.models.KeyedVectors.load_word2vec_format(file_path, binary=True)
# Prepare Embedding Matrix.
embedding_matrix = np.zeros((len(word_index) + 1, self.embedding_size))
for word, i in word_index.items():
if word not in model.wv.vocab:
if word != "PAD":
embedding_matrix[i] = torch.Tensor(self.embedding_size).uniform_(
-math.sqrt(float(3 / self.embedding_size)), math.sqrt(float(3 / self.embedding_size)))
else:
embedding_matrix[i] = model[word]
del model
embedding_matrix = torch.FloatTensor(embedding_matrix)
if self.use_cuda: embedding_matrix = embedding_matrix.cuda()
return embedding_matrix
def create_embed_matrix_mimic(self, file_path, word_index, final_list, name="word"):
"""
use a mimic or google embedding in order to get a better representation
:param file_path: of mimic embedding
:param word_index: for words not in the dataset (this will not effect)
:param final_list: dataset list
:param pretrained: get a pretrained embeding
:return:
"""
print("start mimic embedding")
model = gensim.models.KeyedVectors.load_word2vec_format(file_path, binary=True)
# Prepare Embedding Matrix.
embedding_matrix = np.zeros((len(word_index) + 1, self.embedding_size))
for word, i in word_index.items():
if word not in model.wv.vocab:
if word != "PAD":
embedding_matrix[i] = torch.Tensor(self.embedding_size).uniform_(
-math.sqrt(float(3 / self.embedding_size)), math.sqrt(float(3 / self.embedding_size)))
else:
embedding_matrix[i] = model[word]
del model
embedding_matrix = torch.FloatTensor(embedding_matrix)
if self.use_cuda: embedding_matrix = embedding_matrix.cuda()
return embedding_matrix