<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/classifying-duplicate-questions-from-quora-with-keras/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://tensorflow.rstudio.com/blog/keras-duplicate-questions-quora.html"> TensorFlow for R</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In this post we will use Keras to classify duplicated questions from Quora. The dataset first appeared in the Kaggle competition <a rel="nofollow" href="https://www.kaggle.com/c/quora-question-pairs" target="_blank">Quora Question Pairs</a> and consists of approximately 400,000 pairs of questions along with a column indicating if the question pair is considered a duplicate.</p>
<p>Our implementation is inspired by the <a rel="nofollow" href="https://dl.acm.org/citation.cfm?id=3016291" target="_blank">Siamese Recurrent Architecture</a>, with modifications to the similarity measure and the embedding layers (the original paper uses pre-trained word vectors). Using this kind of architecture dates back to 2005 with <a rel="nofollow" href="https://dl.acm.org/citation.cfm?id=1068961" target="_blank">Le Cun et al</a> and is useful for verification tasks. The idea is to learn a function that maps input patterns into a target space such that a similarity measure in the target space approximates the “semantic” distance in the input space.</p>
<p>After the competition, Quora also described their approach to this problem in this <a rel="nofollow" href="https://engineering.quora.com/Semantic-Question-Matching-with-Deep-Learning" target="_blank">blog post</a>.</p>
<div>
<h2>Dowloading data</h2>
<p>Data can be downloaded from the Kaggle <a rel="nofollow" href="https://www.kaggle.com/quora/question-pairs-dataset" target="_blank">dataset webpage</a> or from Quora’s <a rel="nofollow" href="https://data.quora.com/First-Quora-Dataset-Release-Question-Pairs" target="_blank">release of the dataset</a>:</p>
<div>
<pre><code><span>library</span>(keras)
quora_data &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/get_file.html" target="_blank">get_file</a></span>(
  <span>&quot;quora_duplicate_questions.tsv&quot;</span>,
  <span>&quot;https://qim.ec.quoracdn.net/quora_duplicate_questions.tsv&quot;</span>
)</code></pre>
</div>
<p>We are using the Keras <code><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/get_file.html" target="_blank">get_file()</a></code> function so that the file download is cached.</p>
</div>
<div>
<h2>Reading and preprocessing</h2>
<p>We will first load data into R and do some preprocessing to make it easier to include in the model. After downloading the data, you can read it using the readr <code><a rel="nofollow" href="http://www.rdocumentation.org/packages/readr/topics/read_delim?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">read_tsv()</a></code> function.</p>
<div>
<pre><code><span>library</span>(readr)
df &lt;-<span> </span><span><a rel="nofollow" href="http://www.rdocumentation.org/packages/readr/topics/read_delim?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">read_tsv</a></span>(quora_data)</code></pre>
</div>
<p>We will create a Keras <code>tokenizer</code> to transform each word into an integer token. We will also specify a hyperparameter of our model: the vocabulary size. For now let’s use the 50,000 most common words (we’ll tune this parameter later). The tokenizer will be fit using all unique questions from the dataset.</p>
<div>
<pre><code>tokenizer &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/text_tokenizer.html" target="_blank">text_tokenizer</a></span>(<span>num_words =</span> <span>50000</span>)
tokenizer <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit_text_tokenizer.html" target="_blank">fit_text_tokenizer</a></span>(<span>unique</span>(<span>c</span>(df<span>$</span>question1, df<span>$</span>question2)))</code></pre>
</div>
<p>Let’s save the tokenizer to disk in order to use it for inference later.</p>
<div>
<pre><code><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/save_text_tokenizer.html" target="_blank">save_text_tokenizer</a></span>(tokenizer, <span>&quot;tokenizer-question-pairs&quot;</span>)</code></pre>
</div>
<p>We will now use the text tokenizer to transform each question into a list of integers.</p>
<div>
<pre><code>question1 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/texts_to_sequences.html" target="_blank">texts_to_sequences</a></span>(tokenizer, df<span>$</span>question1)
question2 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/texts_to_sequences.html" target="_blank">texts_to_sequences</a></span>(tokenizer, df<span>$</span>question2)</code></pre>
</div>
<p>Let’s take a look at the number of words in each question. This will helps us to decide the padding length, another hyperparameter of our model. Padding the sequences normalizes them to the same size so that we can feed them to the Keras model.</p>
<div>
<pre><code><span>library</span>(purrr)
questions_length &lt;-<span> </span><span>c</span>(
  <span><a rel="nofollow" href="http://www.rdocumentation.org/packages/purrr/topics/map?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">map_int</a></span>(question1, length),
  <span><a rel="nofollow" href="http://www.rdocumentation.org/packages/purrr/topics/map?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">map_int</a></span>(question2, length)
)

