-
Notifications
You must be signed in to change notification settings - Fork 6
/
prepare.py
154 lines (139 loc) · 4.75 KB
/
prepare.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
import json
import numpy as np
import os
from PIL import Image
from keras.layers import Embedding
import keras.preprocessing.text
from autocorrect import spell
import re
'''
Some utility methods to process NLVR.
'''
def correction(word):
if not str(word).isdigit():
return spell(word)
else:
return word
# This is due to problems with keras text_to_word_sequence
def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
if lower: text = text.lower()
if type(text) == unicode:
translate_table = {ord(c): ord(t) for c,t in zip(filters, split*len(filters)) }
else:
translate_table = maketrans(filters, split * len(filters))
text = text.translate(translate_table)
seq = text.split(split)
return [i for i in seq if i]
from keras.preprocessing.text import Tokenizer
keras.preprocessing.text.text_to_word_sequence = text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
tokenizer = Tokenizer()
stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()
def process_sentence(text, objects='False'):
'''
Simple and dirty text preprocessing to remove some mispelled words
and lemmatize
'''
text = text.lower()
old_text = text
text = text.replace('1', 'one').replace('2','two').replace(
'3','three').replace('4','four').replace('5','five').replace('6','six').replace(
'.','').replace('contains', 'contain').replace(
'which','').replace('are there','there are').replace(
'there is', '').replace('ablue', 'a blue').replace(
'corner','edge').replace('wall', 'edge').replace('yelow', 'yellow').replace(
'below','beneath').replace(
'brick','block').replace('leats','least').replace('is touching', 'touching')
text = re.sub(r'colour([\W])', 'color ', text)
text = re.sub(r'colored([\W])', 'color ', text)
text = re.sub(r'coloured([\W])', 'color ', text)
text = text.split(' ')
text = map(correction, [t for t in text if t])
text = [lemmatizer.lemmatize(x) if not x in [u'as',u'wall'] else x for x in text]
text = ' '.join(text)
if 'that' in text:
text = text.replace('that', '')
if 'contain' in text or 'ha ' in text:
text = text.replace('contain', 'with').replace('ha ','with ')
text = re.sub(r'(^|\W)a([\W])', ' one ', text)
text = re.sub(r'(^)ll ', ' ', text)
text = re.sub(r'(^)t ', 'at ', text)
text = ' '.join([t for t in text.split(' ') if t])
text = text.replace('based', 'base')
return text
def load_data(path, objects=False):
'''
Loading NLVR dataset
'''
f = open(path, 'r')
data = []
for l in f:
jn = json.loads(l)
s = process_sentence(jn['sentence'])
idn = jn['identifier']
la = int(jn['label'] == 'true')
if objects:
la = [int(o in s) for o in objects_list]
if sum(la) == 0:
continue
data.append([idn, s, la])
return data
def init_tokenizer(sdata):
texts = [t[1] for t in sdata]
tokenizer.fit_on_texts(texts)
def tokenize_data(sdata, mxlen):
texts = [t[1] for t in sdata]
seqs = tokenizer.texts_to_sequences(texts)
seqs = pad_sequences(seqs, mxlen)
data = {}
for k in range(len(sdata)):
data[sdata[k][0]] = [seqs[k], sdata[k][2]]
return data
def section_image(img):
'''
Separating the image into 3 sub-images
'''
img1 = img[:,:50,:]
img2 = img[:,75:125,:]
img3 = img[:,150:200,:]
return img1, img2, img3
def load_images(path, sdata, section=False, standarize=False):
'''
Load images from NLVR
'''
data = {}
cnt = 0
for lists in os.listdir(path):
p = os.path.join(path, lists)
for f in os.listdir(p):
cnt += 1
im_path = os.path.join(p, f)
im = Image.open(im_path)
im = im.convert('RGB')
im = im.resize((200, 50))
im = np.array(im)
#im = img_to_array(im)
if standarize:
im = tf_image.per_image_standardization(im)
if section:
im = section_image(im)
idf = f[f.find('-') + 1:f.rfind('-')]
if not idf in sdata:
continue
data[f] = [im] + sdata[idf]
ims, ws, labels = [], [], []
for key in data:
ims.append(data[key][0])
ws.append(data[key][1])
labels.append(data[key][2])
data.clear()
if section:
ims = np.array(ims, dtype=np.float32)
ws = np.array(ws, dtype=np.float32)
labels = np.array(labels, dtype=np.float32)
return ims, ws, labels