-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathape-codigo-fonte.tex
602 lines (468 loc) · 31.2 KB
/
ape-codigo-fonte.tex
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
%% ------------------------------------------------------------------------- %%
\chapter{Código-fonte dos modelos}
\label{ape:codigo-fonte-dos-modelos}
Neste capítulo apresentamos parte do código-fonte utilizado em nossos experimentos. O código-fonte completo está disponível no seguinte endereço: \url{https://github.com/mrezende/concra}. Neste repositório estão disponíveis o código-fonte para treinamento, avaliação dos modelos, juntamente com os dados originais e os dados pré-preprocessados. Além disso, também estão disponíveis os arquivos word2vec utilizados como entrada em nossos modelos. Utilizamos a linguagem Python, versão 3.6.9 com as bibliotecas \Gls{keras} (versão 2.2.4-tf) e \Gls{tensorflow} (1.15.2). Todos os nossos experimentos foram executados na plataforma \Gls{colab} do Google. Optamos por apresentar neste capítulo apenas os códigos-fontes dos modelos propostos para o presente trabalho. Os códigos-fontes do pré-processamento, treinamento e avaliação estão disponíveis publicamente em nosso repositório. Os dados estão sob a licença \textit{Creative Commons}(\url{https://creativecommons.org/licenses/by/4.0/}) e os códigos estão disponíveis sob a licença \textit{MIT}(\url{https://opensource.org/licenses/MIT}).
\section{Código do modelo de referência \textit{Embedding}}
\label{sec:codigo-modelo-embedding}
O código a seguir é referente ao modelo que utilizamos como base para comparação em nossos experimentos. Este modelo é bem simples, ele recebe como entrada os vetores contínuos das questões e trechos de código-fonte. As características mais relevantes dos vetores são extraídas através da camada \textit{maxpool} (linha 22). Ao final, a similaridade dos vetores é calculada através da função \textit{cosine}.
\begin{mypython-linenumber}{Embedding}
class EmbeddingModel(LanguageModel):
def build(self):
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
# maxpooling
maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), output_shape=lambda x: (x[0], x[2]),
name='max')
maxpool.supports_masking = True
question_pool = maxpool(question_embedding)
answer_pool = maxpool(answer_embedding)
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([question_pool,
answer_pool])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}
\vspace{2cm}
\section{Código do modelo \textit{Unif}}
O código a seguir apresenta a camada da questão do modelo Unif proposto por \citeonline{cambronero-deep-learning-code-search:2019}. O vetor de representação final da questão é resultado da média aritmética dos vetores contínuos de cada palavra que fazem parte da sentença (linha 32).
\begin{mypython-linenumber}{Camada da questão do modelo Unif}
class AverageLayer(Layer):
def __init__(self, **kwargs):
super(AverageLayer, self).__init__(**kwargs)
def build(self, inputs_shape):
inputs_shape = inputs_shape if isinstance(inputs_shape, list) else [inputs_shape]
if len(inputs_shape) != 1:
raise ValueError("AverageLayer expect one input.")
# The first (and required) input is the actual input to the layer
input_shape = inputs_shape[0]
# Expected input shape consists of a triplet: (batch, input_length, input_dim)
if len(input_shape) != 3:
raise ValueError("Input shape for AverageLayer should be of 3 dimension.")
self.input_length = int(input_shape[1])
self.input_dim = int(input_shape[2])
super(AverageLayer, self).build(input_shape)
def call(self, inputs, **kwargs):
inputs = inputs if isinstance(inputs, list) else [inputs]
if len(inputs) != 1:
raise ValueError("AverageLayer expect one input.")
actual_input = inputs[0]
# (batch, input_length, input_dim) = mean => (batch, input_dim)
result = K.mean(actual_input, axis=1)
return result
def compute_output_shape(self, input_shape):
return input_shape[0], input_shape[2] # (batch, input_dim)
\end{mypython-linenumber}
\vspace{2cm}
O código a seguir refere-se a camada de atenção utilizada para obter o vetor de representação final do trecho de código-fonte. A camada de atenção calcula uma média ponderada sobre os vetores contínuos de cada palavra da sentença (linhas 50, 58, 59). Essa camada aprende ao longo do treinamento a ''prestar atenção'' (ponderar) às palavras mais importantes de acordo com o objetivo da tarefa. No nosso caso, o objetivo é aproximar os trechos de código-fonte anotados como corretos às suas questões.
\begin{mypython-linenumber}{Camada de atenção do modelo Unif}
# attention from https://github.com/tech-srl/code2vec
# paper: Code2Vec: Learning Distributed Representations of Code
class AttentionLayer(Layer):
def __init__(self, **kwargs):
super(AttentionLayer, self).__init__(**kwargs)
def build(self, inputs_shape):
inputs_shape = inputs_shape if isinstance(inputs_shape, list) else [inputs_shape]
if len(inputs_shape) < 1 or len(inputs_shape) > 2:
raise ValueError("AttentionLayer expect one or two inputs.")
# The first (and required) input is the actual input to the layer
input_shape = inputs_shape[0]
# Expected input shape consists of a triplet: (batch, input_length, input_dim)
if len(input_shape) != 3:
raise ValueError("Input shape for AttentionLayer should be of 3 dimension.")
self.input_length = int(input_shape[1])
self.input_dim = int(input_shape[2])
attention_param_shape = (self.input_dim, 1)
self.attention_param = self.add_weight(
name='attention_param',
shape=attention_param_shape,
initializer='uniform',
trainable=True,
dtype=tf.float32)
super(AttentionLayer, self).build(input_shape)
def call(self, inputs, **kwargs):
inputs = inputs if isinstance(inputs, list) else [inputs]
if len(inputs) < 1 or len(inputs) > 2:
raise ValueError("AttentionLayer expect one or two inputs.")
actual_input = inputs[0]
mask = inputs[1] if len(inputs) > 1 else None
if mask is not None and not (((len(mask.shape) == 3 and mask.shape[2] == 1) or len(mask.shape) == 2)
and mask.shape[1] == self.input_length):
raise ValueError('mask should be of shape (batch, input_length)'
'or (batch, input_length, 1) '
'when calling an AttentionLayer.')
assert actual_input.shape[-1] == self.attention_param.shape[0]
# (batch, input_length, input_dim) * (input_dim, 1) ==> (batch, input_length, 1)
attention_weights = K.dot(actual_input, self.attention_param)
if mask is not None:
if len(mask.shape) == 2:
mask = K.expand_dims(mask, axis=2) # (batch, input_length, 1)
mask = K.log(mask)
attention_weights += mask
attention_weights = K.softmax(attention_weights, axis=1) # (batch, input_length, 1)
result = K.sum(actual_input * attention_weights, axis=1) # (batch, input_length) [multiplication uses broadcast]
return result
def compute_output_shape(self, input_shape):
return input_shape[0], input_shape[2] # (batch, input_dim)
\end{mypython-linenumber}
\vspace{2cm}
O código a seguir refere-se ao modelo Unif. Os parâmetros de entrada são os vetores contínuos das questões e trechos de código-fonte. A similaridade entre os vetores é calculada através da função \textit{cosine}. O vetor de representação final da questão é resultado da média aritmética dos vetores de cada palavra da sentença (linha 17). Os vetores de representações finais dos trechos de código-fonte são obtidos através da camada de atenção (linha 27).
\begin{mypython-linenumber}{Unif}
class UnifModel(LanguageModel):
def build(self):
print(tf.__version__)
print(tf.keras.__version__)
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
f_average_layer = AverageLayer(name='average')
e_q = f_average_layer([question_embedding])
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
f_attention_layer = AttentionLayer(name='attention')
e_c = f_attention_layer([answer_embedding])
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([e_q,
e_c])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}
\vspace{2cm}
\section{Redes convolucionais}
Os códigos apresentados a seguir referem-se a rede convolucional proposta no Capítulo~\ref{cap:abordagem}. Um ponto importante com relação a eles, é uma adaptação necessária que fizemos para comportar o experimento que avalia os diferentes tamanhos de janela do filtro convolucional. Em todos os códigos acrescentamos o seguinte trecho para permitir a combinação de filtros convolucionais com diferentes tamanhos de janela:
\begin{mypython-linenumber}{Trecho para permitir filtros convolucionais com diferentes tamanhos de janela}
if len(kernel_size) > 1:
q_cnns = [Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'question_conv1d_{k}') for k in kernel_size]
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = concatenate([cnn(question_embedding) for cnn in q_cnns])
...
else:
k = kernel_size[0]
q_cnn = Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'question_conv1d_{k}')
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = q_cnn(question_embedding)
\end{mypython-linenumber}
\vspace{2cm}
Na primeira condição na linha 1, verificamos se o vetor \emph{kernel\_size}, que indica o tamanho das janelas dos filtros convolucionais, possui mais de 1 elemento. Caso ele possua, criamos os filtros convolucionais para cada tamanho de janela (linha 2) e concatenamos ao final (linha 8). Caso o vetor \emph{kernel\_size} possua apenas 1 elemento, não há necessidade de concatenar os filtros e apenas aplicamos a operação de convolução nos vetores contínuos (linhas 12, 14, 20).
\subsection{Rede convolucional com parâmetros independentes entre as camadas de questão e trecho de código-fonte}
\label{sec:rede-convolucional-parametros-indepdentes-codigo-fonte-sem-normalizacao}
O código a seguir apresenta a rede convolucional no qual os parâmetros de aprendizagem são independentes entre as camadas da questão e do trecho de código-fonte. Nas linhas 31 e 39 e nas linhas 47 e 55, criamos uma camada Conv1D para a questão e outra para o trecho de código-fonte. Com isto, não compartilhamos a mesma camada entre eles e, como consequência, os parâmetros também não são compartilhados.
\begin{mypython-linenumber}{Rede convolucional com parâmetros independentes}
class ConvolutionModel(LanguageModel):
def build(self):
assert self.config.question_len() == self.config.answer_len()
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
# cnn
filters = self.config.filters()
kernel_size = self.kernel_size
question_cnn = None
answer_cnn = None
if len(kernel_size) > 1:
q_cnns = [Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'question_conv1d_{k}') for k in kernel_size]
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = concatenate([cnn(question_embedding) for cnn in q_cnns])
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
a_cnns = [Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'answer_conv1d_{k}') for k in kernel_size]
answer_cnn = concatenate([cnn(answer_embedding) for cnn in a_cnns])
else:
k = kernel_size[0]
q_cnn = Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'question_conv1d_{k}')
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = q_cnn(question_embedding)
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
a_cnn = Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'answer_conv1d_{k}')
answer_cnn = a_cnn(answer_embedding)
# maxpooling
maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), output_shape=lambda x: (x[0], x[2]),
name='max')
maxpool.supports_masking = True
# enc = Dense(100, activation='tanh')
# question_pool = enc(maxpool(question_cnn))
# answer_pool = enc(maxpool(answer_cnn))
question_pool = maxpool(question_cnn)
answer_pool = maxpool(answer_cnn)
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([question_pool,
answer_pool])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}
\vspace{2cm}
\subsection{Rede convolucional com parâmetros compartilhados}
O código a seguir exibe o modelo de rede convolucional onde os parâmetros são compartilhados durante a aprendizagem das representações das questões e dos trechos de código-fonte. Diferente da Seção~\ref{sec:rede-convolucional-parametros-indepdentes-codigo-fonte-sem-normalizacao}, nas linhas 31 e 43, instanciamos apenas 1 camada do Conv1D e ela recebe como entrada os vetores contínuos das questões e trechos de código-fonte (linhas 37,40 e 49, 52). Conforme a documentação da biblioteca \Gls{keras} (\url{https://keras.io/getting-started/functional-api-guide/}), este procedimento permite criar uma camada compartilhada, onde os parâmetros de aprendizagem são compartilhados.
\begin{mypython-linenumber}{Rede convolucional com parâmetros compartilhados}
class SharedConvolutionModel(LanguageModel):
def build(self):
assert self.config.question_len() == self.config.answer_len()
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
# cnn
filters = self.config.filters()
kernel_size = self.kernel_size
question_cnn = None
answer_cnn = None
if len(kernel_size) > 1:
cnns = [Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'shared_conv1d_{k}') for k in kernel_size]
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = concatenate([cnn(question_embedding) for cnn in cnns])
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
answer_cnn = concatenate([cnn(answer_embedding) for cnn in cnns])
else:
k = kernel_size[0]
cnn = Conv1D(kernel_size=k,
filters=filters,
activation='relu',
padding='same',
name=f'shared_conv1d_{k}')
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_cnn = cnn(question_embedding)
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
answer_cnn = cnn(answer_embedding)
# maxpooling
maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), output_shape=lambda x: (x[0], x[2]),
name='max')
maxpool.supports_masking = True
# enc = Dense(100, activation='tanh')
# question_pool = enc(maxpool(question_cnn))
# answer_pool = enc(maxpool(answer_cnn))
question_pool = maxpool(question_cnn)
answer_pool = maxpool(answer_cnn)
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([question_pool,
answer_pool])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}
\vspace{2cm}
\subsection{Normalização em lote}
Durante os experimentos, verificamos que os modelos apresentavam sinais de \textit{overfitting}, onde havia um decréscimo rápido do erro na amostra de treinamento em comparação com o erro na amostra de validação (ver Seção~\ref{sec:regularizacao-normalizacao-lote}). Para mitigar este problema, criamos modelos que utilizam a normalização em lote. Durante a criação dos modelos, seguimos a recomendação dos próprios autores \citeonline{sergey-batch-normalization-2015} e adicionamos a normalização em lote antes da função de ativação.
\subsubsection{Rede convolucional com parâmetros independentes entre as camadas}
No código a seguir, acrescentamos a normalização em lote nas linhas 39, 51, 64 e 76.
\begin{mypython-linenumber}{Rede convolucional com parâmetros independentes}
class ConvolutionModelWithBatchNormalization(LanguageModel):
def build(self):
assert self.config.question_len() == self.config.answer_len()
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
# cnn
filters = self.config.filters()
kernel_size = self.kernel_size
question_cnn = None
answer_cnn = None
if len(kernel_size) > 1:
q_cnns = [Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'question_conv1d_with_bn_{k}') for k in kernel_size]
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_outputs_cnn = [cnn(question_embedding) for cnn in q_cnns]
bn_question_outputs_cnn = [BatchNormalization()(output) for output in question_outputs_cnn]
activation_question_outputs_cnn = [Activation('relu')(output) for output in bn_question_outputs_cnn]
question_cnn = concatenate([activation_output for activation_output in activation_question_outputs_cnn])
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
a_cnns = [Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'answer_conv1d_with_bn_{k}') for k in kernel_size]
answer_outputs_cnn = [cnn(answer_embedding) for cnn in a_cnns]
bn_answer_outputs_cnn = [BatchNormalization()(output) for output in answer_outputs_cnn]
activation_answer_outputs_cnn = [Activation('relu')(output) for output in bn_answer_outputs_cnn]
answer_cnn = concatenate([activation_output for activation_output in activation_answer_outputs_cnn])
else:
k = kernel_size[0]
q_cnn = Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'question_conv1d_with_bn_{k}')
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_output_cnn = q_cnn(question_embedding)
bn_question_output_cnn = BatchNormalization()(question_output_cnn)
activation_question_output_cnn = Activation('relu')(bn_question_output_cnn)
question_cnn = activation_question_output_cnn
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
a_cnn = Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'answer_conv1d_with_bn_{k}')
answer_output_cnn = a_cnn(answer_embedding)
bn_answer_output_cnn = BatchNormalization()(answer_output_cnn)
activation_answer_output_cnn = Activation('relu')(bn_answer_output_cnn)
answer_cnn = activation_answer_output_cnn
# maxpooling
maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), output_shape=lambda x: (x[0], x[2]),
name='max')
maxpool.supports_masking = True
# enc = Dense(100, activation='tanh')
# question_pool = enc(maxpool(question_cnn))
# answer_pool = enc(maxpool(answer_cnn))
question_pool = maxpool(question_cnn)
answer_pool = maxpool(answer_cnn)
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([question_pool,
answer_pool])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}
\vspace{2cm}
\subsubsection{Rede convolucional com parâmetros compartilhados}
A normalização em lote foi acrescentada no código a seguir nas linhas 37, 44, 57 e 64.
\begin{mypython-linenumber}{Rede convolucional com parâmetros compartilhados e normalização em lote}
class SharedConvolutionModelWithBatchNormalization(LanguageModel):
def build(self):
assert self.config.question_len() == self.config.answer_len()
question = Input(shape=(self.question_len,), dtype='int32', name='question')
answer = Input(shape=(self.answer_len,), dtype='int32', name='answer')
# add embedding layers
question_weights = np.load(self.config.initial_question_weights())
q_embedding = Embedding(input_dim=question_weights.shape[0],
output_dim=question_weights.shape[1],
weights=[question_weights],
name='question_embedding')
question_embedding = q_embedding(question)
answer_weights = np.load(self.config.initial_answer_weights())
a_embedding = Embedding(input_dim=answer_weights.shape[0],
output_dim=answer_weights.shape[1],
weights=[answer_weights],
name='answer_embedding')
answer_embedding = a_embedding(answer)
# cnn
filters = self.config.filters()
kernel_size = self.kernel_size
question_cnn = None
answer_cnn = None
if len(kernel_size) > 1:
cnns = [Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'shared_conv1d_with_bn_{k}') for k in kernel_size]
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_outputs_cnn = [cnn(question_embedding) for cnn in cnns]
bn_question_outputs_cnn = [BatchNormalization()(output) for output in question_outputs_cnn]
activation_question_outputs_cnn = [Activation('relu')(output) for output in bn_question_outputs_cnn]
question_cnn = concatenate([activation_output for activation_output in activation_question_outputs_cnn])
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
answer_outputs_cnn = [cnn(answer_embedding) for cnn in cnns]
bn_answer_outputs_cnn = [BatchNormalization()(output) for output in answer_outputs_cnn]
activation_answer_outputs_cnn = [Activation('relu')(output) for output in bn_answer_outputs_cnn]
answer_cnn = concatenate([activation_output for activation_output in activation_answer_outputs_cnn])
else:
k = kernel_size[0]
cnn = Conv1D(kernel_size=k,
filters=filters,
padding='same',
name=f'shared_conv1d_with_bn_{k}')
# question_cnn = merge([cnn(question_embedding) for cnn in cnns], mode='concat')
question_output_cnn = cnn(question_embedding)
bn_question_output_cnn = BatchNormalization()(question_output_cnn)
activation_question_output_cnn = Activation('relu')(bn_question_output_cnn)
question_cnn = activation_question_output_cnn
# answer_cnn = merge([cnn(answer_embedding) for cnn in cnns], mode='concat')
answer_output_cnn = cnn(answer_embedding)
bn_answer_output_cnn = BatchNormalization()(answer_output_cnn)
activation_answer_output_cnn = Activation('relu')(bn_answer_output_cnn)
answer_cnn = activation_answer_output_cnn
# maxpooling
maxpool = Lambda(lambda x: K.max(x, axis=1, keepdims=False), output_shape=lambda x: (x[0], x[2]),
name='max')
maxpool.supports_masking = True
# enc = Dense(100, activation='tanh')
# question_pool = enc(maxpool(question_cnn))
# answer_pool = enc(maxpool(answer_cnn))
question_pool = maxpool(question_cnn)
answer_pool = maxpool(answer_cnn)
cos_similarity = Lambda(lambda x: cosine_similarity(x[0], x[1], axis=1)
, output_shape=lambda _: (None, 1), name='similarity')([question_pool,
answer_pool])
return Model(inputs=[question, answer], outputs=cos_similarity,
name='qa_model')
\end{mypython-linenumber}