-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessing_word2vec.py
209 lines (172 loc) · 6.01 KB
/
preprocessing_word2vec.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
import re
import math
import pickle
import copy
import tqdm
from loguru import logger
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
WINDOW_SIZE = 5 # WINDOW_SIZE number of words on either side of the input word
VOCABULARY_SIZE = 0
CORPUS_SIZE = 0
VOCABULARY = {}
UNIGRAM_RATIOS = []
BERNOULLI_MAP = [] # Bernoulli Map to help with subsampling
"""
Function to get string from a file
Input: File Name
Output: String
"""
def getText(fileName):
file = open(fileName, "r")
return file.read()
"""
Function to tokenize strings
Input: Text
Output: Tokenized version of string, Corpus Size
"""
def generateTokens(text):
pattern = re.compile(r'[A-Za-z]+[\w^\']*|[\w^\']*[A-Za-z]+[\w^\']*')
return pattern.findall(text.lower())
"""
Function to generate Vocabulary
Input: Tokens
Output: Vocabulary, Vocabulary Size
"""
def generateVocabulary(tokens):
vocabulary = {}
for i, token in tqdm.tqdm(enumerate(set(tokens))):
vocabulary[token] = i
return vocabulary, len(vocabulary)
"""
Function to generate Unigram Ratios
Input: Tokens
Output: Unigram Ratios
"""
def generateUnigramRatios(tokens):
unigram_ratios = torch.zeros(VOCABULARY_SIZE)
for token in tqdm.tqdm(tokens):
unigram_ratios[VOCABULARY[token]] += 1
return unigram_ratios/CORPUS_SIZE
"""
Function to generate Bernoulli Map to help with sub-sampling
Input: Tokens
Output: Bernoulli Map
"""
def generateBernoulliMap(tokens):
bernoulli_map = copy.deepcopy(tokens)
for i in tqdm.tqdm(range(len(tokens))):
for j in range(len(tokens[i])):
ratio = UNIGRAM_RATIOS[VOCABULARY[tokens[i][j]]]
p_keep = (np.sqrt(ratio * 1000) + 1) * (0.001/ratio)
if(ratio <= 0.0026):
bernoulli_map[i][j] = 1
continue
bernoulli_map[i][j] = torch.from_numpy(np.random.binomial(1, p_keep, 1)).item()
return bernoulli_map
"""
Function to generate One Hot Encoded Vector of a word
Input: word
Output: One Hot Encoded Vector
"""
def generateOneHotEncoding(word):
one_hot_encoded_vector = torch.zeros(VOCABULARY_SIZE)
one_hot_encoded_vector[VOCABULARY[word]] = 1
return one_hot_encoded_vector
"""
Function to generate Training Data with Subsampling
Input: text
Output: Sub-Sampled Training Data
"""
def generateTrainingData(tokens):
train_data = []
for i, token in enumerate(tqdm.tqdm(tokens)):
for j, t in enumerate(token):
if(BERNOULLI_MAP[i][j] == 0):
continue
X = token[j]
Y = []
if(j < WINDOW_SIZE):
for k in range(0,j):
if(BERNOULLI_MAP[i][k] == 1):
Y.append(tokens[i][k])
for k in range(j+1, min(j + WINDOW_SIZE + 1,len(token) - 1)):
if(k != j):
if(BERNOULLI_MAP[i][k] == 1):
Y.append(tokens[i][k])
elif(j + WINDOW_SIZE > len(token) - 1):
for k in range(j - WINDOW_SIZE,j):
if(k != j):
if(BERNOULLI_MAP[i][k] == 1):
Y.append(tokens[i][k])
for k in range(j+1, len(token)):
if(BERNOULLI_MAP[i][k] == 1):
Y.append(tokens[i][k])
else:
for k in range(int(j - WINDOW_SIZE), int(j + WINDOW_SIZE + 1)):
if(k != j):
if(BERNOULLI_MAP[i][k] == 1):
Y.append(tokens[i][k])
train_data.append(tuple((X,Y)))
return train_data
text = getText("Data/data_word2vec.txt")
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)
data_file = open("Pickle/data_word2vec.pkl",'wb')
pickle.dump(sentences,data_file)
data_file.close()
data_file = open("Pickle/data_word2vec.pkl",'rb')
data = pickle.load(data_file)
data_file.close()
tokens_vocab = []
tokens_train = []
for sentence in tqdm.tqdm(sentences):
tokens = generateTokens(sentence)
tokens_train.append(tokens)
for token in tokens:
tokens_vocab.append(token)
CORPUS_SIZE += 1
token_vocabulary_file = open("Pickle/token_vocabulary_file.pkl",'wb')
pickle.dump(tokens_vocab,token_vocabulary_file)
token_vocabulary_file.close()
token_train_file = open("Pickle/token_train_file.pkl",'wb')
pickle.dump(tokens_train,token_train_file)
token_train_file.close()
token_vocabulary_file = open("Pickle/token_vocabulary_file.pkl",'rb')
tokens_vocab = pickle.load(token_vocabulary_file)
token_vocabulary_file.close()
token_train_file = open("Pickle/token_train_file.pkl",'rb')
tokens_train = pickle.load(token_train_file)
token_train_file.close()
VOCABULARY, VOCABULARY_SIZE = generateVocabulary(tokens_vocab)
vocabulary_file = open("Pickle/vocabulary_file.pkl",'wb')
pickle.dump(VOCABULARY,vocabulary_file)
vocabulary_file.close()
vocabulary_file = open("Pickle/vocabulary_file.pkl",'rb')
VOCABULARY = pickle.load(vocabulary_file)
vocabulary_file.close()
CORPUS_SIZE = len(tokens_vocab)
VOCABULARY_SIZE = len(VOCABULARY)
UNIGRAM_RATIOS = generateUnigramRatios(tokens_vocab)
unigram_ratios_file = open("Pickle/unigram_ratios_file.pkl",'wb')
pickle.dump(UNIGRAM_RATIOS,unigram_ratios_file)
unigram_ratios_file.close()
unigram_file = open("Pickle/unigram_ratios_file.pkl",'rb')
UNIGRAM_RATIOS = pickle.load(unigram_file)
unigram_file.close()
BERNOULLI_MAP = generateBernoulliMap(tokens_train)
bernoulli_map_file = open("Pickle/bernoulli_map_file.pkl",'wb')
pickle.dump(BERNOULLI_MAP,bernoulli_map_file)
bernoulli_map_file.close()
bernoulli_map_file = open("Pickle/bernoulli_map_file.pkl",'rb')
BERNOULLI_MAP = pickle.load(bernoulli_map_file)
bernoulli_map_file.close()
train_data = generateTrainingData(tokens_train)
train_data_file = open("Pickle/train_data_file.pkl",'wb')
pickle.dump(train_data,train_data_file)
train_data_file.close()
train_data_file = open("Pickle/train_data_file.pkl",'rb')
train_data = pickle.load(train_data_file)
train_data_file.close()
print(len(train_data))