avatarNaina Chaturvedi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

11635

Abstract

s, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to <b>Tech Brew :</b></p></blockquote><div id="8d5c" class="link-block"> <a href="https://naina0405.substack.com/"> <div> <div> <h2>Ignito</h2> <div><h3>Data Science, ML, AI and more… Click to read Ignito, by Naina Chaturvedi, a Substack publication. Launched 7 months…</h3></div> <div><p>naina0405.substack.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*_ER1J-h50iqAjH70)"></div> </div> </div> </a> </div><p id="c781">Recurrent Neural Network, created in the 1980’s, is a state of the art algorithm for dealing with sequential data by using internal memory to remember important things about the input RNN’s received to precisely predict what’s coming next. RNN’s are popularly used in language translation, natural language processing (nlp), speech recognition, captioning etc.</p><figure id="09af"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*qfAkD_ULX3dHkNcM.png"><figcaption>RNN vs Feed Forward Network ( Pic credits : IBM)</figcaption></figure><figure id="5388"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*hr7tFcw4FDHuMIbI.png"><figcaption>How RNN works ( Pic credits : Research Gate)</figcaption></figure><p id="06a7">Long Short Term Memory networks (LSTM) introduced by Hochreiter & Schmidhuber are special type of Recurrent Neural Networks ( RNN) designed to avoid the long-term dependency problem and can selectively remember patterns for long duration of time.</p><figure id="5b9b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*VpGDrEIBm1Jcmy5m.jpg"><figcaption>Pic credits : ResearchGate</figcaption></figure><figure id="6f9a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*GytesBQynahmHkhx.jpg"><figcaption>Bidirectional LSTM ( Pic credits : Datax)</figcaption></figure><p id="a60b"><i>“The Long Short Term Memory architecture was motivated by an analysis of error flow in existing RNNs which found that long time lags were inaccessible to existing architectures, because backpropagated error either blows up or decays exponentially.</i></p><p id="33af"><i>An LSTM layer consists of a set of recurrently connected blocks, known as memory blocks. These blocks can be thought of as a differentiable version of the memory chips in a digital computer. Each one contains one or more recurrently connected memory cells and three multiplicative units — the input, output and forget gates — that provide continuous analogues of write, read and reset operations for the cells. … The net can only interact with the cells via the gates.”</i></p><p id="36e6"><i>— Alex Graves, et al., Framewise Phoneme Classification with Bidirectional LSTM and Other Neural Network Architectures, 2005.</i></p><p id="d61d">A good reference to understand the vastness of LSTM —</p><div id="2cc9" class="link-block"> <a href="https://keras.io/api/layers/recurrent_layers/lstm/"> <div> <div> <h2>Keras documentation: LSTM layer</h2> <div><h3>Long Short-Term Memory layer - Hochreiter 1997. See the Keras RNN API guide for details about the usage of RNN API…</h3></div> <div><p>keras.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*DSUxtD7e793LVQ-V)"></div> </div> </div> </a> </div><p id="24ea">In this post we are going to implement translator using LSTM.</p><p id="affe">Let’s dive in!</p><h2 id="54e3">Import libraries and datasets</h2><div id="cf87"><pre><span class="hljs-title">from</span> collections <span class="hljs-keyword">import</span> Counter <span class="hljs-keyword">import</span> operator <span class="hljs-keyword">import</span> plotly.express <span class="hljs-keyword">as</span> px <span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd <span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np <span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt <span class="hljs-keyword">import</span> seaborn <span class="hljs-keyword">as</span> sns <span class="hljs-title">from</span> wordcloud <span class="hljs-keyword">import</span> WordCloud, STOPWORDS</pre></div><div id="5d11"><pre>from sklearn<span class="hljs-selector-class">.model_selection</span> import train_test_split import nltk import re from nltk<span class="hljs-selector-class">.stem</span> import PorterStemmer, WordNetLemmatizer from nltk<span class="hljs-selector-class">.corpus</span> import stopwords from nltk<span class="hljs-selector-class">.tokenize</span> import word_tokenize, sent_tokenize import gensim from gensim<span class="hljs-selector-class">.utils</span> import simple_preprocess from gensim<span class="hljs-selector-class">.parsing</span><span class="hljs-selector-class">.preprocessing</span> import STOPWORDS from tensorflow<span class="hljs-selector-class">.keras</span><span class="hljs-selector-class">.preprocessing</span><span class="hljs-selector-class">.text</span> import one_hot, Tokenizer from tensorflow<span class="hljs-selector-class">.keras</span><span class="hljs-selector-class">.preprocessing</span><span class="hljs-selector-class">.sequence</span> import pad_sequences from tensorflow<span class="hljs-selector-class">.keras</span><span class="hljs-selector-class">.models</span> import Sequential from tensorflow<span class="hljs-selector-class">.keras</span><span class="hljs-selector-class">.layers</span> import Dense, Flatten, TimeDistributed, RepeatVector, Embedding, Input, LSTM, Conv1D, MaxPool1D, Bidirectional from tensorflow<span class="hljs-selector-class">.keras</span><span class="hljs-selector-class">.models</span> import Model from jupyterthemes import jtplot jtplot<span class="hljs-selector-class">.style</span>(theme=<span class="hljs-string">'monokai'</span>, context=<span class="hljs-string">'notebook'</span>, ticks=True, <span class="hljs-attribute">grid</span>=False) nltk<span class="hljs-selector-class">.download</span>(<span class="hljs-string">'punkt'</span>) nltk<span class="hljs-selector-class">.download</span>(<span class="hljs-string">"stopwords"</span>)</pre></div><h2 id="6d0a">Load Data and Data Preprocessing</h2><div id="3f75"><pre><span class="hljs-comment"># load the data</span> df_english = pd.read_csv(<span class="hljs-string">'small_vocab_en.csv'</span>, sep = <span class="hljs-string">'/t'</span>, names = [<span class="hljs-string">'english'</span>]) df_french = pd.read_csv(<span class="hljs-string">'small_vocab_fr.csv'</span>, sep = <span class="hljs-string">'/t'</span>, names = [<span class="hljs-string">'french'</span>]) <span class="hljs-built_in">print</span>(df_english.<span class="hljs-built_in">info</span>())</pre></div><div id="a97e"><pre><span class="hljs-attr">df</span> = pd.concat([df_english,df_french],axis=<span class="hljs-number">1</span>) </pre></div><p id="834f">Output —</p><div id="9251"><pre><<span class="hljs-keyword">class</span> <span class="hljs-string">'pandas.core.frame.DataFrame'</span>> Range<span class="hljs-keyword">Index</span>: <span class="hljs-number">137860</span> entries, <span class="hljs-number">0</span> <span class="hljs-keyword">to</span> <span class="hljs-number">137859</span> Data <span class="hljs-keyword">columns</span> (total <span class="hljs-number">1</span> <span class="hljs-keyword">columns</span>):