<span>quantile</span>(questions_length, <span>c</span>(<span>0.8</span>, <span>0.9</span>, <span>0.95</span>, <span>0.99</span>))</code></pre>
</div>
<pre><code>80% 90% 95% 99% 
 14  18  23  31 </code></pre>
<p>We can see that 99% of questions have at most length 31 so we’ll choose a padding length between 15 and 30. Let’s start with 20 (we’ll also tune this parameter later). The default padding value is 0, but we are already using this value for words that don’t appear within the 50,000 most frequent, so we’ll use 50,001 instead.</p>
<div>
<pre><code>question1_padded &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/pad_sequences.html" target="_blank">pad_sequences</a></span>(question1, <span>maxlen =</span> <span>20</span>, <span>value =</span> <span>50000</span> <span>+</span><span> </span><span>1</span>)
question2_padded &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/pad_sequences.html" target="_blank">pad_sequences</a></span>(question2, <span>maxlen =</span> <span>20</span>, <span>value =</span> <span>50000</span> <span>+</span><span> </span><span>1</span>)</code></pre>
</div>
<p>We have now finished the preprocessing steps. We will now run a simple benchmark model before moving on to the Keras model.</p>
</div>
<div>
<h2>Simple benchmark</h2>
<p>Before creating a complicated model let’s take a simple approach. Let’s create two predictors: percentage of words from question1 that appear in the question2 and vice-versa. Then we will use a logistic regression to predict if the questions are duplicate.</p>
<div>
<pre><code>perc_words_question1 &lt;-<span> </span><span><a rel="nofollow" href="http://www.rdocumentation.org/packages/purrr/topics/map2?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">map2_dbl</a></span>(question1, question2, <span>~</span><span>mean</span>(.x <span>%in%</span><span> </span>.y))
perc_words_question2 &lt;-<span> </span><span><a rel="nofollow" href="http://www.rdocumentation.org/packages/purrr/topics/map2?tap_a=5644-dce66f&tap_s=10907-287229" target="_blank">map2_dbl</a></span>(question2, question1, <span>~</span><span>mean</span>(.x <span>%in%</span><span> </span>.y))

df_model &lt;-<span> </span><span>data.frame</span>(
  <span>perc_words_question1 =</span> perc_words_question1,
  <span>perc_words_question2 =</span> perc_words_question2,
  <span>is_duplicate =</span> df<span>$</span>is_duplicate
) <span>%>%</span>
<span> </span><span>na.omit</span>()</code></pre>
</div>
<p>Now that we have our predictors, let’s create the logistic model. We will take a small sample for validation.</p>
<div>
<pre><code>val_sample &lt;-<span> </span><span>sample.int</span>(<span>nrow</span>(df_model), <span>0.1</span><span>*</span><span>nrow</span>(df_model))
logistic_regression &lt;-<span> </span><span>glm</span>(
  is_duplicate <span>~</span><span> </span>perc_words_question1 <span>+</span><span> </span>perc_words_question2, 
  <span>family =</span> <span>&quot;binomial&quot;</span>,
  <span>data =</span> df_model[<span>-</span>val_sample,]
)
<span>summary</span>(logistic_regression)</code></pre>
</div>
<pre><code>Call:
glm(formula = is_duplicate ~ perc_words_question1 + perc_words_question2, 
    family = &quot;binomial&quot;, data = df_model[-val_sample, ])

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-1.5938  -0.9097  -0.6106   1.1452   2.0292  

