-
Notifications
You must be signed in to change notification settings - Fork 11
/
vectorizer.py
59 lines (49 loc) · 1.81 KB
/
vectorizer.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
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 23:27:45 2018
@author: mwahdan
"""
import string
class Vectorizer:
def __init__(self, word_embeddings, tokenizer):
self.word_embeddings = word_embeddings
self.tokenizer = tokenizer
def vectorize_sentence(self, sentence, threshold=-1):
tokens = self.tokenizer.tokenize(sentence)
if threshold > 0:
# truncate answers to threshold tokens.
tokens = tokens[:threshold]
vector = []
for token in tokens:
if self.__valid_token(token):
token = self.__normalize(token)
token_vector = self.word_embeddings.get_vector(token)
if token_vector is not None:
vector.append(token_vector)
return vector
def vectorize_sentences(self, sentences, threshold=-1):
return [self.vectorize_sentence(s) for s in sentences]
def vectorize_df(self, df):
a_vectors = [self.vectorize_sentence(sentence) for sentence in df['sentence_A']]
b_vectors = [self.vectorize_sentence(sentence) for sentence in df['sentence_B']]
gold = df['relatedness_score'].tolist()
ids = 0 * [len(gold)]
if 'pair_ID' in df.columns:
ids = df['pair_ID']
return ids, a_vectors, b_vectors, gold
def __valid_token(self, token):
if token in string.punctuation:
return False
return True
def __normalize(self, token):
if token == "'s":
token = 'is' # may be 'has' also
elif token == "'re":
token = 'are'
elif token == "'t":
token = 'not'
elif token == "'m":
token = 'am'
elif token == "'d":
token = 'would' # may be 'had' also
return token