<?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 Akash Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Akash Chauhan on Medium]]></description>
        <link>https://medium.com/@aakashchauhan425?source=rss-6550cd7cb5e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pE6gAKpO70kwQ2ZI9lKE6w.jpeg</url>
            <title>Stories by Akash Chauhan on Medium</title>
            <link>https://medium.com/@aakashchauhan425?source=rss-6550cd7cb5e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:36:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aakashchauhan425/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[Creating a Machine Learning Based Web Application Using Django]]></title>
            <link>https://medium.com/data-science/creating-a-machine-learning-based-web-application-using-django-5444e0053a09?source=rss-6550cd7cb5e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5444e0053a09</guid>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Akash Chauhan]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 14:42:53 GMT</pubDate>
            <atom:updated>2020-09-02T17:52:46.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploy your Machine Learning model on the web using Python’s famous Django framework and increase its visibility.</h4><p>This article is for readers who want to deploy their Machine Learning model as a Web Application using Python’s Django framework. For many Data Science and Machine Learning enthusiasts, this could be a good reference for converting their simple .py model files into a much more dynamic and powerful web application that can accept inputs from a user and generate a prediction.</p><p>For the sake of simplicity of the article, we will be focusing more on how to create a ML based web application rather than spending the majority of time in solving a tough Machine Learning problem. Also, this is not a complete django tutorial but a step in the direction towards becoming an AI/ML developer.</p><p>First, we will be creating a simple ML model using the famous titanic dataset and then convert it into a fully functional, dynamic web based application.</p><h3>Developing Machine Learning Model</h3><p>As mentioned above, we will be working on the famous titanic dataset that is used to predict the survival of the passengers based on their different attributes (Passenger class, Sex, Age, Fare etc.). Since this a binary classification problem, we would be using Logistic Regression algorithm (a powerful yet simple machine learning algorithm) for creating our model.</p><p>The below code can be referred to create the classification model.</p><blockquote>Note: Creating a Machine Learning Model is a complete detailed task in itself that contains multiple steps (such as Data Pre-processing, EDA, Feature Engineering, Model Development, Model Validation, Tuning Hyperparameters). Here we are skipping all those steps since we are much more interested in using this model for powering our web based application.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346d286029987f4b92490a24f67feef7/href">https://medium.com/media/346d286029987f4b92490a24f67feef7/href</a></iframe><p>Once we have created our final model, we are simply storing this model as a <strong><em>model.sav </em></strong>file (using pickle). Also, notice we are storing our scaler object as a <strong><em>scaler.sav </em></strong>file (since we will be using this same scaling object for transforming our user input to the same level as training data before feeding it to the model).</p><h3><strong>Creating our own Django Project</strong></h3><p>Before creating our django project, first we need to install django into our development machine using the below command.</p><blockquote><strong>pip install django</strong></blockquote><p>This will automatically install all the dependencies that the django framework required in order to function properly. If this command is not working for you, please refer to the below link-</p><p><a href="https://docs.djangoproject.com/en/3.1/topics/install/">How to install Django | Django documentation | Django</a></p><p>Once you have installed the django, you need to open command prompt on your machine (terminal on Ubuntu or Mac) and follow the below steps-</p><ol><li><strong>cd Desktop</strong> (you can traverse to whichever location you want to create your project folder)</li><li><strong>mkdir Titanic_Survial_Prediction</strong> (you can choose whatever name you want to use for your web application)</li><li><strong>cd Titanic_Survial_Prediction</strong> (cd into the folder you just created in the step above)</li><li><strong>django-admin startproject Titanic_Survial_Prediction_Web</strong> (this command will automatically create a django project with name <em>Titanic_Survial_Prediction_Web </em>inside your main project folder)</li><li><strong>cd Titanic_Survial_Prediction_Web</strong> (cd into the django project created in the step above)</li><li>Now if you followed the above steps correctly, just type in <strong>python manage.py runserver </strong>into your command prompt screen and then copy the link that appear on the command prompt (<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>) into a web browser. As soon as you hit enter, you would be able to see the below screen</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fH8bfS0HW1-weF5B4TxFTg.png" /><figcaption>Django default home view</figcaption></figure><p>If the above web page also appears for you, then you have successfully completed the first step in creating your own django web application.</p><p>If for some people this web page is not appearing, please refer to the above steps once again and see if in case you missed anything.</p><p>Now using any IDE (PyCharm, Atom etc.) open your django project (<strong>Titanic_Survial_Prediction_Web</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*thVRCcuKungkn1jq7Ho1mQ.png" /><figcaption>Default Django Project Structure</figcaption></figure><p>Now inside the same folder where your urls.py is present, create a new python file with name <strong><em>‘views.py’. </em></strong>This views file would be responsible for getting the input from any user using a web page, using the same input for generating predictions and then showing this prediction back to the user using a web page.</p><blockquote>Also, we need to move our ‘model.sav’ and ‘scaler.sav’ file inside the same folder as urls.py.</blockquote><p>Before moving any further, lets first complete the configuration for our django project. Inside our main project folder, create an empty folder by the name <strong><em>‘templates’</em></strong> (you can use any name but its recommended to follow a defined framework naming convention). This folder will be holding all out html files that we would be using in our project.</p><p>Now open the setting.py file and add ‘templates’ (or whatever name you have given to your html files folder) to the highlighted ‘DIRS’ list inside the ‘TEMPLATES’ list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nr_xO3AeOiWGVdK84zMKeg.png" /><figcaption>Final Project Structure</figcaption></figure><p>Now inside the urls.py file add the below code for configuring the urls for our website (different urls for different web pages).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87efca0458928ffae9fde34d71786525/href">https://medium.com/media/87efca0458928ffae9fde34d71786525/href</a></iframe><p>We have first imported our views file inside the urls.py file and then inside the urlpatterns list added path for our home page (the default page whenever we open our web application instead of django default view) and the result page (for displaying the results to user) along with there respective names (using which they can be referred inside our html files).</p><p>Now we need to define these two functions inside our views.py file. Along with these two, we will also create a getPredictions function that would be able to generate predictions by loading our pre-trained model.</p><p>The below code can be referred to do this task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ddd25970a3fc1a4cb80ed6ffea7fb42/href">https://medium.com/media/1ddd25970a3fc1a4cb80ed6ffea7fb42/href</a></iframe><p>the result method is responsible for collecting all the information that the user have entered and then return the result as a key-value pair.</p><blockquote>Note: It is always recommended to create getPredictions method inside a separate python file and then import it inside our views.py file. Here for keeping things simple and straight forward, we have made the function inside the views.py file.</blockquote><p>Now that we have worked on the backend logic, lets create our web pages to accept the input from user through forms and display results.</p><p>Inside the “<strong><em>templates”</em></strong> folder, create an index.html file. This index.html would be our home page and will have our form that we will use for getting input from our user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f255d50ebc262fd4bdc124f09081cbf9/href">https://medium.com/media/f255d50ebc262fd4bdc124f09081cbf9/href</a></iframe><p>There are couple of things we need to understand here before moving forward.</p><ol><li>Forms action parameter → View that collects the form data, generate predictions using this data and then redirects to the webpage with result. For django we have a specific way of doing this- <strong><em>action = “{% urls ‘name_of_url’ %}”</em></strong>. In our case the name of our url is result (as we have already provided this in our urls.py file).</li><li>Also, along with this we need to provide a <strong><em>{% csrf_token %}</em></strong> (i.e. cross site reference forgery token) which makes data handling in django more secure. This part is mandatory and hence it should always be the first line inside your form tags.</li></ol><blockquote>Note: <strong>{% .. %}</strong> are called scripting tags.</blockquote><p>Once we have created our index.html file, we then need to create our result.html that will display the prediction to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19cfd32a4d33acc204cbaeb1fb3e3451/href">https://medium.com/media/19cfd32a4d33acc204cbaeb1fb3e3451/href</a></iframe><p>Inside the “<strong>{{ }}</strong>” tags, we specify the name of the key which contains our result (in our case it is result).</p><p>Once you have completed all these steps, press CTRL + C in your command prompt to stop the server and then restart it using “python manage.py runserver” command. Now reopen the link in your browser. This time the default page would be the index.html webpage which have our input form.</p><p>Once you fill in the respective data and submit the form, you will be redirected to the result.html page which will display the prediction for your input data.</p><p>So this is how, we create a simple yet powerful ML based django web application that is dynamic in nature (accepts input from user) and make predictions based on Machine Learning model.</p><p>If you want to learn more about django, please refer to the django documentation (link below).</p><p><a href="https://www.djangoproject.com/">Django</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5444e0053a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-a-machine-learning-based-web-application-using-django-5444e0053a09">Creating a Machine Learning Based Web Application Using Django</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[Natural Language Processing: Intelligent Search through text using Spacy and Python]]></title>
            <link>https://medium.com/data-science/natural-language-processing-document-search-using-spacy-and-python-820acdf604af?source=rss-6550cd7cb5e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/820acdf604af</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Akash Chauhan]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 09:48:50 GMT</pubDate>
            <atom:updated>2020-09-06T09:12:01.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extract useful information from text using Python and Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuHKUK0OzsMsZX7iduBwOA.png" /></figure><p>Searching through text is one of the key focus areas of Machine Learning Applications in the field of Natural Language.</p><p><strong><em>But what if we have to search for multiple keywords from a large document (100+ pages). Also, what if we have do a contextual search (searching for similar meaning keywords) with in our document!</em></strong><em> — </em>The conventional ‘CTRL + F’ solution would either take long long hours to accomplish this task (or in case of contextual search, it will not be able to find any meaning text).</p><p>This article will help the readers understand how we can use Machine Learning to solve this problem using Spacy (a powerful open source NLP library) and Python.</p><h3>Data Pre-Processing</h3><p>The initial step in any building any machine learning-based solution is pre-processing the data. In our case, we will be pre-processing a PDF document using PyPDF2 package in Python and then convert the entire text into a Spacy document object. For readers who have not worked on Spacy — It is an advanced open source library in Python used for various NLP tasks. For users who are interested in learning more about Spacy, please refer this link for reading the documentation and learning more about Spacy — <a href="https://spacy.io/">https://spacy.io/</a></p><p>We will first load the PDF document, clean the text and then convert it into Spacy document object. The following code can be used to perform this task-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f31e2bbcbbca57f92a700d301442bf3/href">https://medium.com/media/3f31e2bbcbbca57f92a700d301442bf3/href</a></iframe><p>First we will have to load Spacy’s ‘<strong>en_core_web_lg</strong>’ model which is a pre-trained English language model available in Spacy. Spacy also provides support for multiple languages (more can be found in the documentation link). Also, Spacy has multiple variations for models (small, medium and large) and for our case we will be working with large model since we have to work with word vectors which is only supported with the large model variant.</p><p>The ‘<strong>setCustomBoundaries()</strong>’ is used as a customer sentence segmentation method as opposed to the default option. The same method can be modified depending upon the document we are dealing.</p><p>Once we have the Spacy’s document object ready, we can move to the next part of handling the input query (keywords) that we need to search for in the document.</p><h3>Handling Query — Finding Similar Keywords</h3><p>Before moving on to the coding part, let&#39;s look at the broader approach we are following in order to get more accurate search results from the document we are searching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5d61hBn70Me4CdK2WaX6g.png" /><figcaption>Process Workflow</figcaption></figure><p>Up until the data preprocessing stage we have already converted our PDF document text to Spacy’s document object. Now we also have to convert our keywords to Spacy’s document object, convert them into their equivalent vector form ((300, ) dimension) and then finding similar keywords using the cosine similarity. At the end we will have an exhaustive list of similar keywords along with the original keywords that we can now search through our document to generate accurate results.</p><p>Refer the below code to perform this task-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445918e566273529a2cc5350d0acd3f4/href">https://medium.com/media/445918e566273529a2cc5350d0acd3f4/href</a></iframe><p>Now that we have found contextually similar words to our original keywords, let&#39;s work on the final searching part.</p><h3><strong>Searching Keywords through Text</strong></h3><p>For searching, we would be using the PhraseMatcher class of Spacy’s Matcher class. At this point, it is important to remember that Spacy’s document object is not as same as a simple python string and hence we cannot directly use if then else to find the results.</p><p>Refer to the below code to perform this task-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/635d3ac4d57b504aa667182fb8cd4683/href">https://medium.com/media/635d3ac4d57b504aa667182fb8cd4683/href</a></iframe><p>The above code will search for every keyword we have through the entire text and will return us the entire sentence wherever it has found a match.</p><p>The above code will generate the following output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3kDqR5UU-RLRYogaxEjug.png" /><figcaption>Search Output Screenshot</figcaption></figure><p>You can increase or decrease the number of similar keywords that you want to find for any original keywords. Also, once you get the results in a dataframe, you can simply add some more logics for ranking the results (give more weightage to exact keyword match and so on).</p><blockquote>Note: Increasing number of Similar Keywords to large number may increase the computational cost of the overall program and hence should be chosen wisely.</blockquote><p>So this is how you can create your own ML based Python program for performing search through any text.</p><p>In case of any other input source (Photographs, Web pages etc.) you just need to customize the data preprocessing part (OCR, Web Scraping etc.) and the rest of the logic should perform just fine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820acdf604af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/natural-language-processing-document-search-using-spacy-and-python-820acdf604af">Natural Language Processing: Intelligent Search through text using Spacy and Python</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[Generating Captions for Images using Neural Networks]]></title>
            <link>https://levelup.gitconnected.com/generating-captions-for-images-using-neural-networks-2b0ecf657335?source=rss-6550cd7cb5e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b0ecf657335</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Akash Chauhan]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 09:19:58 GMT</pubDate>
            <atom:updated>2020-08-15T10:11:00.207Z</atom:updated>
            <content:encoded><![CDATA[<p>We all know that Neural Networks can do so much in terms of replicating a human brain while performing certain tasks. The applications of Neural Networks in Computer Vision and Natural Language Generation has been truly remarkable.</p><p>This article will introduce the readers to one such application of Neural Networks and let the readers understand how we can actually generate Captions (descriptions) for Images using a Hybrid Network of CNNs and RNNs (LSTM). The dataset that we are using for this task is the popular <em>flickr 8k Image Dataset </em>which is the benchmark data for this task and can be accessed by the below link<em>.</em></p><p><em>Kaggle — </em><a href="https://www.kaggle.com/adityajn105/flickr8k">https://www.kaggle.com/adityajn105/flickr8k</a></p><blockquote>Note : We will be splitting our dataset as 7k for training and 1k for testing purpose.</blockquote><p>We will first discuss what are the different components (layers) and their function in our Hybrid Neural Network. Along with this, we will also look at the practical implementation of developing our Hybrid Neural Network using Tensorflow, Keras, and Python.</p><h3><strong>Overall Architecture of Neural Network</strong></h3><p>Let&#39;s look at the overall architecture of our Neural Network that we will be using for generating captions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3JoyOelmtyowMuoSIkadg.png" /><figcaption>Neural Network Architecture (Source: Google Images)</figcaption></figure><p>In simple terms, the above Neural Network has 3 main components (Sub Networks), each assigned with a specific task namely —The Convolutional Network (for extracting features from Images), The RNN (LSTM) (for text generation) and A Decoder (for combining both networks).</p><p>Now let&#39;s talk about each component in detail and understand their working.</p><h3><strong>Image Feature Extractor</strong></h3><p>For generating features from an Image we will be using a Convolutional Neural Network with just a bit of modification. Let&#39;s look at a ConvNet that is used for Image Recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXP94kNxfDlyqCaTQg9pEg.jpeg" /><figcaption>CNN Architecture (Source: Bing Images)</figcaption></figure><p>As you can see, our CNN has two sub-networks —</p><ol><li><strong>Feature Learning Network</strong> — Network responsible for generating feature maps from the Images (Network of multiple Convolution &amp; Pooling Layers).</li><li><strong>Classification Network</strong> — Fully connected Deep Neural Network responsible for Image classification (Network of multiple Dense Layers and a single Output Layer).</li></ol><p>Since we are only interested in extracting features from Images and not their classification, we are only interested in the Feature Learning Part of the CNN and that is how we can extract features from the Images.</p><p>Below code can be used to extract features from any set of images-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0181cff98fe7ba563534dc38ec49802a/href">https://medium.com/media/0181cff98fe7ba563534dc38ec49802a/href</a></iframe><p>Yes, anyone can build their own Image Feature Extractor using the above code, but there is catch…</p><p><strong><em>The above model is too simple to extract each and every important detail from our set of images and hence will impact the performance of our overall model. Also, making model too complex (multiple Dense Layers with high number of Neurons) is also challenging due to the non-availability of high performing GPUs and systems.</em></strong></p><p>To solve this problem, we have very popular pre-trained CNN models (VGG-16, ResNet50 etc. developed by scientists of different universities and organizations) that are available in Tensorflow and can be used to extract features from images. <strong>Just remember to remove the output layer from the model before using it for Feature Extraction.</strong></p><p>The below code will let you understand how to use these pre-trained models in Tensorflow for extracting features from images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4064eb89e5d9c36c6af68f63b0ef26b8/href">https://medium.com/media/4064eb89e5d9c36c6af68f63b0ef26b8/href</a></iframe><p>As you can see below, if you execute the above code you will see that our image feature is nothing but a numpy array of shape — (18432,)</p><pre>image_feature_dictionary[list(image_feature_dictionary. Keys())[0]].shape</pre><pre>(18432,)</pre><p>Next we will develop our LSTM Network (RNN) for generating captions for images.</p><h3>LSTM for generating Captions</h3><p>Text generation is one of the most popular applications of LSTM Networks. LSTM cells (the basic building block of LSTM Networks) have the capability to generate output basis on the output of previous layers i.e. it retains the output of previous layers (the memory) and uses that memory to generate (predict) the next output in the sequence.</p><p>For our dataset, we have 5 captions for each images i.e. 40k captions in total.</p><p>Let&#39;s look at our dataset-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*LO2YGullmHu-iFUtVWL_EA.jpeg" /><figcaption>Image from Flickr8k dataset</figcaption></figure><p><strong>Captions for Image</strong></p><ol><li><strong><em>A child in a pink dress is climbing up a set of stairs in an entry way.</em></strong></li><li><strong><em>A girl going into a wooden building.</em></strong></li><li><strong><em>A little girl climbing into a wooden playhouse.</em></strong></li><li><strong><em>A little girl climbing the stairs to her playhouse.</em></strong></li><li><strong><em>A little girl in a pink dress going into a wooden cabin.</em></strong></li></ol><p>As seen, all the captions describe the Image quite well. Our task now is to design an RNN that could replicate this task for any similar set of images.</p><p>Coming back to the original task, we first have to look at how an LSTM Network generates text. For an LSTM network caption is nothing but a long sequence of individual words (encoded as digits) placed together. Using this information, it tries to predict the next word in the sequence based on the previous words (Memory).</p><p>In our case, since the captions can be of varying length, we first need to specify the starting and ending of every caption. Let us see what this actually means-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccAxD4C8u86gE4Z_-shFPw.jpeg" /><figcaption>Preparing Training Dataset</figcaption></figure><p>First we will be adding &lt;start&gt; and &lt;end&gt; to each and every caption in our dataset. After that we will tokenize each &amp; every caption in our training dataset before creating our final vocabulary. For training our model, we will be dropping tokes (words) from our vocabulary that has frequency less than or equal to 10. This step is added to improve the generic performance of our model and to prevent it from overfitting the training dataset.</p><p>The following code can be used to implement this-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7102dc666a872c9651e04bdb724e5ab5/href">https://medium.com/media/7102dc666a872c9651e04bdb724e5ab5/href</a></iframe><p>The above code will generate the below output —</p><pre>train_image_captions[list(train_image_captions. Keys())[150]]<br></pre><pre>[&#39;&lt;start&gt; A brown dog chases a tattered ball around the yard . &lt;end&gt;&#39;,<br> &#39;&lt;start&gt; A brown dog is chasing a tattered soccer ball across a low cut field . &lt;end&gt;&#39;,<br> &#39;&lt;start&gt; Large brown dog playing with a white soccer ball in the grass . &lt;end&gt;&#39;,<br> &#39;&lt;start&gt; Tan dog chasing a ball . &lt;end&gt;&#39;,<br> &#39;&lt;start&gt; The tan dog is chasing a ball . &lt;end&gt;&#39;]</pre><p>Once we have loaded in the captions, we will first tokenize everything using spacy and Tokenizer (from <em>tensorflow.preprocessing.text</em> class).</p><p>Tokenization is nothing but breaking down a sentence into different words while removing special characters, lowercasing everything. Result is we have a corpus of meaningful words (tokens) in the sentence that we can further encode before using it as an input to our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b60c850cbf0e2307344129a1a95165b/href">https://medium.com/media/0b60c850cbf0e2307344129a1a95165b/href</a></iframe><p>The above code will generate a dictionary with every token encoded as an integer and vice versa. The sample output looks like below —</p><pre>tokenizer.word_index </pre><pre>{&#39;a&#39;: 1,<br> &#39;end&#39;: 2,<br> &#39;start&#39;: 3,<br> &#39;in&#39;: 4,<br> &#39;the&#39;: 5,<br> &#39;on&#39;: 6,<br> &#39;is&#39;: 7,<br> &#39;and&#39;: 8,<br> &#39;dog&#39;: 9,<br> &#39;with&#39;: 10,<br> &#39;man&#39;: 11,<br> &#39;of&#39;: 12,<br> &#39;two&#39;: 13,<br> &#39;black&#39;: 14,<br> &#39;white&#39;: 15,<br> &#39;boy&#39;: 16,<br> &#39;woman&#39;: 17,<br> &#39;girl&#39;: 18,<br> &#39;wearing&#39;: 19,<br> &#39;are&#39;: 20,<br> &#39;brown&#39;: 21.....}</pre><p>After this, we need to find the <strong>length of our vocabulary and length of longest caption. Let&#39;s see the significance of both of these measures in creating our model.</strong></p><ol><li><strong>Vocabulary Length</strong> → Length of Vocabulary is basically the count of unique words in our corpus. Also, the neurons in our output layers would be equal to <strong>Vocabulary Length + 1</strong> <em>(+ 1 is for extra whitespace due to padding sequence)</em> since at every iteration we need our model to generate a new word from our corpus of words.</li><li><strong>Maximum Caption Length</strong> → Since in our dataset, we have captions of varying length even for the same image. Let&#39;s try to understand this in a bit detail-</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*i19g_Cl5k03OT-iKMwZmxA.png" /><figcaption>Captions Sequence Length</figcaption></figure><p>As you can see every caption is of different length and hence we cannot use these as an input to our LSTM model. For fixing this problem, we fill pad every caption to the length of maximum caption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Lv4dkrjtVMw-jXsRBfTdnQ.png" /><figcaption>Padded Sequence</figcaption></figure><p>Notice every sequence has a set of extra 0s to increase its length to the maximum sequence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf71c5f35a6bca1e8fb1b159788e4b9/href">https://medium.com/media/daf71c5f35a6bca1e8fb1b159788e4b9/href</a></iframe><p>Next we need to create training dataset for our model specifying the input and output. For our problem we have 2 inputs and 1 output. Let&#39;s see this in a bit detail for understanding-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*MhI3macM9r6x6xKlbosppQ.png" /><figcaption>Training Dataset</figcaption></figure><p>For every image we have-</p><ol><li><strong>Input Image Feature (X1)</strong> → Numpy array of shape (18432, ) extracted using ResNet50 Model</li><li><strong>Input Sequence (X2)</strong> → This requires a bit more explanation. Every caption is nothing but a list of sequence and our model is trying to predict to next best element in the sequence. Hence for every caption, we will first start of with the first element in the sequence and the corresponding output to that element would be the very next element. In the next iteration, the output of previous iteration would become the new input along with the input of previous iteration (the memory) and this goes on until we have reached the end of sequence.</li><li><strong>Output (y)</strong> → The next word in the sequence.</li></ol><p>The below code can be used to implement the above logic for creating training dataset-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb97dc2edac3a3ac811540ddaf847136/href">https://medium.com/media/fb97dc2edac3a3ac811540ddaf847136/href</a></iframe><h3><strong>Combining the two Sub Networks</strong></h3><p>Now that we have developed our two sub networks (Image Feature Extractor &amp; LSTM for generating captions), lets combine these two to create our final model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*9t0uK6vJ28m9LYL4DyqGkQ.png" /><figcaption>Final Model Architecture</figcaption></figure><p>For any new image (must be similar to ones used during training) our model will generate the caption based on the knowledge it has acquired while training over similar set of images and captions.</p><blockquote>Note: For good results, the testing images should be similar to the ones used during training.</blockquote><p>The following code creates our final model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54619cc217f0feea9f741f9938ff6b5c/href">https://medium.com/media/54619cc217f0feea9f741f9938ff6b5c/href</a></iframe><p>Before compiling the model, we need to add weights to our embedding layer. This is done by creating word embeddings (representation of token in a high dimensional vector space) for every token present in our corpus (vocabulary). There are some very popular word embedding models that can be used for this purpose (GloVe, Gensim Word Embedding Models etc.).</p><p>We will be using Spacy’s inbuilt “en_core_web_lg” model for creating vector representation of our token (i.e. every token would be represented as a (300,) numpy array).</p><p>The following code can be used to create word embeddings and add it to our model embedding layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d48a22b77a08a65a19cbfbae51a49cec/href">https://medium.com/media/d48a22b77a08a65a19cbfbae51a49cec/href</a></iframe><p>Now that we have created everything, we just have to compile and train our model.</p><blockquote><strong>Note : Training time of this network would be very high (with high number of epochs) due to complex nature of our task</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89db94ee5ad8ed544bc73ba9cecd2d35/href">https://medium.com/media/89db94ee5ad8ed544bc73ba9cecd2d35/href</a></iframe><p>For generating new captions, we first need to convert an image into a numpy array of same dimension as images of training dataset (18432,) and using &lt;start&gt; as the input to model .</p><p>During sequence generation, we would terminate the process as soon as we have encountered a &lt;end&gt; in our output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133dc5f80d1109bcf3afdc5ec60882c9/href">https://medium.com/media/133dc5f80d1109bcf3afdc5ec60882c9/href</a></iframe><p>Now lets check the output of our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*ulg85KwidtQb8WSp8BLmuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*OoLsEIIWzXJmH7qEsOGgNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*9KUnZcGwlbv2_X7YvbiNkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*tpaX1wqUO0BxnidQwnAZrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*jSahQnd1oWWO6toKcEvYtw.png" /></figure><p>As you can see our model generates good enough captions for some images but for some the captions are not explanatory.</p><p>This can be improved by increasing the epochs, training data, adding layers to our final model but all this requires high end machines (GPUs) for processing.</p><p>So this is how we can generate captions for images using our own deep learning model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b0ecf657335" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/generating-captions-for-images-using-neural-networks-2b0ecf657335">Generating Captions for Images using Neural Networks</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional Neural Networks for Multiclass Image Classification — A Beginners Guide to Understand]]></title>
            <link>https://medium.com/swlh/convolutional-neural-networks-for-multiclass-image-classification-a-beginners-guide-to-6dbc09fabbd?source=rss-6550cd7cb5e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dbc09fabbd</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Akash Chauhan]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 13:49:42 GMT</pubDate>
            <atom:updated>2020-07-11T16:52:59.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Convolutional Neural Networks for Multiclass Image Classification — A Beginners Guide to Understand CNN</h3><p>Convolutional Neural Network (<strong>ConvNet or CNN</strong>) is a class of deep neural networks most commonly used for analyzing visual imagery. Convolution layers are the building blocks of the CNNs.</p><p>A convolution is the simple application of a filter to an input that results in an activation. Repeated application of the same filter to an input results in a map of activations called a feature map, indicating the locations and strength of a detected feature in an input, such as an image.</p><p>What makes CNNs so powerful and useful is that they can generate excellent predictions with minimal image preprocessing. Also, the CNNs are immune to spatial variance and hence are able to detect features anywhere in the input images. This article will let the readers understand how CNNs work along with its Python implementation using Tensorflow and Keras libraries to solve a multiclass classification problem.</p><h3>CNN Architecture</h3><p>Before talking about CNN Architecture, lets understand how human brain actually recognizes an image using an example. Try and recognize this image..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OodO5EEzJvY1WEuBQLQ0mw.jpeg" /><figcaption>Example Image</figcaption></figure><p>We all know its an image of dog and even with just a glimpse of this image or any other similar image we would always know that this a dog, but how do we know this?? How are we so sure and correct all the time?</p><p>The reason is that with every evolution step in Humankind, our brain has learned to identify certain key features (big ears, hairy face, long mouth, large teeth etc.) in an image and basis of these feature it would just recognize the above image as a Dog Image.</p><p>This is what a CNN tries to mimic for classifying Images.</p><p>Below is the Architecture Diagram of a Simple Convolutional Neural Network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXP94kNxfDlyqCaTQg9pEg.jpeg" /><figcaption>CNN Architecture — Source (Bing Images)</figcaption></figure><p>As you can see, a Convolutional Neural Network can be interpreted as two sub networks where each sub network is responsible for performing a specific task. These Subnetworks are — <em>Feature Learning Net(The Eyes of our CNN) and Classification Net (The Brain of our CNN)</em>. Together they perform an approximate function of how a Human Brain classifies the Images.</p><ol><li><strong>Feature Learning</strong> — The Feature Learning part mainly consist of Convolutional Layers and Pooling Layers . The number of Convolutional and Pooling Layers in a CNN are usually more than one and are directly dependent on the nature of the classification problem ( More complex problem would require more Convolutional and Pooling layers for feature extractions).</li><li><strong>Classification</strong> — The classification part is responsible for classifying the images to their respective categories based on the features (Feature Maps) that Feature Learning part has extracted (created) from the image. The Classification part usually consist of a Flatten Layer and a network of Fully Connected Hidden Layers.</li></ol><h3><strong>Feature Learning</strong></h3><p>The Feature Learning Net consists of two layers — The Convolution Layer and The Pooling Layer. Lets talk about the Convolution Layer first.</p><p>The <strong>Convolution Layer</strong> or sometimes referred to as a decomposition layer is responsible for decomposing the Image into various feature maps using different kernels. The resulting Feature Map is a convolved Image generated from our original Image. Lets understand this with the below example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*RdWgEO6cEDV3GnJRbbbypw.png" /><figcaption>Feature Map from Image</figcaption></figure><p>For simplicity, <strong>a kernel is nothing but a filter</strong> which when applied on the image creates a new image (feature map) that has all the essential features of the original image but rejects the redundant information.</p><p>This is why <strong>Convolution is also referred to as Decomposition sometime</strong>.</p><p>The next layer in our network is the <strong>Pooling Layer</strong> which is responsible for approximating the feature maps that were created using the Convolutional layers. The Pooling Layer is also responsible for accounting any spatial variance that might effect the performance of our network in Image Recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*GbivCYfABKxOswjDOrDPwA.png" /><figcaption>Max Pooling</figcaption></figure><p><em>This is how Pooling Layer functions in a ConvNet. There are many types of Pooling layers (Mean, Max etc.). For our ConvNet we are using Max Pooling.</em></p><p>The following code will help you understand how to add a convolution layer and a Pooling Layer to our CNN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680521c884e26d53654abbec901e1729/href">https://medium.com/media/680521c884e26d53654abbec901e1729/href</a></iframe><p>Following are the arguments of the Conv2D function-</p><ol><li><strong>filters</strong> — Number of different filters (feature detectors) that will be applied on the original image to create feature maps. Different types of filters are Edge Detection Filter, Blur Filter etc.</li><li><strong>kernel_size</strong> — Dimension of the convolution filter (n x n) matrix.</li><li><strong>Activation</strong> — The activation function for the neurons. A general thumb of rule is to use a <strong>Rectifier Linear Unit (Relu)</strong> function as an activation function for every layer besides the output layer. The Relu function also adds non linearity to our network which is highly required to eliminate any linear relationships that does exist in the feature maps.</li><li><strong>Input Layer</strong> — Takes the shape of the Input Images and number of channels (3 for color and 1 for B/W image).</li></ol><p>Following are the arguments of the MaxPool2D function-</p><ol><li><strong>pool_size</strong> — Dimension of pooling matrix (m x m)</li><li><strong>strides </strong>— The number of rows and columns traversed per slide.</li></ol><h3>Classification</h3><p>The Classification Net consists of two layers — The Flatten Layer and The Fully Connected Layers. The Flatten layer is used to convert the 2D output array from Pooling Layer or Convolutional layer to 1D array (Flattening the input) before feeding it to the fully connected layers.</p><p>The fully connected layers are a network of serially connected dense layers that would be used for classification. In a fully connected network every neuron from layer1 is connected to every neuron in layer2. Usually for Computer Vision Application, the dense layers have large numbers of neurons (256, 128 etc.) for achieving higher accuracy in our predictions.</p><p>The following code can be used to add a Flatten and a network of fully connected layers to our CNN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1761a04f5c41ca27a77ee979e7c6521/href">https://medium.com/media/a1761a04f5c41ca27a77ee979e7c6521/href</a></iframe><p>The final layer in our CNN is the output layer. The number of Neurons in this layer is 1 (for regression and binary classification) or equal to number of distinct classes in a multiclass classification task.</p><p>After adding the output layer to the network, the next step is to compile the model and then train it on a training dataset.</p><p>For compiling the model, we have to specify the following parameters —</p><ol><li><strong>optimizer</strong> → Algorithm used for updating the weights of our CNN. “Adam” (Gradient Descent) is one of the popular optimizer used for updating weights.</li><li><strong>loss</strong> → Cost function used for calculating the error between the predicted &amp; actual value. In our case we will be using “categorical_crossentropy” since we are dealing with multiclass classification. In case of binary classification we have to use “binary_crossentropy” as loss function.</li><li><strong>metrics</strong> → Evaluation metric for checking performance of our model.</li></ol><p>For fitting the model, we have to specify the following parameters —</p><ol><li><strong>batch_size</strong> → Number of images that will be used by to train our CNN model before updating the weights using back propagation.</li><li><strong>epochs</strong> → An <strong>epoch</strong> is a measure of the number of times all of the training images are used once to update the weights.</li></ol><p>Till now we have learnt about the different components of a Convolutional Neural Network. Let us now develop our own CNN for image classification.</p><p>The problem at our hand is image data of Nature Scenes around the world. The Data contains around 25k images of size 150x150 distributed under 6 categories.</p><blockquote>{‘buildings’ -&gt; 0, ‘forest’ -&gt; 1, ‘glacier’ -&gt; 2, ‘mountain’ -&gt; 3, ‘sea’ -&gt; 4,<br>‘street’ -&gt; 5 }</blockquote><p>Our goal is to develop a CNN that can accurately classify the new images into one of these category.</p><h3>Developing a CNN for Multiclass Image Classification</h3><p>Before training our CNN on training set images, we first have to apply image augmentation. The reason for performing image augmentation is to eliminate any chance of overfitting our model (training accuracy &gt;&gt; testing accuracy).</p><p>Image Augmentation can be applied using <strong>ImageDataGenerator</strong> function of <strong>keras.preprocessing.image</strong> class. Along with augmentation, we also need to rescale our images (every pixel value becomes a value between 0 &amp; 1).</p><p>The following code can be used to develop a CNN for image classification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69bd9265fd9fb07f6e2144ddb645cb47/href">https://medium.com/media/69bd9265fd9fb07f6e2144ddb645cb47/href</a></iframe><p>The following is the output of the model while training.</p><pre>Epoch 1/30<br>439/439 [==============================] - 52s 119ms/step - loss: 1.1012 - accuracy: 0.5655 - val_loss: 0.9319 - val_accuracy: 0.6333<br>Epoch 2/30<br>439/439 [==============================] - 53s 121ms/step - loss: 0.8520 - accuracy: 0.6773 - val_loss: 0.7698 - val_accuracy: 0.7140<br>Epoch 3/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.7336 - accuracy: 0.7292 - val_loss: 0.7235 - val_accuracy: 0.7243<br>Epoch 4/30<br>439/439 [==============================] - 53s 120ms/step - loss: 0.6590 - accuracy: 0.7579 - val_loss: 0.6601 - val_accuracy: 0.7593<br>Epoch 5/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.6014 - accuracy: 0.7832 - val_loss: 0.6266 - val_accuracy: 0.7777<br>Epoch 6/30<br>439/439 [==============================] - 52s 118ms/step - loss: 0.5648 - accuracy: 0.7964 - val_loss: 0.6243 - val_accuracy: 0.7740<br>Epoch 7/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.5266 - accuracy: 0.8109 - val_loss: 0.5804 - val_accuracy: 0.7880<br>Epoch 8/30<br>439/439 [==============================] - 53s 120ms/step - loss: 0.4994 - accuracy: 0.8195 - val_loss: 0.5344 - val_accuracy: 0.8097<br>Epoch 9/30<br>439/439 [==============================] - 52s 120ms/step - loss: 0.4811 - accuracy: 0.8253 - val_loss: 0.5347 - val_accuracy: 0.8140<br>Epoch 10/30<br>439/439 [==============================] - 53s 120ms/step - loss: 0.4729 - accuracy: 0.8292 - val_loss: 0.5352 - val_accuracy: 0.8113<br>Epoch 11/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.4439 - accuracy: 0.8407 - val_loss: 0.5560 - val_accuracy: 0.8010<br>Epoch 12/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.4406 - accuracy: 0.8409 - val_loss: 0.5026 - val_accuracy: 0.8273<br>Epoch 13/30<br>439/439 [==============================] - 54s 124ms/step - loss: 0.4236 - accuracy: 0.8459 - val_loss: 0.5692 - val_accuracy: 0.8107<br>Epoch 14/30<br>439/439 [==============================] - 52s 118ms/step - loss: 0.4188 - accuracy: 0.8499 - val_loss: 0.4980 - val_accuracy: 0.8190<br>Epoch 15/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.3954 - accuracy: 0.8590 - val_loss: 0.5697 - val_accuracy: 0.7963<br>Epoch 16/30<br>439/439 [==============================] - 54s 123ms/step - loss: 0.3771 - accuracy: 0.8643 - val_loss: 0.5335 - val_accuracy: 0.8127<br>Epoch 17/30<br>439/439 [==============================] - 53s 120ms/step - loss: 0.3766 - accuracy: 0.8616 - val_loss: 0.5396 - val_accuracy: 0.8120<br>Epoch 18/30<br>439/439 [==============================] - 52s 118ms/step - loss: 0.3639 - accuracy: 0.8666 - val_loss: 0.5345 - val_accuracy: 0.8163<br>Epoch 19/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.3561 - accuracy: 0.8705 - val_loss: 0.4960 - val_accuracy: 0.8313<br>Epoch 20/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.3425 - accuracy: 0.8764 - val_loss: 0.5402 - val_accuracy: 0.8240<br>Epoch 21/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.3405 - accuracy: 0.8746 - val_loss: 0.5499 - val_accuracy: 0.8310<br>Epoch 22/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.3257 - accuracy: 0.8825 - val_loss: 0.5232 - val_accuracy: 0.8253<br>Epoch 23/30<br>439/439 [==============================] - 51s 117ms/step - loss: 0.3154 - accuracy: 0.8835 - val_loss: 0.5071 - val_accuracy: 0.8340<br>Epoch 24/30<br>439/439 [==============================] - 51s 117ms/step - loss: 0.3121 - accuracy: 0.8858 - val_loss: 0.5404 - val_accuracy: 0.8143<br>Epoch 25/30<br>439/439 [==============================] - 52s 118ms/step - loss: 0.3082 - accuracy: 0.8847 - val_loss: 0.5662 - val_accuracy: 0.8217<br>Epoch 26/30<br>439/439 [==============================] - 52s 119ms/step - loss: 0.2939 - accuracy: 0.8950 - val_loss: 0.5530 - val_accuracy: 0.8230<br>Epoch 27/30<br>439/439 [==============================] - 52s 117ms/step - loss: 0.2821 - accuracy: 0.8970 - val_loss: 0.5394 - val_accuracy: 0.8253<br>Epoch 28/30<br>439/439 [==============================] - 52s 118ms/step - loss: 0.2794 - accuracy: 0.8966 - val_loss: 0.5438 - val_accuracy: 0.8360<br>Epoch 29/30<br>439/439 [==============================] - 51s 117ms/step - loss: 0.2709 - accuracy: 0.9017 - val_loss: 0.5954 - val_accuracy: 0.8170<br>Epoch 30/30<br>439/439 [==============================] - 51s 116ms/step - loss: 0.2683 - accuracy: 0.9023 - val_loss: 0.5720 - val_accuracy: 0.8240</pre><p>As you can see, our model has an accuracy of ~83 % on validation data which is not bad. The accuracy can be further increased by playing around with different parameters such as</p><ol><li>Increasing number of Neurons</li><li>Increasing number of hidden layers</li><li>Increasing epochs</li><li>Playing around with convolutional layer parameters</li></ol><p>So this was all about how you can build your own Convolutional Neural Network for Image Classification.</p><p>If you want to learn more about CNNs, you can refer to the below links</p><ol><li><em>Yann LeCun et al., 1998, </em><a href="http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf"><em>Gradient-Based Learning Applied to Document Recognition</em></a></li><li><em>Adit Deshpande, 2016, </em><a href="https://adeshpande3.github.io/adeshpande3.github.io/The-9-Deep-Learning-Papers-You-Need-To-Know-About.html"><em>The 9 Deep Learning Papers You Need To Know About (Understanding CNNs Part 3)</em></a></li><li><em>C.-C. Jay Kuo, 2016, </em><a href="https://arxiv.org/pdf/1609.04112.pdf"><em>Understanding Convolutional Neural Networks with A Mathematical Model</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dbc09fabbd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/convolutional-neural-networks-for-multiclass-image-classification-a-beginners-guide-to-6dbc09fabbd">Convolutional Neural Networks for Multiclass Image Classification — A Beginners Guide to Understand</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Text from Scanned PDF using Pytesseract & Open CV]]></title>
            <link>https://medium.com/data-science/extracting-text-from-scanned-pdf-using-pytesseract-open-cv-cd670ee38052?source=rss-6550cd7cb5e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd670ee38052</guid>
            <category><![CDATA[pytesseract]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cv2]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[invoice]]></category>
            <dc:creator><![CDATA[Akash Chauhan]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 10:27:13 GMT</pubDate>
            <atom:updated>2020-09-08T14:56:00.306Z</atom:updated>
            <content:encoded><![CDATA[<h4>Document Intelligence using Python and other open source libraries</h4><p>The process of extracting information from a digital copy of invoice can be a tricky task. There are various tools that are available in the market that can be used to perform this task. However there are many factors due to which most of the people want to solve this problem using Open Source Libraries.</p><p>I came across a similar set of problem a few days back and wanted to share with you all the approach through which I solved this problem. The libraries that I used for developing this solution were <strong>pdf2image</strong> (for converting PDF to images), <strong>OpenCV</strong> (for Image pre-processing) and finally <strong>PyTesseract</strong> for OCR along with <strong>Python</strong>.</p><h3><strong>Converting PDF to Image</strong></h3><p>pdf2image is a python library which converts PDF to a sequence of PIL Image objects using pdftoppm library. The following command can be used for installing the pdf2image library using pip installation method.</p><blockquote>pip install pdf2image</blockquote><p>Note: pdf2image uses <strong><em>Poppler</em></strong> which is a PDF rendering library based on the xpdf-3.0 code base and will not work without it. Please refer to the below resources for downloading and installation instructions for Poppler.</p><p><a href="https://anaconda.org/conda-forge/poppler"><em>https://anaconda.org/conda-forge/popple</em></a><em>r</em></p><p><a href="https://stackoverflow.com/questions/18381713/how-to-install-poppler-on-windows"><em>https://stackoverflow.com/questions/18381713/how-to-install-poppler-on-windows</em></a></p><p>After installation, any pdf can be converted to images using the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c53e814007e090f8a8666027b0c36020/href">https://medium.com/media/c53e814007e090f8a8666027b0c36020/href</a></iframe><p>After converting the PDF to images, the next step is to highlight the regions of the images from which we have to extract the information.</p><blockquote>Note: Before marking regions make sure that you have preprocessed the image for improving its quality (DPI ≥ 300, Skewness, Sharpness and Brightness should be adjusted, Thresholding etc.)</blockquote><h3><strong>Marking Regions of Image for Information Extraction</strong></h3><p>Here in this step we will mark the regions of the image from where we have to extract the data. After marking those regions with the rectangle, we will crop those regions one by one from the original image before feeding it to the OCR engine.</p><blockquote>Most of us would think to this point — why should we mark the regions in an image before doing OCR and not doing it directly?</blockquote><blockquote>The simple answer to this question is that <strong>YOU CAN</strong></blockquote><blockquote>The only catch to this question is sometimes there are hidden line breaks/ page breaks that are embedded in the document and if this document is passed directly into the OCR engine, the continuity of data breaks automatically (as line breaks are recognized by OCR).</blockquote><p>Through this approach, we can get maximum correct results for any given document. In our case we will be trying to extract information from an invoice using the exact same approach.</p><p>The below code can be used for marking the regions of interest in the image and getting their respective co-ordinates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e57fb573df6fa5056c9fb81b5eea201b/href">https://medium.com/media/e57fb573df6fa5056c9fb81b5eea201b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTJ5_mezfc-K3WKyxpls8Q.jpeg" /><figcaption>Original Image (Source: Abbyy OCR Tool Sample Invoice Image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YiYMZB6XMV3s8R0tNrqI1A.jpeg" /><figcaption>Regions of Interest marked in Image (Source: Abbyy OCR Tool Sample Invoice Image)</figcaption></figure><h3><strong>Applying OCR to the Image</strong></h3><p>Once we have marked the regions of interest (along with the respective coordinates) we can simply crop the original image for the particular region and pass it through pytesseract to get the results.</p><p>For those who are new to Python and OCR, pytesseract can be an overwhelming word. According to its official website -</p><blockquote>Python-tesseract is a wrapper for <a href="https://github.com/tesseract-ocr/tesseract">Google’s Tesseract-OCR Engine</a>. It is also useful as a stand-alone invocation script to tesseract, as it can read all image types supported by the Pillow and Leptonica imaging libraries, including jpeg, png, gif, bmp, tiff, and others. Additionally, if used as a script, Python-tesseract will print the recognized text instead of writing it to a file.</blockquote><p>Also, if you want to play around with the configuration parameters of pytesseract, I would recommend to go through the below links first.</p><ul><li><a href="https://pypi.org/project/pytesseract/">pytesseract</a></li><li><a href="https://stackoverflow.com/questions/44619077/pytesseract-ocr-multiple-config-options">Pytesseract OCR multiple config options</a></li></ul><p>The following code can be used to perform this task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe78064b1ddb004902369656d89a7161/href">https://medium.com/media/fe78064b1ddb004902369656d89a7161/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Omos0aoeTCSk2DXdl97KLQ.jpeg" /><figcaption>Cropped Image-1 from Original Image (Source: Abbyy OCR Tool Sample Invoice Image)</figcaption></figure><p>Output from OCR:</p><pre>Payment:<br><br>Mr. John Doe<br><br>Green Street 15, Office 4<br>1234 Vermut<br><br>New Caledonia</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_kWBVRIPoGTAVooqOFZhw.jpeg" /><figcaption>Cropped Image-2 from Original Image (Source: Abbyy OCR Tool Sample Invoice Image)</figcaption></figure><p>Output from OCR</p><pre>COMPLETE OVERHAUL 1 5500.00 5500.00 220<br>REFRESHING COMPLETE CASE 1 380.00 380.00 220<br>AND RHODIUM BATH</pre><p>As you can see, the accuracy of our output is 100%.</p><p>So this was all about how you can develop a solution for extracting data from a complex document such as invoices.</p><p>There are many applications to what OCR can do in term of document intelligence. Using pytesseract, one can extract almost all the data irrespective of the format of the documents (whether its a scanned document or a pdf or a simple jpeg image).</p><p>Also, since its open source, the overall solution would be flexible as well as not that expensive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd670ee38052" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/extracting-text-from-scanned-pdf-using-pytesseract-open-cv-cd670ee38052">Extracting Text from Scanned PDF using Pytesseract &amp; Open CV</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>