-
Notifications
You must be signed in to change notification settings - Fork 4
/
data_process.py
182 lines (160 loc) · 6.47 KB
/
data_process.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
# -*- coding: utf-8 -*-
from collections import defaultdict
import numpy as np
import nltk
from nltk.corpus import stopwords
import pickle
'''
tokenize and process words in sentences, including lemmatize, lowercase, remove words with non alpha or dight letter
'''
class Lemmatizer(object):
def __init__(self, basedir=None, output_dir=None):
self.stop = set(stopwords.words('english'))
self.wn_lemmatizer = nltk.stem.WordNetLemmatizer()
self.basedir = basedir
self.output_dir = output_dir
def lemmatize(self):
data_sets = ['train', 'dev', 'test']
for set_name in data_sets:
fin_path = self.basedir + 'WikiQA-{}.tsv'.format(set_name)
fout_path = self.output_dir + 'WikiQA-{}.csv'.format(set_name)
with open(fin_path, 'r', encoding='utf-8') as fin, open(fout_path, 'w', encoding='utf-8') as fout:
fin.readline()
for line in fin:
line_info = line.strip().split('\t')
q_id = line_info[0]
question = line_info[1]
a_id = line_info[4]
answer = line_info[5]
question = ' '.join(self.process_sentence(question))
answer = ' '.join(self.process_sentence(answer))
label = line_info[6]
fout.write('\t'.join([q_id, question, a_id, answer, label]) + '\n')
def process_sentence(self, line):
return list(filter(lambda x: x not in self.stop and x.isalnum(),
map(lambda x: self.wn_lemmatizer.lemmatize(x).lower(), nltk.word_tokenize(line))))
'''
load qa file from file
'''
def load_qa_data(fname, test=False):
data = []
q_dict = {}
with open(fname, 'r', encoding='utf-8') as fin:
# this process for test data is for ranking task
if test:
for line in fin:
line_info = line.strip().split('\t')
q_id = line_info[0]
question = line_info[1].strip().split()
answer = line_info[3].strip().split()
label = int(line_info[4])
if q_id not in q_dict:
q_dict[q_id] = (question, [answer], [label])
else:
q_dict[q_id][1].append(answer)
q_dict[q_id][2].append(label)
for key, value in q_dict.items():
if 1 in value[2]:
data.append(value)
else:
for line in fin:
line_info = line.strip().split('\t')
question = line_info[1].strip().split()
answer = line_info[3].strip().split()
label = int(line_info[4])
data.append((question, answer, label))
return data
class DataHelper(object):
def __init__(self):
self.vocab = None
self.word_index = None
self.idf = None
self.word_embeddings = None
self.train_data = None
self.dev_data = None
self.test_data = None
self.embedding_dim = None
def build(self, embedding_file, train_file, dev_file, test_file=None):
self.train_data = load_qa_data(train_file)
self.dev_data = load_qa_data(dev_file)
self.test_data = load_qa_data(test_file, test=True)
self.build_vocab()
self.load_embeddings(embedding_file=embedding_file)
self.transform()
def build_vocab(self):
idf = defaultdict(float)
n = 0
for question, answer, _ in self.train_data:
n += 2
q_words = set(question)
a_words = set(answer)
for word in q_words:
idf[word] += 1
for word in a_words:
idf[word] += 1
for word in idf:
idf[word] = np.log(n / idf[word])
self.idf = idf
self.vocab = list(idf.keys())
word_index = {}
for i, word in enumerate(self.vocab):
word_index[word] = i
self.word_index = word_index
# load word embeddings from text file
def load_embeddings(self, embedding_file):
word_vecs = {}
with open(embedding_file, encoding='utf-8') as f:
i = 0
for line in f:
line = line.strip().split()
word = line[0]
if word in self.word_index:
i += 1
embedding = [float(item) for item in line[1:]]
word_vecs[word] = np.array(embedding)
print("num words already in word2vec: " + str(i))
self.word_embeddings = word_vecs
self.embedding_dim = len(embedding)
def word2index(self, sentences):
if len(sentences) == 0:
return []
if isinstance(sentences[0], list):
tmp = []
for sentence in sentences:
tmp.append([self.word_index[word] + 1 for word in sentence if word in self.word_index])
return tmp
else:
return [self.word_index[word] + 1 for word in sentences if word in self.word_index]
# convert word list to id list
def transform(self):
# for sentence padding
word_embeddings = np.zeros((len(self.vocab) + 1, self.embedding_dim))
for i, word in enumerate(self.vocab):
if word in self.word_embeddings:
word_embeddings[i] = self.word_embeddings[word]
self.word_embeddings = word_embeddings
train_tmp = []
for question, answer, label in self.train_data:
train_tmp.append((self.word2index(question), self.word2index(answer), label))
self.train_data = np.array(train_tmp)
dev_tmp = []
for question, answer, label in self.dev_data:
dev_tmp.append((self.word2index(question), self.word2index(answer), label))
self.dev_data = np.array(dev_tmp)
test_tmp = []
for question, answers, labels in self.test_data:
test_tmp.append((self.word2index(question), self.word2index(answers), labels))
self.test_data = np.array(test_tmp)
def save_vocab(self, path):
pickle.dump(self.vocab, open(path, "wb"))
def load_vocab(self, path):
self.vocab = pickle.load( open(path, "rb"))
word_index = {}
for i, word in enumerate(self.vocab):
word_index[word] = i
self.word_index = word_index
if __name__ == '__main__':
basedir = './WikiQACorpus/'
output_dir = './data/'
lemmatizer = Lemmatizer(basedir, output_dir)
lemmatizer.lemmatize()