<span class="hljs-keyword">Column</span> Non-<span class="hljs-keyword">Null</span> Count Dtype

<span class="hljs-comment">--- ------ -------------- ----- </span> <span class="hljs-number">0</span> english <span class="hljs-number">137860</span> non-<span class="hljs-keyword">null</span> <span class="hljs-keyword">object</span> dtypes: <span class="hljs-keyword">object</span>(<span class="hljs-number">1</span>) memory <span class="hljs-keyword">usage</span>: <span class="hljs-number">1.1</span>+ MB</pre></div><h2 id="b10c">Remove Punctuations and Word Cloud</h2><div id="504b"><pre>def <span class="hljs-built_in">remove_punc</span>(x): return re.<span class="hljs-built_in">sub</span>(<span class="hljs-string">'[!#?,.:";]'</span>, <span class="hljs-string">''</span>, x) df[<span class="hljs-string">'french'</span>] = df[<span class="hljs-string">'french'</span>].<span class="hljs-built_in">apply</span>(remove_punc) df[<span class="hljs-string">'english'</span>] = df[<span class="hljs-string">'english'</span>].<span class="hljs-built_in">apply</span>(remove_punc) def <span class="hljs-built_in">guw</span>(x,word_list): for word in x.<span class="hljs-built_in">split</span>(): if word not in word_list: word_list.<span class="hljs-built_in">append</span>(word) df[<span class="hljs-string">'english'</span>].<span class="hljs-built_in">apply</span>(lambda x:<span class="hljs-built_in">guw</span>(x,english_words)) df[<span class="hljs-string">'french'</span>].<span class="hljs-built_in">apply</span>(lambda x: <span class="hljs-built_in">guw</span>(x,french_words)) plt.<span class="hljs-built_in">figure</span>(figsize = (<span class="hljs-number">20</span>,<span class="hljs-number">20</span>)) wc = <span class="hljs-built_in">WordCloud</span>(max_words = <span class="hljs-number">2000</span>, width = <span class="hljs-number">1600</span>, height = <span class="hljs-number">800</span> ).<span class="hljs-built_in">generate</span>(<span class="hljs-string">" "</span>.<span class="hljs-built_in">join</span>(df.english)) plt.<span class="hljs-built_in">imshow</span>(wc, interpolation = <span class="hljs-string">'bilinear'</span>) </pre></div><p id="d75a">Output —</p><figure id="8f5a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*XTFshD8jb9WlAXCY1XR9WA.png"><figcaption></figcaption></figure><h2 id="33f0">Tokenization, Padding and Split the data into train and test set</h2><div id="b26b"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">tokenize_and_pad</span>(<span class="hljs-params">x, maxlen</span>): <span class="hljs-comment"># a tokenier to tokenize the words and create sequences of tokenized words</span> tokenizer = Tokenizer(char_level = <span class="hljs-literal">False</span>) tokenizer.fit_on_texts(x) sequences = tokenizer.texts_to_sequences(x) padded = pad_sequences(sequences, maxlen = maxlen, padding = <span class="hljs-string">'post'</span>) <span class="hljs-keyword">return</span> tokenizer, sequences, padded x_tokenizer, x_sequences, x_padded = tokenize_and_pad(df.english, maxlen_english) y_tokenizer, y_sequences, y_padded = tokenize_and_pad(df.french, maxlen_french)

