-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataExtractor.py
305 lines (270 loc) · 9.74 KB
/
DataExtractor.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
import numpy as np
import re
import itertools
from collections import Counter
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower()
def load_data_and_labels(positive_data_file, negative_data_file):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
positive_examples = list(open(positive_data_file, "r").readlines())
positive_examples = [s.strip() for s in positive_examples]
negative_examples = list(open(negative_data_file, "r").readlines())
negative_examples = [s.strip() for s in negative_examples]
# Split by words
x_text = positive_examples + negative_examples
x_text = [clean_str(sent) for sent in x_text]
# Generate labels
positive_labels = [[0, 1] for _ in positive_examples]
negative_labels = [[1, 0] for _ in negative_examples]
y = np.concatenate([positive_labels, negative_labels], 0)
return [x_text, y]
def load_data_and_labels_new(filepath):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
no_freebase_relations = 51
train_examples = list(open(filepath, "r").readlines())
train_examples = [s.strip() for s in train_examples]
labels = np.zeros([len(train_examples),no_freebase_relations])
x_text = []
for i,l in enumerate(train_examples):
splt = l.split("\t")
pattern = splt[0]
relation_id = int(splt[1])
# pattern = pattern + " " + bigramString(pattern)
# pattern = bigramString(pattern)
# print i
relation = splt[2]
x_text.append(pattern)
label = np.zeros([no_freebase_relations])
label[int(relation_id)] = 1
labels[i,:] = label
# Split by words
return [x_text, labels]
def get_max_sequence_length(filename):
max_sequence_length = 0
f = file(filename, 'r')
lines = f.readlines()
for l in lines:
sequence_length = 0
words = l.strip("\n").split(" ")
for i in enumerate(words):
sequence_length += 1
if (sequence_length > max_sequence_length):
max_sequence_length = sequence_length
return max_sequence_length
from GloveModel import Glove_Model
trainPath = "resources/train_web_freepal"
max_seq = get_max_sequence_length(trainPath)
isGlove = True
if isGlove == True:
g = Glove_Model(max_seq, skip= True)
g.model['#crd#'] = np.array(np.random.random(size=g.DIMENSION))
def get_patternList_stackedEmbedding(line, max_sequence_length):
# inputData = np.zeros((len(lines), self.max_sequence_length*300))
i = 0
# for i, line in enumerate(lines):
words = line.strip("\n").split(" ")
line_emb = np.zeros(shape= [max_sequence_length,300])
for word in words:
if word == "":
continue
elif word == "$ARG1":
continue
elif word == "$ARG2":
continue
else:
try:
word_emb = g.model[word]
if (word_emb != None):
line_emb[i,:] = word_emb
i = i + 1
except:
print 0, word
return None
# if(i > 0):
# inputData[j, :] = line_emb
# j += 1
return line_emb
def load_data_and_labels_glove(filepath):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
no_freebase_relations = 51
train_examples = list(open(filepath, "r").readlines())
train_examples = [s.strip() for s in train_examples]
train_size = len(train_examples)
labels = np.zeros([len(train_examples),no_freebase_relations])
# x_text = []
x_train = np.zeros(shape= [train_size, max_seq* g.DIMENSION])
i =0
for l in enumerate(train_examples):
if i == 257:
print "debug"
splt = l[1].split("\t")
pattern = splt[0]
relation_id = int(splt[1])
# pattern = pattern + " " + bigramString(pattern)
# pattern = bigramString(pattern)
# print i
relation = splt[2]
# x_text.append(pattern)
emb = g.get_patternList_ConcatEmbedding(pattern)
if emb is not None:
x_train[i] = emb
label = np.zeros([no_freebase_relations])
label[int(relation_id)] = 1
labels[i,:] = label
i+=1
# Split by words
return x_train, labels, max_seq
def load_data_and_labels_glove_custom(filepath):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
no_freebase_relations = 51
train_examples = list(open(filepath, "r").readlines())
train_examples = [s.strip() for s in train_examples]
train_size = len(train_examples)
labels = np.zeros([len(train_examples),no_freebase_relations])
# x_text = []
x_train = np.zeros(shape= [train_size, max_seq* g.DIMENSION])
i =0
for l in enumerate(train_examples):
if i == 257:
print "debug"
splt = l[1].split("\t")
pattern = splt[1]
pattern_length = len(pattern.split(" "))
if pattern_length> max_seq:
continue
# relation_id = int(splt[1])
# pattern = pattern + " " + bigramString(pattern)
# pattern = bigramString(pattern)
# print i
# relation = splt[2]
# x_text.append(pattern)
emb = g.get_patternList_ConcatEmbedding(pattern)
if emb is not None:
x_train[i] = emb
label = np.zeros([no_freebase_relations])
# label[int(relation_id)] = 1
labels[i,:] = label
i+=1
# Split by words
return x_train, labels, max_seq
def load_data_and_labels_new_entity_Type(filepath):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
no_freebase_relations = 113
max_entityTypes = 42
train_examples = list(open(filepath, "r").readlines())
train_examples = [s.strip() for s in train_examples]
entityTypeArry = np.zeros([len(train_examples), max_entityTypes])
labels = np.zeros([len(train_examples),no_freebase_relations])
x_text = []
for i,l in enumerate(train_examples):
splt = l.split("\t")
pattern = splt[0]
relation_id = splt[1]
x_text.append(pattern)
label = np.zeros([no_freebase_relations])
label[int(relation_id)] = 1
labels[i,:] = label
type_sequence_ids = splt[2].split(" ")
for j,type_id in enumerate(type_sequence_ids):
# print l
entityTypeArry[i,j] = int(type_id)
# Split by words
return [x_text, labels,entityTypeArry]
def bigramString(strng):
bigram_String = ""
words = strng.split(" ")
for i in range(len(words)-1):
bigram_String = bigram_String + " " + words[i] + "_" + words[i+1]
return bigram_String
def loadTraindata(self, filename):
f = file(filename, 'r')
lines = f.readlines()
fb_id = 0
# self.observation_matrix = np.zeros([self.no_of_relations,self.no_of_ep])
# self.freebase_observation_matrix= np.zeros([self.no_of_freebase,self.no_of_ep])
pattern_id = 0
ep_id = 0
# self.emb_matrix = np.zeros([self.no_of_relations , word_embedding_size])
isFB = False
ep_rel = {}
x_train = []
y_train = []
pattern_count = 0
no_of_relations = 5
for j, l in enumerate(lines):
if l.startswith('REL$/') == True:
# isFB = True
split = l.split("\t")
pattern = split[0]
entity1 = split[1]
entity2 = split[2]
enPair = entity1 + "\t" + entity2
ep_rel[enPair] = pattern
else:
pattern_count += 1
for j, l in enumerate(lines):
if l.startswith('REL$/') == True:
isFB = True
split = l.split("\t")
pattern = split[0]
entity1 = split[1]
entity2 = split[2]
enPair = entity1 + "\t" + entity2
if isFB == False:
x_train.append(pattern)
y_train.append(ep_rel[enPair])
def batch_iter(data, batch_size, num_epochs, shuffle=True):
"""
Generates a batch iterator for a dataset.
"""
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int((len(data)-1)/batch_size) + 1
for epoch in range(num_epochs):
# Shuffle the data at each epoch
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_data = data[shuffle_indices]
else:
shuffled_data = data
for batch_num in range(num_batches_per_epoch):
start_index = batch_num * batch_size
end_index = min((batch_num + 1) * batch_size, data_size)
yield shuffled_data[start_index:end_index]