-
Notifications
You must be signed in to change notification settings - Fork 2
/
predict-word-presence.py
209 lines (160 loc) · 7.1 KB
/
predict-word-presence.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
from time import gmtime, strftime
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import Adam, SGD
import numpy
import imaginet.task as task
import imaginet.defn.audiovis_rhn as audiovis
import sys
import random
import imaginet.vendrov_provider as vdp
import imaginet.data_provider as dp
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
item_count = -1
if len(sys.argv) > 1:
item_count = int(sys.argv[1])
def applyNeuralNetwork(train_x, train_y, test_x, test_y):
#print "input shape", train_x.shape
model = Sequential()
input_size = len(train_x[0])
model.add(Dense(1024, input_dim=input_size, init='orthogonal', activation='tanh'))
model.add(Dense(1, init='orthogonal', activation='sigmoid'))
# Use ADAM optimizer, setting some extra options
optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(loss='binary_crossentropy', optimizer=optimizer)
max_acc = 0
# for j in range(10):
# model.fit(train_x, train_y, nb_epoch=(j+1)*10, batch_size=64, verbose=0)
# trainprd = (numpy.ndarray.flatten(model.predict(train_x, verbose=0))>=0.5).astype('float32')
# prd = (numpy.ndarray.flatten(model.predict(test_x, verbose=0))>=0.5).astype('float32')
# max_acc = max(max_acc, numpy.mean(prd==test_y))
for j in range(10):
model.fit(train_x, train_y, nb_epoch=10, batch_size=64, verbose=0)
prd = (numpy.ndarray.flatten(model.predict(test_x, verbose=0))>=0.5).astype('float32')
acc = numpy.mean(prd==test_y)
max_acc = max(max_acc, acc)
print j*10, acc
return max_acc
def readStopWords():
stop_words = set()
inf = open("nltk-stopwords.txt", 'r')
sw = inf.readline()
while (sw != ""):
stop_words.add(sw.strip().lower())
sw = inf.readline()
inf.close()
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])
return stop_words
def stimuli(features):
x = []
for i in range(len(validate)):
x += [numpy.concatenate((features[i],embeddings_pos[i]),axis=0), numpy.concatenate((features[i],embeddings_neg[i]),axis=0)]
return numpy.array(x, dtype='float32')
def minall(scores):
mmin = 1.0
for x in scores:
mmin = min(mmin, min(scores[x]))
return mmin
def maxall(scores):
mmax = 0.0
for x in scores:
mmax = max(mmax, max(scores[x]))
return mmax
acc = {}
for dataset in ['flickr8k','coco']:
print ">>>>>>>> DATASET: ", dataset
savedir = "../data/%s/"%dataset
print "load the model and the validation dataset..."
if dataset == 'flickr8k':
model = task.load("../models/flickr8k-speech.zip")
prov = dp.getDataProvider('flickr8k', root='..', audio_kind='human.max1K.accel3.ord.mfcc')
else:
model = task.load("../models/coco-speech.zip")
prov = vdp.getDataProvider(dataset='coco', root='..', audio_kind='mfcc')
validate = list(prov.iterSentences(split='val'))
data = [ numpy.asarray(sent['audio'], dtype='float32') for sent in validate ]
val_embeddings = audiovis.encode_sentences(model, data)
val_states = [ datum.mean(axis=0) for datum in audiovis.iter_layer_states(model, data) ]
del data
if item_count > -1:
validate = validate[:min(item_count,len(validate))]
val_embeddings = val_embeddings[:min(item_count,len(val_embeddings))]
val_states = val_states[:min(item_count,len(val_states))]
#split data into training and test
sp = 2*len(val_embeddings)*4/5
print "Train: 1-%d; Test: %d-%d\n"%(sp,sp+1,2*len(val_embeddings))
###predict the presence or absence of a word
# For each sentence, pick a random word as the postive example.
# Pick a positive example of another sentence as the negative example of the current sentence.
print "generate positive and negative examples..."
numpy.random.seed(0)
random.seed(0)
stopwords = readStopWords()
positive = []
for i in range(len(validate)):
positem = random.choice(validate[i]['tokens'])
while (positem.lower() in stopwords):
positem = random.choice(validate[i]['tokens'])
positive += [positem]
negative = []
pmax = len(validate)
for i in range(pmax):
negitem = positive[pmax-i-1]
while (negitem in validate[i]['tokens']):
negitem = random.choice(positive)
negative += [negitem]
#read synthetic representations of word forms from a file
print "loading audio features..."
if dataset == 'flickr8k':
words=numpy.load(savedir+"words-flickr8k.npy")
audiofeatures = numpy.load(savedir+"mfcc-flickr8k.npy")
else:
words=numpy.load(savedir+"words-coco.npy")
audiofeatures = numpy.load(savedir+"mfcc-coco.npy")
lexicon = dict(zip(words, audiofeatures))
mfcc_pos = [lexicon[w] for w in positive]
mfcc_neg = [lexicon[w] for w in negative]
embeddings_pos = audiovis.encode_sentences(model, [ numpy.asarray(x, dtype='float32') for x in mfcc_pos ])
embeddings_neg = audiovis.encode_sentences(model, [ numpy.asarray(x, dtype='float32') for x in mfcc_neg ])
acc[dataset] = []
#Predict the presence of a word in a sentence using a neural network
y = numpy.array([1,0] * len(validate), dtype='float32')
#Average input vectors
x = stimuli([numpy.average(item['audio'],axis=0) for item in validate])
acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))
layers = val_states[0].shape[0]
#Average activation units
for l in range(layers):
x = stimuli([item[l,:] for item in val_states])
acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))
#Sentence embeddings
x = stimuli(val_embeddings)
acc[dataset].append(applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:]))
#Average normalized activation units
#for l in range(layers):
# x = stimuli([item[:,l,:].mean(axis=0) for item in val_states])
# acc['l2avg'+str(l)] = applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:])
#Activation units at the last time step
#for l in range(layers):
# x = stimuli([item[-1][l] for item in val_states])
# acc['last'+str(l)] = applyNeuralNetwork(x[0:sp], y[0:sp], x[sp:], y[sp:])
clen = len(acc['coco'])
flen = len(acc['flickr8k'])
xaxis = [i for i in range(clen)]
plt.axis([-1,clen,minall(acc)-0.05, maxall(acc)+0.05])
plt.text(clen-1.5, acc['coco'][-1]-0.05, 'embeddings',color='blue')
plt.text(flen-1.5, acc['flickr8k'][-1]-0.05, 'embeddings', color='red')
plt.xlabel("Network layers")
plt.ylabel("Accuracy")
plt.plot(xaxis[0:2],acc['coco'][0:2],'b--')
coco, = plt.plot(xaxis[1:clen-1],acc['coco'][1:clen-1],'b-', label="COCO")
plt.plot(xaxis[clen-2:],acc['coco'][clen-2:],'b--')
plt.plot([clen-1], acc['coco'][-1], 'bo')
plt.plot(xaxis[0:2],acc['flickr8k'][0:2],'r--')
flickr, = plt.plot(xaxis[1:flen-1],acc['flickr8k'][1:flen-1],'r-', label="Flickr8k")
plt.plot(xaxis[flen-2:flen],acc['flickr8k'][flen-2:],'r--')
plt.plot([flen-1], acc['flickr8k'][-1], 'ro')
plt.legend([coco,flickr], ["COCO","Flickr8k"], loc=4)
plt.savefig('predword.pdf')