<span class="hljs-keyword">def</span> <span class="hljs-title function_">pad_to_text</span>(<span class="hljs-params">padded, tokenizer</span>):</pre></div><div id="459d"><pre>id_to_word = {<span class="hljs-built_in">id</span>: <span class="hljs-built_in">word</span> <span class="hljs-keyword">for</span> <span class="hljs-built_in">word</span>, <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> tokenizer.word_index.items()} id_to_word[<span class="hljs-number">0</span>] = ''</pre></div><div id="7c82"><pre>return <span class="hljs-string"

Options

' '</span><span class="hljs-selector-class">.join</span>(<span class="hljs-selector-attr">[id_to_word[j]</span> <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> padded]) <span class="hljs-function"><span class="hljs-title">pad_to_text</span><span class="hljs-params">(y_padded[<span class="hljs-number">0</span>], y_tokenizer)</span></span> x_train, x_test, y_train, y_test = <span class="hljs-built_in">train_test_split</span>(x_padded, y_padded, test_size = <span class="hljs-number">0.1</span>)</pre></div><h2 id="452b">Build and train the model</h2><div id="c042"><pre><span class="hljs-comment"># Sequential Model</span> model = Sequential() <span class="hljs-comment"># embedding layer</span> model.<span class="hljs-built_in">add</span>(Embedding(english_vocab_size, 256, input_length = maxlen_english, mask_zero = <span class="hljs-literal">True</span>)) <span class="hljs-comment"># encoder</span> model.<span class="hljs-built_in">add</span>(LSTM(256)) <span class="hljs-comment"># decoder</span> <span class="hljs-comment"># repeatvector repeats the input for the desired number of times to change</span> <span class="hljs-comment"># 2D-array to 3D array. For example: (1,256) to (1,23,256)</span> model.<span class="hljs-built_in">add</span>(RepeatVector(maxlen_french)) model.<span class="hljs-built_in">add</span>(LSTM(256, return_sequences= <span class="hljs-literal">True</span> )) model.<span class="hljs-built_in">add</span>(TimeDistributed(Dense(french_vocab_size, activation =<span class="hljs-string">'softmax'</span>))) model.compile(<span class="hljs-attribute">optimizer</span>=<span class="hljs-string">'adam'</span>, <span class="hljs-attribute">loss</span>=<span class="hljs-string">'sparse_categorical_crossentropy'</span>, metrics=[<span class="hljs-string">'accuracy'</span>]) model.summary()</pre></div><div id="bc44"><pre><span class="hljs-attribute">model</span>.fit(x_train, y_train, batch_size=<span class="hljs-number">1024</span>, validation_split= <span class="hljs-number">0</span>.<span class="hljs-number">1</span>, epochs=<span class="hljs-number">10</span>)</pre></div><p id="c60e">Output —</p><div id="f096"><pre>Model: "sequential" <span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span>_ <span class="hljs-section">Layer (type) Output Shape Param #
=================================================================</span> embedding (Embedding) (None, 15, 256) 51200
<span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span>_ lstm (LSTM) (None, 256) 525312
<span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span><span class="hljs-strong"></span>_ repeat<span class="hljs-emphasis">vector (RepeatVector) (None, 24, 256) 0
<span class="hljs-strong">
</span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span></span> lstm<span class="hljs-emphasis">1 (LSTM) (None, 24, 256) 525312
<span class="hljs-strong">
</span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span><span class="hljs-strong"></span><span class="hljs-strong">__</span></span> <span class="hljs-section">time<span class="hljs-emphasis">_distributed (TimeDistri (None, 24, 351) 90207
================================================================= Total params: 1,192,031 Trainable params: 1,192,031 Non-trainable params: 0</span></span></pre></div><h2 id="ec07">Prediction</h2><div id="52a6"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">prediction</span>(<span class="hljs-params">x, x_tokenizer = x_tokenizer, y_tokenizer = y_tokenizer</span>): predictions = model.predict(x)[<span class="hljs-number">0</span>] id_to_word = {<span class="hljs-built_in">id</span>: word <span class="hljs-keyword">for</span> word, <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> y_tokenizer.word_index.items()} id_to_word[<span class="hljs-number">0</span>] = <span class="hljs-string">''</span> <span class="hljs-keyword">return</span> <span class="hljs-string">' '</span>.join([id_to_word[j] <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> np.argmax(predictions,<span class="hljs-number">1</span>)])</pre></div><p id="5577"><b><i>Learnings —</i></b></p><p id="477f">How to perform tokenization and padding, create a pipeline to remove stop-words and implement Recurrent Neural Networks and LSTM.</p><p id="d38a"><b><i>Day 59: Coming soon!</i></b></p><p id="a039">Follow and Stay tuned. Keep coding :)</p><h1 id="a69d">For other projects, tune to —</h1><p id="b31f"><b>Build Machine Learning Pipelines( With Code)</b></p><div id="5b37" class="link-block"> <a href="https://medium.datadriveninvestor.com/build-machine-learning-pipelines-with-code-part-1-bd3ed7152124"> <div> <div> <h2>Build Machine Learning Pipelines( With Code) — Part 1</h2> <div><h3>Complete implementation…</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*KdToBD8RDMBH4jXM.png)"></div> </div> </div> </a> </div><p id="946c"><b>Recurrent Neural Network with Keras</b></p><div id="607d" class="link-block"> <a href="https://medium.datadriveninvestor.com/recurrent-neural-network-with-keras-b5b5f6fe5187"> <div> <div> <h2>Recurrent Neural Network with Keras</h2> <div><h3>Project Implementation and cheatsheet…</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*xs3Dya3qQBx6IU7C.png)"></div> </div> </div> </a> </div><p id="56e1"><b>Clustering Geolocation Data in Python using DBSCAN and K-Means</b></p><div id="2b3e" class="link-block"> <a href="https://medium.datadriveninvestor.com/clustering-geolocation-data-in-python-using-dbscan-and-k-means-3705d9f44522"> <div> <div> <h2>Clustering Geolocation Data in Python using DBSCAN and K-Means</h2> <div><h3>Project Implementation…</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*0uPCZnohdaPCO4NN.png)"></div> </div> </div> </a> </div><p id="a29c"><b>Facial Expression Recognition using Keras</b></p><div id="ccaa" class="link-block"> <a href="https://medium.datadriveninvestor.com/facial-expression-recognition-using-keras-cbdd661a0a54"> <div> <div> <h2>Facial Expression Recognition using Keras</h2> <div><h3>Project Implementation…</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*CGch7hzdjg1fpgKy.jpg)"></div> </div> </div> </a> </div><p id="0db7"><b>Hyperparameter Tuning with Keras Tuner</b></p><div id="6dff" class="link-block"> <a href="https://medium.datadriveninvestor.com/hyperparameter-tuning-with-keras-tuner-3a609d3fd85b"> <div> <div> <h2>Hyperparameter Tuning with Keras Tuner</h2> <div><h3>Project Implementation….</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*jlaEz8AZaptNWHEr.png)"></div> </div> </div> </a> </div><p id="fed8"><b>Custom Layers in Keras</b></p><div id="e4fd" class="link-block"> <a href="https://medium.datadriveninvestor.com/custom-layers-in-keras-de5f793217aa"> <div> <div> <h2>Custom Layers in Keras</h2> <div><h3>Code implementation …</h3></div> <div><p>medium.datadriveninvestor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*1IH67KJadqeqeO01.png)"></div> </div> </div> </a> </div><p id="2ea9"><b><i>That’s it fellas. Peace out and keep coding :)</i></b></p><p id="ec55">Stay Tuned and of-course let me end this post with a quote by Steve Jobs ;)</p><p id="5004" type="7">“You have to be burning with an idea, or a problem, or a wrong that you want to right. If you’re not passionate enough from the start, you’ll never stick it out.”</p></article></body>

Day 58: 60 days of Data Science and Machine Learning Series

How RNN works ( Pic credits : Research Gate)

Welcome back peeps. In this post we are going to understand the basics of RNN and LSTM through a project.

Some of the other best Series —

30 Days of Natural Language Processing ( NLP) Series

30 days of Data Engineering with projects Series

60 days of Data Science and ML Series with projects

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

30 days of Machine Learning Ops

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

Recurrent Neural Network, created in the 1980’s, is a state of the art algorithm for dealing with sequential data by using internal memory to remember important things about the input RNN’s received to precisely predict what’s coming next. RNN’s are popularly used in language translation, natural language processing (nlp), speech recognition, captioning etc.

RNN vs Feed Forward Network ( Pic credits : IBM)
How RNN works ( Pic credits : Research Gate)

Long Short Term Memory networks (LSTM) introduced by Hochreiter & Schmidhuber are special type of Recurrent Neural Networks ( RNN) designed to avoid the long-term dependency problem and can selectively remember patterns for long duration of time.

Pic credits : ResearchGate
Bidirectional LSTM ( Pic credits : Datax)

“The Long Short Term Memory architecture was motivated by an analysis of error flow in existing RNNs which found that long time lags were inaccessible to existing architectures, because backpropagated error either blows up or decays exponentially.

An LSTM layer consists of a set of recurrently connected blocks, known as memory blocks. These blocks can be thought of as a differentiable version of the memory chips in a digital computer. Each one contains one or more recurrently connected memory cells and three multiplicative units — the input, output and forget gates — that provide continuous analogues of write, read and reset operations for the cells. … The net can only interact with the cells via the gates.”

— Alex Graves, et al., Framewise Phoneme Classification with Bidirectional LSTM and Other Neural Network Architectures, 2005.

A good reference to understand the vastness of LSTM —

In this post we are going to implement translator using LSTM.

Let’s dive in!

Import libraries and datasets

from collections import Counter
import operator
import plotly.express as px
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud, STOPWORDS
from sklearn.model_selection import train_test_split
import nltk
import re
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
import gensim
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import STOPWORDS
from tensorflow.keras.preprocessing.text import one_hot, Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, TimeDistributed, RepeatVector, Embedding, Input, LSTM, Conv1D, MaxPool1D, Bidirectional
from tensorflow.keras.models import Model
from jupyterthemes import jtplot
jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)
nltk.download('punkt')
nltk.download("stopwords")