Coefficients:
                      Estimate Std. Error z value Pr(>|z|)    
(Intercept)          -2.259007   0.009668 -233.66   &lt;2e-16 ***
perc_words_question1  1.517990   0.023038   65.89   &lt;2e-16 ***
perc_words_question2  1.681410   0.022795   73.76   &lt;2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 479158  on 363843  degrees of freedom
Residual deviance: 431627  on 363841  degrees of freedom
  (17 observations deleted due to missingness)
AIC: 431633

Number of Fisher Scoring iterations: 3</code></pre>
<p>Let’s calculate the accuracy on our validation set.</p>
<div>
<pre><code>pred &lt;-<span> </span><span>predict</span>(logistic_regression, df_model[val_sample,], <span>type =</span> <span>&quot;response&quot;</span>)
pred &lt;-<span> </span>pred <span>></span><span> </span><span>mean</span>(df_model<span>$</span>is_duplicate[<span>-</span>val_sample])
accuracy &lt;-<span> </span><span>table</span>(pred, df_model<span>$</span>is_duplicate[val_sample]) <span>%>%</span><span> </span>
<span> </span><span>prop.table</span>() <span>%>%</span><span> </span>
<span> </span><span>diag</span>() <span>%>%</span><span> </span>
<span> </span><span>sum</span>()
accuracy</code></pre>
</div>
<pre><code>[1] 0.6573577</code></pre>
<p>We got an accuracy of 65.7%. Not all that much better than random guessing. Now let’s create our model in Keras.</p>
</div>
<div>
<h2>Model definition</h2>
<p>We will use a Siamese network to predict whether the pairs are duplicated or not. The idea is to create a model that can embed the questions (sequence of words) into a vector. Then we can compare the vectors for each question using a similarity measure and tell if the questions are duplicated or not.</p>
<p>First let’s define the inputs for the model.</p>
<div>
<pre><code>input1 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_input.html" target="_blank">layer_input</a></span>(<span>shape =</span> <span>c</span>(<span>20</span>), <span>name =</span> <span>&quot;input_question1&quot;</span>)
input2 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_input.html" target="_blank">layer_input</a></span>(<span>shape =</span> <span>c</span>(<span>20</span>), <span>name =</span> <span>&quot;input_question2&quot;</span>)</code></pre>
</div>
<p>Then let’s the define the part of the model that will embed the questions in a vector.</p>
<div>
<pre><code>word_embedder &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_embedding.html" target="_blank">layer_embedding</a></span>( 
  <span>input_dim =</span> <span>50000</span> <span>+</span><span> </span><span>2</span>, <span># vocab size + UNK token + padding value</span>
  <span>output_dim =</span> <span>128</span>,      <span># hyperparameter - embedding size</span>
  <span>input_length =</span> <span>20</span>,     <span># padding size,</span>
  <span>embeddings_regularizer =</span> <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/regularizer_l1.html" target="_blank">regularizer_l2</a></span>(<span>0.0001</span>) <span># hyperparameter - regularization </span>
)

