<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harshil Patel on Medium]]></title>
        <description><![CDATA[Stories by Harshil Patel on Medium]]></description>
        <link>https://medium.com/@harshil.99?source=rss-ef96953faa42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ak9mrqM81Le1VtUAIKZ7LA.jpeg</url>
            <title>Stories by Harshil Patel on Medium</title>
            <link>https://medium.com/@harshil.99?source=rss-ef96953faa42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:41:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshil.99/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Neural Machine Translation (NMT) with Attention Mechanism]]></title>
            <link>https://medium.com/data-science/neural-machine-translation-nmt-with-attention-mechanism-5e59b57bd2ac?source=rss-ef96953faa42------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e59b57bd2ac</guid>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Harshil Patel]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 14:43:36 GMT</pubDate>
            <atom:updated>2020-06-15T05:37:20.443Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to translate languages with Deep Learning!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBY0wuKO6FHnejWCkFCCpg.jpeg" /></figure><h3>Overview</h3><p>It is an undeniable truth that in this era of globalization, language translation plays a vital role in communication among the denizens of different nation’s. Moreover, in a country like India - which a multilingual nation, language difference could be observed in its states itself! Hence, considering the importance of Language Translation, it becomes necessary to develop a system that could easily translate an unknown language to a known language.</p><p>In accordance with this, in this story, we will make a Deep Learning model that will translate English sentences to Marathi sentences. I have chosen Marathi language as it is easy for me to recognize. You can use any other language that is comfortable for you, as the model nearly remains the same. Moreover, I will try to briefly explain a major concept in language processing called Attention Mechanism here!</p><h3>Prerequisites</h3><ol><li>Working of<a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21"> Long Short Time Memory(LSTM)</a> cells</li><li>Working of TensorFlow, Keras and some other mandatory python libraries.</li></ol><h3>What is an Attention Mechanism?</h3><p>The major drawback of encoder-decoder model in sequence to sequence recurrent neural network is that it can only work on short sequences. <strong>It is difficult for the encoder model to memorize long sequences and convert it into a fixed-length vector. </strong>Moreover, the decoder receives only one information that is the last encoder hidden state. Hence it&#39;s difficult for the decoder to summarize large input sequence at once. So, how do we overcome this problem?</p><blockquote>How about if we give a vector representation from every encoder step to the decoder model!</blockquote><p>Now, this is where the concept of <strong>‘Attention Mechanism</strong>’ comes. The major intuition about this is that it predicts the next word by concentrating on a few relevant parts of the sequence rather than looking on the entire sequence.</p><blockquote>In layman terms it can be described as an interference between encoder and decoder which extracts useful information from encoder and transmits it back to the decoder.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EJ406jTayuLZKlLa.gif" /><figcaption>Animation of Attention Layer</figcaption></figure><p><em>Refer </em><a href="https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3"><em>here</em></a><em> for detailed understanding about Attention Mechanism.</em></p><p>There are mainly two types of attention mechanism:</p><ul><li>Global Attention</li><li>Local Attention</li></ul><h4>Global Attention</h4><p>Global Attention are those attention in which all the hidden state vectors of the encoder are passed to get the context vector.</p><h4>Local Attention</h4><p>Local Attention are those attention in which only a few hidden state vectors of encoder are considered for the generation of context vector.</p><p>We will be using global attention in this story. Let’s now make use of attention mechanism and develop a language translator that will convert English sentence to Marathi sentence.</p><h3>Implementation</h3><h4>Library Imports</h4><p>Open Jupyter Notebook and import some required libraries:</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>import string<br>from string import digits<br>import re<br>from sklearn.utils import shuffle<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br>from tensorflow.keras.layers import LSTM, Input, Dense,Embedding, Concatenate, TimeDistributed<br>from tensorflow.keras.models import Model,load_model, model_from_json<br>from tensorflow.keras.utils import plot_model<br>from tensorflow.keras.preprocessing.text import one_hot, Tokenizer<br>from tensorflow.keras.callbacks import EarlyStopping<br>import pickle as pkl<br>import numpy as np</pre><h4>Download Dataset</h4><blockquote>We will be working on a language dataset available <a href="http://www.manythings.org/anki/"><em>here</em></a><em>.</em></blockquote><p>This site contains a dataset of numerous languages and its translation to English. You can download any language dataset as per your preference and comfort. However, remember to choose a dataset which is quite huge, so that we can get better results after training the model. Here, I will be downloading Marathi-English dataset which comprises of 38696 sentences.</p><p>After downloading load dataset, import the data as mentioned below:</p><pre>with open(&#39;mar.txt&#39;,&#39;r&#39;) as f:<br>  data = f.read()</pre><h4>Preprocessing Dataset</h4><p><strong>Data Transformation</strong></p><p>As you can see that it is a raw text file and hence it is necessary to clean and transform it as per our preference. We will separate Marathi and English sentences and form a list of it, continuing it by storing it into a dataframe so that it&#39;s easy for us to reuse it again easily.</p><pre>uncleaned_data_list = data.split(&#39;\n&#39;)<br>len(uncleaned_data_list)<br>uncleaned_data_list = uncleaned_data_list[:38695]<br>len(uncleaned_data_list)</pre><pre>english_word = []<br>marathi_word = []<br>cleaned_data_list = []<br>for word in uncleaned_data_list:<br>  english_word.append(word.split(&#39;\t&#39;)[:-1][0])<br>  marathi_word.append(word.split(&#39;\t&#39;)[:-1][1])</pre><pre>language_data = pd.DataFrame(columns=[&#39;English&#39;,&#39;Marathi&#39;])<br>language_data[&#39;English&#39;] = english_word<br>language_data[&#39;Marathi&#39;] = marathi_word</pre><pre>language_data.to_csv(&#39;language_data.csv&#39;, index=False)</pre><blockquote>language_data.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*Nl0lTfBoXvutufRXPce3-g.jpeg" /></figure><pre>english_text = language_data[&#39;English&#39;].values<br>marathi_text = language_data[&#39;Marathi&#39;].values<br>len(english_text), len(marathi_text)</pre><p><strong>Data Cleaning</strong></p><p>Now let’s clean the data and make it suitable for our model. In the cleaning process, we will convert into lower case, remove all punctuation and other unnecessary letters and digits too.</p><pre><strong>#to lower case</strong><br>english_text_ = [x.lower() for x in english_text]<br>marathi_text_ = [x.lower() for x in marathi_text]</pre><pre><strong>#removing inverted commas</strong><br>english_text_ = [re.sub(&quot;&#39;&quot;,&#39;&#39;,x) for x in english_text_]<br>marathi_text_ = [re.sub(&quot;&#39;&quot;,&#39;&#39;,x) for x in marathi_text_]</pre><pre>def remove_punc(text_list):<br>  table = str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)<br>  removed_punc_text = []<br>  for sent in text_list:<br>    sentance = [w.translate(table) for w in sent.split(&#39; &#39;)]<br>    removed_punc_text.append(&#39; &#39;.join(sentance))<br>  return removed_punc_text<br>english_text_ = remove_punc(english_text_)<br>marathi_text_ = remove_punc(marathi_text_)</pre><pre>remove_digits = str.maketrans(&#39;&#39;, &#39;&#39;, digits)<br>removed_digits_text = []<br>for sent in english_text_:<br>  sentance = [w.translate(remove_digits) for w in sent.split(&#39; &#39;)]<br>  removed_digits_text.append(&#39; &#39;.join(sentance))<br>english_text_ = removed_digits_text</pre><pre><strong># removing the digits from the marathi sentances</strong><br>marathi_text_ = [re.sub(&quot;[२३०८१५७९४६]&quot;,&quot;&quot;,x) for x in marathi_text_]<br>marathi_text_ = [re.sub(&quot;[\u200d]&quot;,&quot;&quot;,x) for x in marathi_text_]</pre><pre><strong># removing the stating and ending whitespaces</strong><br>english_text_ = [x.strip() for x in english_text_]<br>marathi_text_ = [x.strip() for x in marathi_text_]</pre><p>Adding ‘start’ and ‘end’ tag to marathi sentence. This will help the decoder to know from where to start decoding and when to end.</p><pre># Putting the start and end words in the marathi sentances<br>marathi_text_ = [&quot;start &quot; + x + &quot; end&quot; for x in marathi_text_]</pre><pre># manipulated_marathi_text_<br>marathi_text_[0], english_text_[0]</pre><blockquote>(‘start जा end’, ‘go’)</blockquote><h4>Data preparation for model building</h4><p>We will split our dataset with a ratio of 0.1 so that our trained model can give precise results. X_train and y_train will be our training set while X_test and y_test will be our testing/validation set.</p><pre>X = english_text_<br>Y = marathi_text_</pre><pre>X_train, X_test, y_train, y_test=train_test_split(X,Y,test_size=0.1)</pre><p>Let’s determine the maximum length of our sentences in both English and Marathi:</p><pre>def Max_length(data):<br>  max_length_ = max([len(x.split(&#39; &#39;)) for x in data])<br>  return max_length_</pre><pre>#Training data<br>max_length_english = Max_length(X_train)<br>max_length_marathi = Max_length(y_train)</pre><pre>#Test data<br>max_length_english_test = Max_length(X_test)<br>max_length_marathi_test = Max_length(y_test)</pre><pre>max_length_marathi, max_length_english</pre><blockquote>(26, 32)</blockquote><p><strong>Tokenization:</strong></p><p>As a neural network requires numerical data to process, it becomes necessary to convert our string input to a numerical list. One way of doing this is to use <strong>Tokenizer </strong>provided by keras-preprocessing library.</p><p>Also, remember it is mandatory to have an equal length of all input sequences in sequence-to-sequence models. So, we will pad extra ‘0s’ to make the sequence of the same length. This would be done by <strong>pad_sequence.</strong></p><pre>englishTokenizer = Tokenizer()<br>englishTokenizer.fit_on_texts(X_train)<br>Eword2index = englishTokenizer.word_index<br>vocab_size_source = len(Eword2index) + 1</pre><pre>X_train = englishTokenizer.texts_to_sequences(X_train)<br>X_train = pad_sequences(X_train, maxlen=max_length_english, padding=&#39;post&#39;)</pre><pre>X_test = englishTokenizer.texts_to_sequences(X_test)<br>X_test = pad_sequences(X_test, maxlen = max_length_english, padding=&#39;post&#39;)</pre><pre>marathiTokenizer = Tokenizer()<br>marathiTokenizer.fit_on_texts(y_train)<br>Mword2index = marathiTokenizer.word_index<br>vocab_size_target = len(Mword2index) + 1</pre><pre>y_train = marathiTokenizer.texts_to_sequences(y_train)<br>y_train = pad_sequences(y_train, maxlen=max_length_marathi, padding=&#39;post&#39;)</pre><pre>y_test = marathiTokenizer.texts_to_sequences(y_test)<br>y_test = pad_sequences(y_test, maxlen = max_length_marathi, padding=&#39;post&#39;)</pre><pre>vocab_size_source, vocab_size_target</pre><blockquote>(5413, 12789)</blockquote><pre>X_train[0], y_train[0]</pre><blockquote>(array([ 1, 157, 5, 134, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,<br> 0, 0, 0, 0, 0, 0], dtype=int32),<br> array([ 1, 6, 22, 61, 253, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32))</blockquote><p><strong>To save our preprocessing time whenever we reuse it again in future, we will save our important attributes. </strong>So, let’s do it first with the help of pickle library.</p><pre>with open(&#39;NMT_data.pkl&#39;,&#39;wb&#39;) as f:<br>  pkl.dump([X_train, y_train, X_test, y_test],f)</pre><pre>with open(&#39;NMT_Etokenizer.pkl&#39;,&#39;wb&#39;) as f:<br>  pkl.dump([vocab_size_source, Eword2index, englishTokenizer], f)</pre><pre>with open(&#39;NMT_Mtokenizer.pkl&#39;, &#39;wb&#39;) as f:<br>  pkl.dump([vocab_size_target, Mword2index, marathiTokenizer], f)</pre><pre>X_train = np.array(X_train)<br>y_train = np.array(y_train)<br>X_test = np.array(X_test)<br>y_test = np.array(y_test)</pre><h4>Model Building</h4><p>Instead of a simple encoder-decoder architecture, we will be using Attention Mechanism as discussed earlier in this blog.</p><p>Keras does not officially support attention layer. So, we can either implement our own attention layer or use a third-party implementation. For now, we will be using a third party attention mechanism. You can download the attention layer from <a href="https://github.com/thushv89/attention_keras/blob/master/layers/attention.py"><strong>here</strong></a><strong> </strong>and copy it in a different file called <strong>attention.py</strong>. This attention is an implementation of <a href="https://arxiv.org/pdf/1409.0473.pdf"><em>‘Bahdanau Attention’</em></a><em> .</em></p><p>Let’s define the structure of our model:</p><pre>from attention import AttentionLayer<br>from keras import backend as K <br>K.clear_session() <br>latent_dim = 500</pre><pre># Encoder <br>encoder_inputs = Input(shape=(max_length_english,)) <br>enc_emb = Embedding(vocab_size_source, latent_dim,trainable=True)(encoder_inputs)</pre><pre>#LSTM 1 <br>encoder_lstm1 = LSTM(latent_dim,return_sequences=True,return_state=True) <br>encoder_output1, state_h1, state_c1 = encoder_lstm1(enc_emb)</pre><pre>#LSTM 2 <br>encoder_lstm2 = LSTM(latent_dim,return_sequences=True,return_state=True) <br>encoder_output2, state_h2, state_c2 = encoder_lstm2(encoder_output1)</pre><pre>#LSTM 3 <br>encoder_lstm3=LSTM(latent_dim, return_state=True, return_sequences=True) <br>encoder_outputs, state_h, state_c= encoder_lstm3(encoder_output2)</pre><pre># Set up the decoder. <br>decoder_inputs = Input(shape=(None,)) <br>dec_emb_layer = Embedding(vocab_size_target, latent_dim,trainable=True) <br>dec_emb = dec_emb_layer(decoder_inputs)</pre><pre>#LSTM using encoder_states as initial state<br>decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True) <br>decoder_outputs,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c])</pre><pre>#Attention Layer<br>attn_layer = AttentionLayer(name=&#39;attention_layer&#39;) <br>attn_out, attn_states = attn_layer([encoder_outputs, decoder_outputs])</pre><pre># Concat attention output and decoder LSTM output <br>decoder_concat_input = Concatenate(axis=-1, name=&#39;concat_layer&#39;)([decoder_outputs, attn_out])</pre><pre>#Dense layer<br>decoder_dense = TimeDistributed(Dense(vocab_size_target, activation=&#39;softmax&#39;)) <br>decoder_outputs = decoder_dense(decoder_concat_input)</pre><pre># Define the model<br>model = Model([encoder_inputs, decoder_inputs], decoder_outputs) </pre><pre>plot_model(model, to_file=&#39;train_model.png&#39;, show_shapes=True)</pre><p>You can modify this model as per your choice and requirement to get better results. You can change number of layers, number of units or some regularization techniques too. For the time being, let’s move forward and see what our model looks like!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*M6UKNwEUmdLdWnNHnva4BA.png" /></figure><pre>model.compile(optimizer=&#39;rmsprop&#39;,<br>              loss=&#39;sparse_categorical_crossentropy&#39;, <br>              metrics=[&#39;accuracy&#39;])</pre><h4>Model Training</h4><p>We will first define some callbacks so that it would be easy for model visualization and evaluation in future.</p><pre>es = EarlyStopping(monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, verbose=1)</pre><p>We are using ‘<strong>Teacher Forcing</strong>’ technique for faster training of our model. In the teacher forcing method, we also pass the target data as the input to the decoder. For example, if we are going to predict ‘hello’, then we will pass ‘hello’ itself as an input to the decoder. Due to this it makes the learning process faster.</p><p>Let&#39;s train our Model:</p><pre>history = model.fit([X_train, y_train[:,:-1]], y_train.reshape(y_train.shape[0], y_train.shape[1],1)[:,1:], <br>                    epochs=50, <br>                    callbacks=[es],<br>                    batch_size=512,<br>                    validation_data = ([X_test, y_test[:,:-1]],           y_test.reshape(y_test.shape[0], y_test.shape[1], 1)[:,1:]))</pre><blockquote>The execution time was around 39 seconds per epoch on 12GB <strong>NVIDIA </strong>Tesla K80 <strong>GPU</strong>. EarlyStopping was achieved at 18th epoch.</blockquote><p>We can visualize the loss difference in both training and validation phase as:</p><pre>from matplotlib import pyplot <br>pyplot.plot(history.history[&#39;loss&#39;], label=&#39;train&#39;) <br>pyplot.plot(history.history[&#39;val_loss&#39;], label=&#39;test&#39;) <br>pyplot.legend() <br>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*auQMVqklYia6LxLxcdJAog.png" /><figcaption>Loss Comparison</figcaption></figure><blockquote>We are getting some pretty good results from our model with around 90% validation accuracy and a validation loss of 0.5303.</blockquote><h4>Model Saving and Loading</h4><p>Let’s save our trained model with proper weights. Do remember to save the model like I have done as we have to load weights too for the inference model.</p><pre>model_json = model.to_json()<br>with open(&quot;NMT_model.json&quot;, &quot;w&quot;) as json_file:<br>    json_file.write(model_json)<br># serialize weights to HDF5<br>model.save_weights(&quot;NMT_model_weight.h5&quot;)<br>print(&quot;Saved model to disk&quot;)</pre><p>Load model:</p><pre># loading the model architecture and asigning the weights<br>json_file = open(&#39;NMT_model.json&#39;, &#39;r&#39;)<br>loaded_model_json = json_file.read()<br>json_file.close()<br>model_loaded = model_from_json(loaded_model_json, custom_objects={&#39;AttentionLayer&#39;: AttentionLayer})<br># load weights into new model<br>model_loaded.load_weights(&quot;NMT_model_weight.h5&quot;)</pre><h4>Inference Model</h4><blockquote>In machine learning we use inference model to predict our output sequences by considering weights from a pre-trained model. In other terms, it can be said that its a model that deduces properties that are learned in training phase and are now used for predicting new sequences.</blockquote><p>Let’s code our inference model:</p><pre>latent_dim=500<br># encoder inference<br>encoder_inputs = model_loaded.input[0]  #loading encoder_inputs<br>encoder_outputs, state_h, state_c = model_loaded.layers[6].output #loading encoder_outputs</pre><pre>#print(encoder_outputs.shape)</pre><pre>encoder_model = Model(inputs=encoder_inputs,outputs=[encoder_outputs, state_h, state_c])</pre><pre># decoder inference<br># Below tensors will hold the states of the previous time step<br>decoder_state_input_h = Input(shape=(latent_dim,))<br>decoder_state_input_c = Input(shape=(latent_dim,))<br>decoder_hidden_state_input = Input(shape=(32,latent_dim))</pre><pre># Get the embeddings of the decoder sequence<br>decoder_inputs = model_loaded.layers[3].output</pre><pre>#print(decoder_inputs.shape)<br>dec_emb_layer = model_loaded.layers[5]</pre><pre>dec_emb2= dec_emb_layer(decoder_inputs)</pre><pre># To predict the next word in the sequence, set the initial states to the states from the previous time step<br>decoder_lstm = model_loaded.layers[7]<br>decoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=[decoder_state_input_h, decoder_state_input_c])</pre><pre>#attention inference<br>attn_layer = model_loaded.layers[8]<br>attn_out_inf, attn_states_inf = attn_layer([decoder_hidden_state_input, decoder_outputs2])</pre><pre>concate = model_loaded.layers[9]<br>decoder_inf_concat = concate([decoder_outputs2, attn_out_inf])</pre><pre># A dense softmax layer to generate prob dist. over the target vocabulary<br>decoder_dense = model_loaded.layers[10]<br>decoder_outputs2 = decoder_dense(decoder_inf_concat)</pre><pre># Final decoder model<br>decoder_model = Model(<br>[decoder_inputs] + [decoder_hidden_state_input,decoder_state_input_h, decoder_state_input_c],<br>[decoder_outputs2] + [state_h2, state_c2])</pre><h4>Predictions</h4><p>Now we have trained the sequence to sequence model and created the inference model using the trained model for making a prediction. Let’s predict some Marathi sentences from the English sentences.</p><pre>def decode_sequence(input_seq):<br>    # Encode the input as state vectors.<br>    e_out, e_h, e_c = encoder_model.predict(input_seq)</pre><pre># Generate empty target sequence of length 1.<br>    target_seq = np.zeros((1,1))</pre><pre># Chose the &#39;start&#39; word as the first word of the target sequence<br>    target_seq[0, 0] = Mword2index[&#39;start&#39;]</pre><pre>stop_condition = False<br>    decoded_sentence = &#39;&#39;<br>    while not stop_condition:<br>        output_tokens, h, c = decoder_model.predict([target_seq] + [e_out, e_h, e_c])</pre><pre># Sample a token<br>        sampled_token_index = np.argmax(output_tokens[0, -1, :])<br>        if sampled_token_index == 0:<br>          break<br>        else:<br>          sampled_token = Mindex2word[sampled_token_index]</pre><pre>if(sampled_token!=&#39;end&#39;):<br>              decoded_sentence += &#39; &#39;+sampled_token</pre><pre># Exit condition: either hit max length or find stop word.<br>              if (sampled_token == &#39;end&#39; or len(decoded_sentence.split()) &gt;= (26-1)):<br>                  stop_condition = True</pre><pre># Update the target sequence (of length 1).<br>          target_seq = np.zeros((1,1))<br>          target_seq[0, 0] = sampled_token_index</pre><pre># Update internal states<br>          e_h, e_c = h, c</pre><pre>return decoded_sentence</pre><p>Forming a reverse vocabulary:</p><pre>Eindex2word = englishTokenizer.index_word<br>Mindex2word = marathiTokenizer.index_word</pre><p>Some transformation before giving a string to the function:</p><pre>def seq2summary(input_seq):<br>    newString=&#39;&#39;<br>    for i in input_seq:<br>      if((i!=0 and i!=Mword2index[&#39;start&#39;]) and i!=Mword2index[&#39;end&#39;]):<br>        newString=newString+Mindex2word[i]+&#39; &#39;<br>    return newString</pre><pre>def seq2text(input_seq):<br>    newString=&#39;&#39;<br>    for i in input_seq:<br>      if(i!=0):<br>        newString=newString+Eindex2word[i]+&#39; &#39;<br>    return newString</pre><p>Call the necessary functions and let’s test our translation model:</p><pre>for i in range(10):  <br>  print(&quot;Review:&quot;,seq2text(X_test[i]))<br>  print(&quot;Original summary:&quot;,seq2summary(y_test[i]))<br>  print(&quot;Predicted summary:&quot;,decode_sequence(X_test[i].reshape(1,32)))<br>  print(&quot;\n&quot;)</pre><blockquote>Review: no one will tell you <br>Original summary: तुला कोणीही सांगणार नाही <br>Predicted summary: कोणीही तुला सांगणार नाही</blockquote><blockquote>Review: look ahead <br>Original summary: समोर बघा <br>Predicted summary: तिथे बघ</blockquote><blockquote>Review: im going to return this to tom <br>Original summary: मी हे टॉमला परत करायला जातोय <br>Predicted summary: मी ते स्वतःहून करणार आहे</blockquote><blockquote>Review: an eagle is flying in the sky <br>Original summary: आकाशात एक गरुड आहे <br>Predicted summary: न्यूयॉर्क अतिरेकी तो दुसर्याचा</blockquote><blockquote>Review: he speaks arabic <br>Original summary: तो अरबी बोलतो <br>Predicted summary: तो अरबी बोलतो</blockquote><blockquote>Review: clean up this mess <br>Original summary: हा पसारा साफ करून टाका <br>Predicted summary: हा पसारा साफ कर</blockquote><blockquote>Review: dont speak french in the class <br>Original summary: वर्गात फ्रेंचमध्ये बोलू नका <br>Predicted summary: वर्गात जास्त कठीण राहू नकोस</blockquote><blockquote>Review: i turned the lights out <br>Original summary: मी दिवे <br>Predicted summary: मी दोन हात वर केला</blockquote><blockquote>Review: how many rackets do you have <br>Original summary: तुझ्याकडे किती रॅकेट आहेत <br>Predicted summary: तुमच्याकडे किती बहिणी आहेत</blockquote><blockquote>Review: i gave tom marys phone number <br>Original summary: मी टॉमला मेरीचा फोन नंबर दिला <br>Predicted summary: मी टॉमला मेरीचा फोन क्रमांक दिला</blockquote><p>Hurrah!!</p><p>Our model makes some good translations of English sentences to Marathi sentences.</p><h4>Project Demo</h4><p>I have deployed my model through Django and have hosted it on heroku. You can look at it here.</p><p><a href="https://hurdlenet.herokuapp.com/">Harshil Patel</a></p><h4>Ending Notes</h4><p>In this story, we learned about the functionality of Attention Mechanism and implemented a Language Translation task. This task could have multiple use cases in daily lifestyles. For example, we can use this technique to build a multi-language translator that can translate various languages from a single language. Also, if we can integrate this with an Optical Character Recognition system, we can translate texts directly from images.</p><p>If you have any other use case or technique to work with translation data and also, if you find a more improved model for NMT, do share in the response block below!</p><p>The entire code for this article is available <a href="https://github.com/harshilpatel99/NMT_english2marthi"><em>here</em></a>. If you have any feedback, feel free to reach out to me on <a href="https://www.linkedin.com/in/harshil-patel-708680148/"><em>LinkedIn</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e59b57bd2ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/neural-machine-translation-nmt-with-attention-mechanism-5e59b57bd2ac">Neural Machine Translation (NMT) with Attention Mechanism</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Super-Resolution using Convolution Neural Networks and Auto-encoders]]></title>
            <link>https://medium.com/data-science/image-super-resolution-using-convolution-neural-networks-and-auto-encoders-28c9eceadf90?source=rss-ef96953faa42------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c9eceadf90</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harshil Patel]]></dc:creator>
            <pubDate>Sat, 16 May 2020 06:25:59 GMT</pubDate>
            <atom:updated>2020-06-15T10:20:33.752Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to enhancing image quality with Deep Learning!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TFC2WK68_lA-JzJf" /><figcaption><a href="https://unsplash.com/@jeroenbosch?utm_source=medium&amp;utm_medium=referral">(Source)</a></figcaption></figure><p>The problem statement is quite familiar. You may all have faced problems with distorted images at some point and hence would have tried to enhance the image quality. Well, due to the advances in deep learning techniques, we’ll try to enhance the resolution of images by training a convolution neural network and using auto-encoders here!</p><h4><strong>Prerequisites</strong></h4><ol><li>A basic understanding of <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53">Convolution Neural Networks</a>(CNNs)</li><li>Working of TensorFlow, Keras and some other mandatory python libraries.</li></ol><h4>What are Auto-encoders?</h4><p>Auto-encoders are a type of generative models used for unsupervised learning.</p><blockquote>In layman terms it can be said that these models take some input <strong><em>x</em></strong>, tries to learn some latent features and then reconstructs input <strong><em>x</em></strong> to give some desired output <strong><em>X</em></strong> with the help of these learned features.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4XXGeLQtoMnuf8ma-OobQ.png" /><figcaption>Here image input is been reconstructed <a href="https://ars.els-cdn.com/content/image/1-s2.0-S235291481830176X-egi10PTKWBT6NG.jpg">(Source)</a></figcaption></figure><p>We will be using the concept of auto-encoder model to increase the resolution of an image. For detailed understanding about auto-encoders click <a href="https://towardsdatascience.com/applied-deep-learning-part-3-autoencoders-1c083af4d798"><em>here</em></a>.</p><h4>Implementation:</h4><p><strong>Library Imports</strong></p><p>Let’s open Jupyter Notebook and import some required libraries.</p><pre>import numpy as np<br>import cv2<br>import glob<br>import tensorflow as tf<br>from tensorflow.keras import Model, Input, regularizers<br>from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, UpSampling2D, Add, Dropout<br>from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint<br>from keras.preprocessing import image<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split <br>import pickle</pre><p><strong>Download Dataset</strong></p><p>We will be working on ‘<strong><em>Labeled Faces in the Wild Home</em></strong>’ dataset. This dataset contains a database of labelled faces, generally used for face recognition and detection. However, our aim is not to detect faces but to make a model to enhance image resolution.</p><blockquote>Download Dataset by clicking <a href="http://vis-www.cs.umass.edu/lfw/lfw.tgz"><em>here</em></a><em>.</em></blockquote><p>The dataset comprises of multiple sub directories containing various images of that person. Hence, it is important to capture image paths from these directories.</p><pre>face_images = glob.glob(&#39;lfw/lfw/**/*.jpg&#39;) #returns path of images<br>print(len(face_images)) #contains 13243 images</pre><p><strong>Load and Preprocess Images</strong></p><p>The size of original images are of 250 x 250 pixels. However, it would take a lot computation power to process these images on normal computer. Therefore, we will reduce the size of all images to 80 x 80 pixels.</p><blockquote>As there are around 13,000 images, it would take lot of time if we process it individually. Hence, we take advantage of <a href="https://docs.python.org/2/library/multiprocessing.html"><strong>multiprocessing</strong> </a>library provided in python for ease of execution.</blockquote><blockquote><a href="https://pypi.org/project/tqdm/"><strong>tqdm </strong></a>is a progress library that we use to get a progress bar of the work done.</blockquote><pre>from tqdm import tqdm<br>from multiprocessing import Pool</pre><pre>progress = tqdm(total= len(face_images), position=0)<br>def read(path):<br>  img = image.load_img(path, target_size=(80,80,3))<br>  img = image.img_to_array(img)<br>  img = img/255.<br>  progress.update(1)<br>  return img</pre><pre>p = Pool(10)<br>img_array = p.map(read, face_images)</pre><p>In order to save time in future, let’s store our <em>img_array</em> (contains images) with the help of pickle library:</p><pre>with open(&#39;img_array.pickle&#39;,&#39;wb&#39;) as f:<br>  pickle.dump(img_array, f)</pre><pre>print(len(img_array))</pre><p><strong>Data preparation for Model Training</strong></p><p>Now, we will split our dataset to train and validation set. We will use train data to train our model and validation data will be used to evaluate the model.</p><pre>all_images = np.array(img_array)</pre><pre>#Split test and train data. all_images will be our output images<br>train_x, val_x = train_test_split(all_images, random_state = 32, test_size=0.2)</pre><p>As this is an image resolution enhancement task we will distort our images and take it as an input images. The original images will be added as our output images.</p><pre>#now we will make input images by lowering resolution without changing the size<br>def pixalate_image(image, scale_percent = 40):<br>  width = int(image.shape[1] * scale_percent / 100)<br>  height = int(image.shape[0] * scale_percent / 100)<br>  dim = (width, height)</pre><pre>  small_image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)<br>  <br>  # scale back to original size<br>  width = int(small_image.shape[1] * 100 / scale_percent)<br>  height = int(small_image.shape[0] * 100 / scale_percent)<br>  dim = (width, height)</pre><pre>  low_res_image = cv2.resize(small_image, dim, interpolation =  cv2.INTER_AREA)</pre><pre> return low_res_image</pre><blockquote>The idea is to take these distorted images and feed it to our model and make model learn to get the original image back.</blockquote><pre>train_x_px = []</pre><pre>for i in range(train_x.shape[0]):<br>  temp = pixalate_image(train_x[i,:,:,:])<br>  train_x_px.append(temp)</pre><pre>train_x_px = np.array(train_x_px)   #Distorted images</pre><pre># get low resolution images for the validation set<br>val_x_px = []</pre><pre>for i in range(val_x.shape[0]):<br>  temp = pixalate_image(val_x[i,:,:,:])<br>  val_x_px.append(temp)</pre><pre>val_x_px = np.array(val_x_px)     #Distorted images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*6vollQxPsSu07FZg1X9_2g.png" /><figcaption>Input Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*R-thvW_0gVh9Y79lBlYEZw.png" /><figcaption>Original Image</figcaption></figure><p><strong>Model building</strong></p><p>Let&#39;s define the structure of model. Moreover, to overcome the possibility of over-fitting, we are using <strong>l1 regularization</strong> technique in our convolution layer.</p><pre>Input_img = Input(shape=(80, 80, 3))  <br>    <br>#encoding architecture<br>x1 = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(Input_img)<br>x2 = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x1)<br>x3 = MaxPool2D(padding=&#39;same&#39;)(x2)</pre><pre>x4 = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x3)<br>x5 = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x4)<br>x6 = MaxPool2D(padding=&#39;same&#39;)(x5)</pre><pre>encoded = Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x6)<br>#encoded = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x2)</pre><pre># decoding architecture<br>x7 = UpSampling2D()(encoded)<br>x8 = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x7)<br>x9 = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x8)<br>x10 = Add()([x5, x9])</pre><pre>x11 = UpSampling2D()(x10)<br>x12 = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x11)<br>x13 = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, kernel_regularizer=regularizers.l1(10e-10))(x12)<br>x14 = Add()([x2, x13])</pre><pre># x3 = UpSampling2D((2, 2))(x3)<br># x2 = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x3)<br># x1 = Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x2)<br>decoded = Conv2D(3, (3, 3), padding=&#39;same&#39;,activation=&#39;relu&#39;, kernel_regularizer=regularizers.l1(10e-10))(x14)</pre><pre>autoencoder = Model(Input_img, decoded)<br>autoencoder.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;, metrics=[&#39;accuracy&#39;])</pre><p>You can modify this model as per your choice and requirement to get better results. You can change number of layers, number of units or some regularization techniques too. For the time being, let’s move forward and see what our model looks like!</p><pre>autoencoder.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0LGxbhH5QBo-hcA-PNzYQ.png" /><figcaption>Screenshot of the model summary</figcaption></figure><p><strong>Model Training</strong></p><p>We will first define some callbacks so that it would be easy for model visualization and evaluation in future.</p><pre>early_stopper = EarlyStopping(monitor=&#39;val_loss&#39;, min_delta=0.01, patience=50, verbose=1, mode=&#39;min&#39;)</pre><pre>model_checkpoint =  ModelCheckpoint(&#39;superResolution_checkpoint3.h5&#39;, save_best_only = True)</pre><p>Let&#39;s train our model:</p><pre>history = autoencoder.fit(train_x_px,train_x,<br>            epochs=500,<br>            validation_data=(val_x_px, val_x),<br>            callbacks=[early_stopper, model_checkpoint])</pre><blockquote>The execution time was around 21 seconds per epoch on 12GB <strong>NVIDIA</strong> Tesla K80 <strong>GPU. </strong>EarlyStopping was achieved at 65th epoch.</blockquote><p>Now, let&#39;s evaluate our model on our test dataset:</p><pre>results = autoencoder.evaluate(val_x_px, val_x)<br>print(&#39;val_loss, val_accuracy&#39;, results)</pre><blockquote>val_loss, val_accuracy [0.002111854264512658, 0.9279356002807617]</blockquote><p>We are getting some pretty good results from our model with around 93% validation accuracy and a validation loss of 0.0021.</p><p><strong>Make Predictions</strong></p><pre>predictions = autoencoder.predict(val_x_px)</pre><pre>n = 4<br>plt.figure(figsize= (20,10))</pre><pre>for i in range(n):<br>  ax = plt.subplot(3, n, i+1)<br>  plt.imshow(val_x_px[i+20])<br>  ax.get_xaxis().set_visible(False)<br>  ax.get_yaxis().set_visible(False)</pre><pre>  ax = plt.subplot(3, n, i+1+n)<br>  plt.imshow(predictions[i+20])<br>  ax.get_xaxis().set_visible(False)<br>  ax.get_yaxis().set_visible(False)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wzZbWyKt9v_vWVmdHmBxA.png" /><figcaption>1st row — Input Images &amp; 2nd row — Output Images</figcaption></figure><h4>Ending Notes</h4><p>In this story, we learned about basic functionality of auto-encoders and implemented an Image Super-Resolution enhancement task. This task could have multiple use cases in daily lifestyles. For example, we can use this technique to enhance the quality of low-resolution videos as well. So, even without labels, we can work with the image data and solve several real-world problems.</p><p>If you have any other use case or technique to work with image data and also, if you find more improved model for image enhancement, do share in the response block below!</p><p>The entire code for this article is available <a href="https://github.com/harshilpatel99/image_superResolution"><em>here</em></a>.</p><h4>Reference</h4><ol><li>A course by Snehan Kekre on <a href="http://www.coursera.org/projects/image-super-resolution-autoencoders-keras?edocomorp=freegpmay2020"><em>Coursera</em></a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c9eceadf90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-super-resolution-using-convolution-neural-networks-and-auto-encoders-28c9eceadf90">Image Super-Resolution using Convolution Neural Networks and Auto-encoders</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>