Load Data and Data Preprocessing

# load the data
df_english = pd.read_csv('small_vocab_en.csv', sep = '/t', names = ['english'])
df_french = pd.read_csv('small_vocab_fr.csv', sep = '/t', names = ['french'])
print(df_english.info())
df = pd.concat([df_english,df_french],axis=1)

Output —

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 137860 entries, 0 to 137859
Data columns (total 1 columns):
 #   Column   Non-Null Count   Dtype 
---  ------   --------------   ----- 
 0   english  137860 non-null  object
dtypes: object(1)
memory usage: 1.1+ MB

Remove Punctuations and Word Cloud

def remove_punc(x):
  return re.sub('[!#?,.:";]', '', x)
df['french'] = df['french'].apply(remove_punc)
df['english'] = df['english'].apply(remove_punc)
def guw(x,word_list):
    for word in x.split():
        if word not in word_list:
            word_list.append(word)
df['english'].apply(lambda x:guw(x,english_words))
df['french'].apply(lambda x: guw(x,french_words))
plt.figure(figsize = (20,20)) 
wc = WordCloud(max_words = 2000, width = 1600, height = 800 ).generate(" ".join(df.english))
plt.imshow(wc, interpolation = 'bilinear')

Output —

Tokenization, Padding and Split the data into train and test set