seq_embedder &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_lstm.html" target="_blank">layer_lstm</a></span>(
  <span>units =</span> <span>128</span>, <span># hyperparameter -- sequence embedding size</span>
  <span>kernel_regularizer =</span> <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/regularizer_l1.html" target="_blank">regularizer_l2</a></span>(<span>0.0001</span>) <span># hyperparameter - regularization </span>
)</code></pre>
</div>
<p>Now we will define the relationship between the input vectors and the embeddings layers. Note that we use the same layers and weights on both inputs. That’s why this is called a Siamese network. It makes sense, because we don’t want to have different outputs if question1 is switched with question2.</p>
<div>
<pre><code>vector1 &lt;-<span> </span>input1 <span>%>%</span><span> </span><span>word_embedder</span>() <span>%>%</span><span> </span><span>seq_embedder</span>()
vector2 &lt;-<span> </span>input2 <span>%>%</span><span> </span><span>word_embedder</span>() <span>%>%</span><span> </span><span>seq_embedder</span>()</code></pre>
</div>
<p>We then define the similarity measure we want to optimize. We want duplicated questions to have higher values of similarity. In this example we’ll use the cosine similarity, but any similarity measure could be used. Remember that the cosine similarity is the normalized dot product of the vectors, but for training it’s not necessary to normalize the results.</p>
<div>
<pre><code>cosine_similarity &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_dot.html" target="_blank">layer_dot</a></span>(<span>list</span>(vector1, vector2), <span>axes =</span> <span>1</span>)</code></pre>
</div>
<p>Next, we define a final sigmoid layer to output the probability of both questions being duplicated.</p>
<div>
<pre><code>output &lt;-<span> </span>cosine_similarity <span>%>%</span><span> </span>
<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_dense.html" target="_blank">layer_dense</a></span>(<span>units =</span> <span>1</span>, <span>activation =</span> <span>&quot;sigmoid&quot;</span>)</code></pre>
</div>
<p>Now that let’s define the Keras model in terms of it’s inputs and outputs and compile it. In the compilation phase we define our loss function and optimizer. Like in the Kaggle challenge, we will minimize the logloss (equivalent to minimizing the binary crossentropy). We will use the Adam optimizer.</p>
<div>
<pre><code>model &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/keras_model.html" target="_blank">keras_model</a></span>(<span>list</span>(input1, input2), output)
model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/compile.html" target="_blank">compile</a></span>(
  <span>optimizer =</span> <span>&quot;adam&quot;</span>, 
  <span>metrics =</span> <span>list</span>(<span>acc =</span> metric_binary_accuracy), 
  <span>loss =</span> <span>&quot;binary_crossentropy&quot;</span>
)</code></pre>
</div>
<p>We can then take a look at out model with the <code>summary</code> function.</p>
<div>
<pre><code><span>summary</span>(model)</code></pre>
</div>
<pre><code>_______________________________________________________________________________________
Layer (type)                Output Shape       Param #    Connected to                 
=======================================================================================
input_question1 (InputLayer (None, 20)         0                                       
_______________________________________________________________________________________
input_question2 (InputLayer (None, 20)         0                                       
_______________________________________________________________________________________
embedding_1 (Embedding)     (None, 20, 128)    6400256    input_question1[0][0]        
                                                          input_question2[0][0]        
_______________________________________________________________________________________
lstm_1 (LSTM)               (None, 128)        131584     embedding_1[0][0]            
                                                          embedding_1[1][0]            
_______________________________________________________________________________________
dot_1 (Dot)                 (None, 1)          0          lstm_1[0][0]                 
                                                          lstm_1[1][0]                 
_______________________________________________________________________________________
dense_1 (Dense)             (None, 1)          2          dot_1[0][0]                  
=======================================================================================
Total params: 6,531,842
Trainable params: 6,531,842
Non-trainable params: 0
_______________________________________________________________________________________</code></pre>
</div>
<div>
<h2>Model fitting</h2>
<p>Now we will fit and tune our model. However before proceeding let’s take a sample for validation.</p>
<div>
<pre><code><span>set.seed</span>(<span>1817328</span>)
val_sample &lt;-<span> </span><span>sample.int</span>(<span>nrow</span>(question1_padded), <span>size =</span> <span>0.1</span><span>*</span><span>nrow</span>(question1_padded))

train_question1_padded &lt;-<span> </span>question1_padded[<span>-</span>val_sample,]
train_question2_padded &lt;-<span> </span>question2_padded[<span>-</span>val_sample,]
train_is_duplicate &lt;-<span> </span>df<span>$</span>is_duplicate[<span>-</span>val_sample]

val_question1_padded &lt;-<span> </span>question1_padded[val_sample,]
val_question2_padded &lt;-<span> </span>question2_padded[val_sample,]
val_is_duplicate &lt;-<span> </span>df<span>$</span>is_duplicate[val_sample]</code></pre>
</div>
<p>Now we use the <code><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit.html" target="_blank">fit()</a></code> function to train the model:</p>
<div>
<pre><code>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit.html" target="_blank">fit</a></span>(
  <span>list</span>(train_question1_padded, train_question2_padded),
  train_is_duplicate, 
  <span>batch_size =</span> <span>64</span>, 
  <span>epochs =</span> <span>10</span>, 
  <span>validation_data =</span> <span>list</span>(
    <span>list</span>(val_question1_padded, val_question2_padded), 
    val_is_duplicate
  )
)</code></pre>
</div>
<pre><code>Train on 363861 samples, validate on 40429 samples
Epoch 1/10
363861/363861 [==============================] - 89s 245us/step - loss: 0.5860 - acc: 0.7248 - val_loss: 0.5590 - val_acc: 0.7449
Epoch 2/10
363861/363861 [==============================] - 88s 243us/step - loss: 0.5528 - acc: 0.7461 - val_loss: 0.5472 - val_acc: 0.7510
Epoch 3/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5428 - acc: 0.7536 - val_loss: 0.5439 - val_acc: 0.7515
Epoch 4/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5353 - acc: 0.7595 - val_loss: 0.5358 - val_acc: 0.7590
Epoch 5/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5299 - acc: 0.7633 - val_loss: 0.5358 - val_acc: 0.7592
Epoch 6/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5256 - acc: 0.7662 - val_loss: 0.5309 - val_acc: 0.7631
Epoch 7/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5211 - acc: 0.7701 - val_loss: 0.5349 - val_acc: 0.7586
Epoch 8/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5173 - acc: 0.7733 - val_loss: 0.5278 - val_acc: 0.7667
Epoch 9/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5138 - acc: 0.7762 - val_loss: 0.5292 - val_acc: 0.7667
Epoch 10/10
363861/363861 [==============================] - 88s 242us/step - loss: 0.5092 - acc: 0.7794 - val_loss: 0.5313 - val_acc: 0.7654</code></pre>
<p>After training completes, we can save our model for inference with the <code><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/save_model_hdf5.html" target="_blank">save_model_hdf5()</a></code> function.</p>
<div>
<pre><code><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/save_model_hdf5.html" target="_blank">save_model_hdf5</a></span>(model, <span>&quot;model-question-pairs.hdf5&quot;</span>)</code></pre>
</div>
</div>
<div>
<h2>Model tuning</h2>
<p>Now that we have a reasonable model, let’s tune the hyperparameters using the <a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns" target="_blank">tfruns</a> package. We’ll begin by adding <code>FLAGS</code> declarations to our script for all hyperparameters we want to tune (<code>FLAGS</code> allow us to vary hyperparmaeters without changing our source code):</p>
<div>
<pre><code>FLAGS &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flags</a></span>(
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flag_integer</a></span>(<span>&quot;vocab_size&quot;</span>, <span>50000</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flag_integer</a></span>(<span>&quot;max_len_padding&quot;</span>, <span>20</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flag_integer</a></span>(<span>&quot;embedding_size&quot;</span>, <span>256</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flag_numeric</a></span>(<span>&quot;regularization&quot;</span>, <span>0.0001</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/reexports.html" target="_blank">flag_integer</a></span>(<span>&quot;seq_embedding_size&quot;</span>, <span>512</span>)
)</code></pre>
</div>
<p>With this <code>FLAGS</code> definition we can now write our code in terms of the flags. For example:</p>
<div>
<pre><code>input1 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_input.html" target="_blank">layer_input</a></span>(<span>shape =</span> <span>c</span>(FLAGS<span>$</span>max_len_padding))
input2 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_input.html" target="_blank">layer_input</a></span>(<span>shape =</span> <span>c</span>(FLAGS<span>$</span>max_len_padding))

embedding &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_embedding.html" target="_blank">layer_embedding</a></span>(
  <span>input_dim =</span> FLAGS<span>$</span>vocab_size <span>+</span><span> </span><span>2</span>, 
  <span>output_dim =</span> FLAGS<span>$</span>embedding_size, 
  <span>input_length =</span> FLAGS<span>$</span>max_len_padding, 
  <span>embeddings_regularizer =</span> <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/regularizer_l1.html" target="_blank">regularizer_l2</a></span>(<span>l =</span> FLAGS<span>$</span>regularization)
)</code></pre>
</div>
<p>The full source code of the script with <code>FLAGS</code> can be found <a rel="nofollow" href="https://gist.github.com/dfalbel/a5d63d6bffe683072cc4781d7c8420ff" target="_blank">here</a>.</p>
<p>We additionally added an early stopping callback in the training step in order to stop training if validation loss doesn’t decrease for 5 epochs in a row. This will hopefully reduce training time for bad models. We also added a learning rate reducer to reduce the learning rate by a factor of 10 when the loss doesn’t decrease for 3 epochs (this technique typically increases model accuracy).</p>
<div>
<pre><code>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit.html" target="_blank">fit</a></span>(
  ...,
  <span>callbacks =</span> <span>list</span>(
    <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/callback_early_stopping.html" target="_blank">callback_early_stopping</a></span>(<span>patience =</span> <span>5</span>),
    <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/callback_reduce_lr_on_plateau.html" target="_blank">callback_reduce_lr_on_plateau</a></span>(<span>patience =</span> <span>3</span>)
  )
)</code></pre>
</div>
<p>We can now execute a tuning run to probe for the optimal combination of hyperparameters. We call the <code><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/tuning_run.html" target="_blank">tuning_run()</a></code> function, passing a list with the possible values for each flag. The <code><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/tuning_run.html" target="_blank">tuning_run()</a></code> function will be responsible for executing the script for all combinations of hyperparameters. We also specify the <code>sample</code> parameter to train the model for only a random sample from all combinations (reducing training time significantly).</p>
<div>
<pre><code><span>library</span>(tfruns)

runs &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/tuning_run.html" target="_blank">tuning_run</a></span>(
  <span>&quot;question-pairs.R&quot;</span>, 
  <span>flags =</span> <span>list</span>(
    <span>vocab_size =</span> <span>c</span>(<span>30000</span>, <span>40000</span>, <span>50000</span>, <span>60000</span>),
    <span>max_len_padding =</span> <span>c</span>(<span>15</span>, <span>20</span>, <span>25</span>),
    <span>embedding_size =</span> <span>c</span>(<span>64</span>, <span>128</span>, <span>256</span>),
    <span>regularization =</span> <span>c</span>(<span>0.00001</span>, <span>0.0001</span>, <span>0.001</span>),
    <span>seq_embedding_size =</span> <span>c</span>(<span>128</span>, <span>256</span>, <span>512</span>)
  ), 
  <span>runs_dir =</span> <span>&quot;tuning&quot;</span>, 
  <span>sample =</span> <span>0.2</span>
)</code></pre>
</div>
<p>The tuning run will return a <code>data.frame</code> with results for all runs. We found that the best run attained 84.9% accuracy using the combination of hyperparameters shown below, so we modify our training script to use these values as the defaults:</p>
<div>
<pre><code>FLAGS &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flags</a></span>(
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flag_integer</a></span>(<span>&quot;vocab_size&quot;</span>, <span>50000</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flag_integer</a></span>(<span>&quot;max_len_padding&quot;</span>, <span>20</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flag_integer</a></span>(<span>&quot;embedding_size&quot;</span>, <span>256</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flag_numeric</a></span>(<span>&quot;regularization&quot;</span>, <span>1e-4</span>),
  <span><a rel="nofollow" href="https://tensorflow.rstudio.com/tools/tfruns/reference/flags.html" target="_blank">flag_integer</a></span>(<span>&quot;seq_embedding_size&quot;</span>, <span>512</span>)
)</code></pre>
</div>
</div>
<div>
<h2>Making predictions</h2>
<p>Now that we have trained and tuned our model we can start making predictions. At prediction time we will load both the text tokenizer and the model we saved to disk earlier.</p>
<div>
<pre><code><span>library</span>(keras)
model &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/save_model_hdf5.html" target="_blank">load_model_hdf5</a></span>(<span>&quot;model-question-pairs.hdf5&quot;</span>, <span>compile =</span> <span>FALSE</span>)
tokenizer &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/save_text_tokenizer.html" target="_blank">load_text_tokenizer</a></span>(<span>&quot;tokenizer-question-pairs&quot;</span>)</code></pre>
</div>
<p>Since we won’t continue training the model, we specified the <code>compile = FALSE</code> argument.</p>
<p>Now let`s define a function to create predictions. In this function we we preprocess the input data in the same way we preprocessed the training data:</p>
<div>
<pre><code>predict_question_pairs &lt;-<span> </span><span>function</span>(model, tokenizer, q1, q2) {
  q1 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/texts_to_sequences.html" target="_blank">texts_to_sequences</a></span>(tokenizer, <span>list</span>(q1))
  q2 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/texts_to_sequences.html" target="_blank">texts_to_sequences</a></span>(tokenizer, <span>list</span>(q2))
  
  q1 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/pad_sequences.html" target="_blank">pad_sequences</a></span>(q1, <span>20</span>)
  q2 &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/pad_sequences.html" target="_blank">pad_sequences</a></span>(q2, <span>20</span>)
  
  <span>as.numeric</span>(<span>predict</span>(model, <span>list</span>(q1, q2)))
}</code></pre>
</div>
<p>We can now call it with new pairs of questions, for example:</p>
<div>
<pre><code><span>predict_question_pairs</span>(
  model,
  tokenizer,
  <span>&quot;What's R programming?&quot;</span>,
  <span>&quot;What's R in programming?&quot;</span>
)</code></pre>
</div>
<pre><code>[1] 0.9784008</code></pre>
<p>Prediction is quite fast (~40 milliseconds).</p>
</div>
<div>
<h2>Deploying the model</h2>
<p>To demonstrate deployment of the trained model, we created a simple <a rel="nofollow" href="https://shiny.rstudio.com/" target="_blank">Shiny</a> application, where you can paste 2 questions from Quora and find the probability of them being duplicated. Try changing the questions below or entering two entirely different questions.</p>
<p><iframe width="450" src="https://jjallaire.shinyapps.io/shiny-quora/"><br>
</iframe></p>
<p>The shiny application can be found at <a rel="nofollow" href="https://jjallaire.shinyapps.io/shiny-quora/" target="_blank">https://jjallaire.shinyapps.io/shiny-quora/</a> and it’s source code at <a rel="nofollow" href="https://github.com/dfalbel/shiny-quora-question-pairs" target="_blank">https://github.com/dfalbel/shiny-quora-question-pairs</a>.</p>
<p>Note that when deploying a Keras model you only need to load the previously saved model file and tokenizer (no training data or model training steps are required).</p>
</div>
<div>
<h2>Wrapping up</h2>
<ul>
<li>We trained a Siamese LSTM that gives us reasonable accuracy (84%). Quora’s state of the art is 87%.</li>
<li>We can improve our model by using pre-trained word embeddings on larger datasets. For example, try using what’s described in <a rel="nofollow" href="https://github.com/rstudio/keras/blob/master/vignettes/examples/pretrained_word_embeddings.R" target="_blank">this example</a>. Quora uses their own complete corpus to train the word embeddings.</li>
<li>After training we deployed our model as a Shiny application which given two Quora questions calculates the probability of their being duplicates.</li>
</ul>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://tensorflow.rstudio.com/blog/keras-duplicate-questions-quora.html"> TensorFlow for R</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/PV89l5s76WA" height="1"></a></div>