def tokenize_and_pad(x, maxlen):
  #  a tokenier to tokenize the words and create sequences of tokenized words
  tokenizer = Tokenizer(char_level = False)
  tokenizer.fit_on_texts(x)
  sequences = tokenizer.texts_to_sequences(x)
  padded = pad_sequences(sequences, maxlen = maxlen, padding = 'post')
  return tokenizer, sequences, padded
x_tokenizer, x_sequences, x_padded = tokenize_and_pad(df.english, maxlen_english)
y_tokenizer, y_sequences, y_padded = tokenize_and_pad(df.french,  maxlen_french)

def pad_to_text(padded, tokenizer):
id_to_word = {id: word for word, id in tokenizer.word_index.items()}
    id_to_word[0] = ''
return ' '.join([id_to_word[j] for j in padded])
pad_to_text(y_padded[0], y_tokenizer)
x_train, x_test, y_train, y_test = train_test_split(x_padded, y_padded, test_size = 0.1)

Build and train the model

# Sequential Model
model = Sequential()
# embedding layer
model.add(Embedding(english_vocab_size, 256, input_length = maxlen_english, mask_zero = True))
# encoder
model.add(LSTM(256))
# decoder
# repeatvector repeats the input for the desired number of times to change
# 2D-array to 3D array. For example: (1,256) to (1,23,256)
model.add(RepeatVector(maxlen_french))
model.add(LSTM(256, return_sequences= True ))
model.add(TimeDistributed(Dense(french_vocab_size, activation ='softmax')))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train, batch_size=1024, validation_split= 0.1, epochs=10)

Output —

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
embedding (Embedding)        (None, 15, 256)           51200     
_________________________________________________________________
lstm (LSTM)                  (None, 256)               525312    
_________________________________________________________________
repeat_vector (RepeatVector) (None, 24, 256)           0         
_________________________________________________________________
lstm_1 (LSTM)                (None, 24, 256)           525312    
_________________________________________________________________
time_distributed (TimeDistri (None, 24, 351)           90207     
=================================================================
Total params: 1,192,031
Trainable params: 1,192,031
Non-trainable params: 0

Prediction

def prediction(x, x_tokenizer = x_tokenizer, y_tokenizer = y_tokenizer):
    predictions = model.predict(x)[0]
    id_to_word = {id: word for word, id in y_tokenizer.word_index.items()}
    id_to_word[0] = ''
    return ' '.join([id_to_word[j] for j in np.argmax(predictions,1)])

Learnings —

How to perform tokenization and padding, create a pipeline to remove stop-words and implement Recurrent Neural Networks and LSTM.

Day 59: Coming soon!

Follow and Stay tuned. Keep coding :)

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

That’s it fellas. Peace out and keep coding :)

Stay Tuned and of-course let me end this post with a quote by Steve Jobs ;)

“You have to be burning with an idea, or a problem, or a wrong that you want to right. If you’re not passionate enough from the start, you’ll never stick it out.”

Machine Learning
Artificial Intelligence
Programming
Tech
Data Science
Recommended from ReadMedium