<?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 Prateek Sahu on Medium]]></title>
        <description><![CDATA[Stories by Prateek Sahu on Medium]]></description>
        <link>https://medium.com/@pratiksahu147?source=rss-302684a33a57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pUroWmPN8brLeoRDIO10EQ.jpeg</url>
            <title>Stories by Prateek Sahu on Medium</title>
            <link>https://medium.com/@pratiksahu147?source=rss-302684a33a57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:12:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pratiksahu147/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[The Art of Chatbot Creation: Designing AI Chatbots for the Airline Industry]]></title>
            <link>https://medium.com/@pratiksahu147/the-art-of-chatbot-creation-designing-ai-chatbots-for-the-airline-industry-e140b4590525?source=rss-302684a33a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/e140b4590525</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prateek Sahu]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 19:10:42 GMT</pubDate>
            <atom:updated>2023-02-01T19:10:42.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design NLP System for AI-Powered Conversations</h4><h3>Introduction</h3><p>The rise of AI technology has revolutionized the way businesses interact with customers, and the airline industry is no exception. AI conversational chatbots are increasingly being adopted by airlines as a way to enhance customer experience, improve efficiency, and streamline operations. In this blog, we explore the key elements involved in creating an effective AI conversational chatbot for the airline industry. From defining goals and objectives to choosing the right platform and designing a natural language processing system, this guide provides valuable insights and practical tips for anyone looking to create an AI chatbot for airlines. Whether you’re an airline executive, a chatbot developer, or just someone interested in this growing field, this blog will give you a deeper understanding of the process of creating AI chatbots, and help you to make informed decisions about chatbot development.</p><h3><strong>Business Problem</strong></h3><p>Customers face challenges when trying to get quick and accurate information about their flight plans, especially during disruptions. Traditional chatbots have limited conversational capabilities and provide rigid responses, leading to frustration for customers. Our goal is to develop a machine learning and NLP-based AI chatbot that will offer a more natural and personalized conversational experience, allowing customers to get the information they need in a fast and efficient manner.</p><h3><strong>ML System Design for Cognitive AI</strong></h3><p>The below flowchart represents the high-level design of a conversational AI chatbot. In order to get the AI-based response, user input has to pass with all given block that is mentioned in the figure. Let’s discuss each component in brief.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*8fD9cYPFLPYvjPUujWIXNQ.png" /><figcaption>High-Level Design for Conversation AI Chatbot</figcaption></figure><ul><li><strong>User Message</strong> in a chatbot refers to the input from the user that is sent to the chatbot for processing and response. It can be in the form of text that the chatbot is designed to understand and interpret.</li><li><strong>Message Autocorrect </strong>in a chatbot refers to the ability of the chatbot to automatically correct spelling, grammar, or other errors in the user’s input. The aim of autocorrect is to improve the accuracy of the chatbot’s understanding of the user message and to ensure that the response is as relevant as possible.</li><li><strong>T</strong>he<strong> intent</strong> in the context of a chatbot refers to the underlying goal or purpose of the user’s message. It is the intention behind the words that the user has written to the chatbot. For example, a user may message a chatbot to inquire about flight timings, ask for a refund, or request help with a problem.</li><li><strong>Entities</strong> are specific words or phrases in the user’s message that are relevant to the conversation. They are typically defined by the chatbot designer and used to extract relevant information from the user’s message. For example, in a chatbot for an airline, entities could be flight numbers, dates, cities, and airports. The chatbot can use these entities to understand the user’s intent and provide a relevant response. For example, if the user asks “What is the flight status of AA123 on March 1st?”, the chatbot would recognize “AA123” as the flight number and “March 1st” as the date entity.</li><li><strong>Generate Response:</strong> To create a reply to the user’s inquiry, the intent must first be identified and the necessary entities must be extracted. This data can then be retrieved from the database by utilizing API calls.</li></ul><h3>Data collection and Annotation</h3><h4><a href="https://www.kaggle.com/datasets/hassanamin/atis-airlinetravelinformationsystem"><strong>Intent Classification Dataset</strong></a></h4><p><a href="https://www.kaggle.com/datasets/hassanamin/atis-airlinetravelinformationsystem">ATIS dataset</a> provides a large number of messages and their associated intents that can be used in training a classifier. Within a chatbot, intent refers to the goal the customer has in mind when typing in a question or comment and it is a standard benchmark dataset widely used as an intent classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*Is_Ec6hXj5ewNizl.png" /><figcaption>Intents and No. of query that belongs to specific intent.</figcaption></figure><p>The above bar plot depicts the count of the number of queries per intent for the airline&#39;s dataset. The intent “atis_flight” has enormous queries as compared to other ones.</p><h4><a href="https://www.kaggle.com/datasets/usdot/flight-delays"><strong>Airline Information Dataset</strong></a></h4><p>This dataset contains all the information for the airlines, airports and flights which are necessary for the client(user).</p><h3>Applied AI Use Cases for Chatbot</h3><p>These use cases must be effectively addressed in order to create a high-quality AI chatbot that provides a good user experience.</p><blockquote><strong>Note</strong>: All use cases have separate sub-problem of the <strong>Machine Learning Life Cycle</strong> which include the process of <strong>data collection</strong>, <strong>data preprocessing</strong>, <strong>feature engineering</strong>, <strong>model selection, model evaluation</strong> and <strong>model deployment</strong>.</blockquote><h4>User Query Auto-Corrector (Spell Correction)</h4><p>Auto-Corrector is useful in conversational AI, where users may type quickly or make typos, leading to misunderstandings or incorrect responses from the chatbot and for this use case we’ll use a transformer-based spelling corrector model.</p><p><strong>What is Transformer based Auto-Corrector?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*XJ1K_jrYGAGsIzL5.png" /><figcaption>Transformer Architecture</figcaption></figure><p>Transformer-based auto corrector is a type of machine learning model that uses the Transformer architecture to correct spelling mistakes in the text, improving the accuracy and quality of the text-based data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a22dc4b51e351d5f9e95f7b0f976d4/href">https://medium.com/media/d1a22dc4b51e351d5f9e95f7b0f976d4/href</a></iframe><p>Here, we utilized a pre-trained <a href="https://huggingface.co/oliverguhr/spelling-correction-english-base">Hugging Face model</a> which is trained on Wikipedia extracted data, if you want to know more about the training and implementation process refer to the <a href="https://github.com/oliverguhr/spelling">GitHub repository of oliverguhr</a>.</p><h4>Intent Classification</h4><p>The next action in creating a chatbot is to determine the user’s intent. This involves using natural language processing (NLP) techniques to understand what the user is asking and to categorize the request into a specific intent.</p><p>The intent classifier model has trained the ATIS dataset by applying the ML techniques such as analysing, text preprocessing and data transformation on the given data then doing the Model selection step in order to get the best model for the classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*U_DsTtlVNGKz18r-KUOtWA.png" /></figure><p>The below-given table shows the information on the Machine Learning model that is trained on the ATIS intent classification dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*yzFNXsiSMRTOMvFmWs1bzw.png" /><figcaption>Machine Learning Model and its Accuracy</figcaption></figure><p>The table has 5 ML models with their Accuracy where the XG Boost model has the most heightened accuracy which is 96% followed by MLP(Multi-Layer Perceptron) model which is 95%.</p><p><strong>Inferences for Intent Classifier</strong></p><p>The inferences pipeline uses the best classifier model and is used in real-time intent classification.</p><pre>#Inferences for Intent Classifier<br>class IntentClassifier:<br>    def __init__(self,model,tokenizer):<br>        self.model=model<br>        self.tokenizer=tokenizer<br>        <br>    def preprocess_query(self, user_query):<br>        try:<br>            preprocessed_query=remove_punctuation(user_query)<br>            preprocessed_query=remove_stopwords(user_query)<br>            preprocessed_query=stem_words(user_query)<br>            return preprocessed_query<br>        except Exception as e:<br>            print(e)<br>    <br>    def tokenization(self,preprocessed_query ):<br>        try:<br>            query = self.preprocess_query(preprocessed_query)<br>            return self.tokenizer.transform([query]).toarray()<br>        except Exception as e:<br>            print(e) <br>    <br>    def get_intent(self, query):<br>        <br>        intent_name_list = [&#39;atis_abbreviation&#39;,<br>         &#39;atis_aircraft&#39;,<br>         &#39;atis_airfare&#39;,<br>         &#39;atis_airline&#39;,<br>         &#39;atis_flight&#39;,<br>         &#39;atis_flight_time&#39;,<br>         &#39;atis_ground_service&#39;,<br>         &#39;atis_quantity&#39;]<br>        try: <br>            if(len(query)==0):<br>                return -1<br>            else:<br>                tokenized_query = self.tokenization(query)<br>                pred_intent=self.model.predict_proba(tokenized_query)<br>                intent = intent_name_list[pred_intent.argmax()]<br>                return intent<br>        except Exception as e:<br>            print(e)<br>        <br>flight = IntentClassifier(ovr, tfidf_vectorizer)<br>flight.get_intent(&#39;what is the time for delhi to bhopal flight?&#39;)           </pre><h4>Entity Recognition</h4><p>Entity recognition is a key component of Natural Language Processing (NLP) and a common feature in conversational AI chatbots. It refers to the process of identifying and extracting specific elements of meaning from a user’s input, such as names, places, organizations, dates, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yyTyXAgG3BonboOH.jpg" /><figcaption>Annotated Entity</figcaption></figure><p>For example, if a user says “I need to book a flight to Paris for next week”, entity recognition in a chatbot would identify “Paris” as a location and “next week” as a date. This information can then be used to provide the user with relevant information or to complete a specific task, such as searching for flight options to Paris on the desired date.</p><p><strong>Inferences for Entity Recognition</strong></p><pre>import spacy <br>class EntityRecognition:<br>    def __init__(self,model):<br>        self.nlp_spacy=model<br>    <br>    def get_entity(self,query:str):<br>        doc=self.nlp_spacy(query)<br>        entity_dict = dict()<br>        for ent in doc.ents:<br>            if ent.label_ not in entity_dict:<br>                entity_dict[ent.label_]=[]<br>                entity_dict[ent.label_].append(ent.text)<br>            else:<br>                entity_dict[ent.label_].append(ent.text)<br>        return entity_dict</pre><p>Here, we use the <strong>spacy </strong>library which has a pre-trained NER model that is able to annotate Date, Name, Organisation(ORG) and Location(GPE). You can train your own NER model as per your need. So you can extract specific information to generate a response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIdlhp8ZBeumT9JVO4WoGA.png" /><figcaption>Entity Recognition Result for a given query</figcaption></figure><h4>Integration with databases and APIs</h4><p>The chatbot may need to retrieve information from databases or external APIs to provide a complete response to the user. This requires integration with these systems and the ability to handle the response from these sources and use the information in the chatbot’s response.</p><p><strong>Amadeus Flight API</strong></p><p>Amadeus API is used for getting the Airport Code(IATA/ICAO). After extracting the location entity, we get the origin and destination places then call the API to get the Codes.</p><pre>from amadeus import Client, ResponseError<br>class AmadeusFlightAPI:<br>    &quot;&quot;&quot;<br>        1. https://developers.amadeus.com<br>        2. https://github.com/amadeus4dev/<br>    &quot;&quot;&quot;<br>    def __init__(self):<br>        pass<br>    <br>    def authentication(self):<br>        client_id=&#39;OmIrXd7UwDaN8EwIelTXy69B6oflO&#39; ## API Key changed<br>        client_secret=&#39;wVEUCTF8fCNUA&#39; ## Secret Key Changed<br>        self.amadeus = Client(client_id=client_id, client_secret=client_secret)<br>    <br>    def get_aitport_informaftion(self, location_name:str):<br>        try:<br>            &#39;&#39;&#39;<br>            What are the cities matched with keyword &#39;Paris&#39; ?<br>            &#39;&#39;&#39;<br>            response = self.amadeus.reference_data.locations.cities.get(keyword=str(location_name))<br>            return response.data<br>        <br>        except ResponseError as error:<br>            raise </pre><p><strong>Flight DataBase</strong></p><p>The below code snippet is about to fetch the flight information from the origin to the destination location, class <em>DataBase </em>has the function <em>get_flight </em>which takes airport codes and return the details of the flight.</p><pre>class DataBase:<br>    def __init__(self):<br>        pass<br>    def load_data(self):<br>        self.airports =  pd.read_csv(&#39;/kaggle/input/flight-delays/airports.csv&#39;)<br>        self.airlines =  pd.read_csv(&#39;/kaggle/input/flight-delays/airlines.csv&#39;)<br>        self.flights =  pd.read_csv(&#39;/kaggle/input/flight-delays/flights.csv&#39;)<br>        <br>    <br>    def get_flight(self, origin_airport_code, destination_airport_code):<br>        try:<br>            flight_information_dict=dict()<br>            top_5_flight=self.flights.loc[lambda x:(x.ORIGIN_AIRPORT == origin_airport_code) &amp; (x.DESTINATION_AIRPORT == destination_airport_code)]<br>            origin_airport_detail=self.airports.loc[lambda x:(x.IATA_CODE == origin_airport_code)]<br>            destination_airport_detail=self.airports.loc[lambda x:(x.IATA_CODE == destination_airport_code)] <br>            flight_information_dict[&#39;flight&#39;]=top_5_flight.head()<br>            flight_information_dict[&#39;origin_airport&#39;]=origin_airport_detail<br>            flight_information_dict[&#39;destination_flight&#39;]=destination_airport_detail<br>            return flight_information_dict<br>            <br>        except Exception as e:<br>            raise</pre><p>Let the user ask a query for getting the flight information from New York to Bhopal. So, In real-time our <strong>spell corrector</strong> checks the query then the <strong>intent classifier</strong> classifies the intent(<em>flight_information</em>) and the <strong>entity</strong> <strong>Recogniser</strong> extract entity such as location: <em>New York</em> and <em>Bhopal</em> and Organisation: <em>Air India.</em></p><h4>Response generation:</h4><p>After the intent, entities, database and APIs have been determined, the chatbot must generate a response that is relevant and appropriate to the user’s request. This requires a good understanding of the user’s intent and the use of advanced natural language generation (NLG) algorithms to produce a well-formed and grammatically correct response.</p><p>Let&#39;s accumulate all the use cases that we’ve discussed above and start the conversation with an AI-powered chatbot.</p><p>In the below code snippet, the class <em>Conversation </em>has the function <em>get_response</em> which takes a parameter <em>query</em> from the user and return the response to the user.</p><pre>class Conversation:<br>    def __init__(self):<br>        pass<br>        <br>    def load_model(self):<br>        self.clf=ovr<br>        self.tokenizer=tfidf_vectorizer<br>        self.nlp_spacy=spacy.load(&quot;en_core_web_sm&quot;)<br>        self.autocorrect=pipeline(&quot;text2text-generation&quot;,model=&quot;oliverguhr/spelling-correction-english-base&quot;)<br>        self.amadeus_flight_API=AmadeusFlightAPI()<br>        self.amadeus_flight_API.authentication()<br>        self.flight_db=DataBase()<br>        self.flight_db.load_data()<br>        <br>    def get_response(self,query):<br>        autocorrect_query=self.autocorrect(query,max_length=2048)[0][&#39;generated_text&#39;]<br>        flight = IntentClassifier(self.clf, self.tokenizer)<br>        entity_recognition=EntityRecognition( self.nlp_spacy)<br>        pred_intent=flight.get_intent(autocorrect_query)   <br>        if pred_intent == &quot;atis_flight&quot;:<br>            entity_dict=entity_recognition.get_entity(autocorrect_query)<br>            location_list=entity_dict[&#39;GPE&#39;]<br>            if len(location_list)&gt;0:<br>                if len(location_list)==1:<br>                    source_location=location_list[0]<br>                    # Information not enough<br>                    <br>                else:<br>                    source_location=location_list[0]<br>                    destination_location=location_list[-1]<br>                    source_location_info=self.amadeus_flight_API.get_aitport_informaftion(source_location)[0]<br>                    destination_location_info=self.amadeus_flight_API.get_aitport_informaftion(destination_location)[0]<br>                    flight_information=self.flight_db.get_flight(source_location_info[&#39;iataCode&#39;],destination_location_info[&#39;iataCode&#39;])<br>                    respose = dict()<br>                    respose[&#39;source_location&#39;]=flight_information<br>                    return flight_information</pre><p>Here’s the result for the asked query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FthuE8zhhcxQCLZrRIeh7A.png" /><figcaption>Query Output</figcaption></figure><h3>References</h3><ol><li><a href="https://drive.google.com/file/d/1OuYkYB5J2getuL89ud7Xvt21WKp9QbwU/view">https://drive.google.com/file/d/1OuYkYB5J2getuL89ud7Xvt21WKp9QbwU/view</a></li><li><a href="https://www.linkedin.com/pulse/end-nlp-model-using-syntactic-processing-atis-data-over-nilesh-gode/">https://www.linkedin.com/pulse/end-nlp-model-using-syntactic-processing-atis-data-over-nilesh-gode/</a></li><li><a href="https://www.cs.cmu.edu/~dkaushik/assets/pubs/RANLP047.pdf">https://www.cs.cmu.edu/~dkaushik/assets/pubs/RANLP047.pdf</a></li><li><a href="https://www.kaggle.com/code/divyansh22/airline-review-data-preprocessing-pt-2-nlp/notebook">https://www.kaggle.com/code/divyansh22/airline-review-data-preprocessing-pt-2-nlp/notebook</a></li><li><a href="https://www.travelpayouts.com/blog/flight-apis-and-travel-project-ideas/">https://www.travelpayouts.com/blog/flight-apis-and-travel-project-ideas/</a></li><li><a href="https://github.com/vishalstark512/ChatBot_With_Intents">https://github.com/vishalstark512/ChatBot_With_Intents</a></li><li><a href="https://meta-guide.com/software/100-best-github-chatbot-dataset">https://meta-guide.com/software/100-best-github-chatbot-dataset</a></li><li><a href="https://www.kaggle.com/datasets/536db59649ec509a2808c8d2c85d560c64e1dce44778a22ab79ce3408813e8fb">https://www.kaggle.com/datasets/536db59649ec509a2808c8d2c85d560c64e1dce44778a22ab79ce3408813e8fb</a> -&gt; Create Account Dataset</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e140b4590525" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where’s the Pothole | Object Detection| Computer Vision| Deep Learning | TFOD-2.0]]></title>
            <link>https://medium.com/@pratiksahu147/wheres-the-pothole-object-detection-computer-vision-deep-learning-tfod-2-0-a422ea4b5844?source=rss-302684a33a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/a422ea4b5844</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[potholes]]></category>
            <dc:creator><![CDATA[Prateek Sahu]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 09:19:08 GMT</pubDate>
            <atom:updated>2022-11-09T11:34:31.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>Where’s the Pothole | Object Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7MAcOo7vLf4w_AvP8Ph_vA.png" /></figure><blockquote><strong>Abstract</strong></blockquote><blockquote>Streets are intended for explicit paces at which vehicles can go with security. Not with standing, at specific areas, eg: “keeping an eye on and automated level intersections, sharp curves, congested or accident-prone, extra speed control might be essential to guarantee well-being”. This is accomplished through a few different ways, for example, posting obligatory speed limit signs, utilization of blazing signals to alarm drivers, and street markings. In specific circumstances, street bumps are required, however, their utilization on streets isn’t viewed as acceptable design practice. Plain speed breakers do not fill the need, however, harm the vehicle and in not many cases they have caused serious wounds and passing. Traffic signs may likewise divert the driver and take their consideration from the street. Anyway absence of light or over-the-top light makes it hard to perceive the speed breaker ahead. This report talks about the technique for distinguishing mounds and potholes and gives ideal cautions to drivers to stay away from mishaps or vehicle harm. A picture-preparing framework is utilized to distinguish the mound. We have additionally utilized ultrasonic sensors to recognize the potholes by estimating the profundity of the streets individually. The proposed framework likewise stores the geographic area of the recognized pothole to the cloud utilizing IO T. This data fills in as an essential source to the administration specialists.</blockquote><blockquote>Keywords: <strong>Detection, PotHole Detection, Animal Detection, Convolution Neural Networks Algorithm, Haar Cascade Algorithm, TFOD, Computer Vision.</strong></blockquote><h3><strong>Introduction</strong></h3><p>India is the second most famous Country in the World and has a quickly developing economy. Roads are the prevailing methods of transportation in India. Be that as it may, the greater part of the streets in India is narrow and congested with helpless surface quality and street upkeep needs are not fulfilled met. Regardless of where you are in India, driving is a breath-holding, multi-reflect including, conceivably life undertaking. Throughout the most recent two decades, there has been a gigantic increment in the vehicle populace. This expansion in the number of streets.</p><p>In the course of the most recent two decades, India has developed hugely, as an ever-increasing number of individuals graduate continuously and increasingly more of us gain work constantly, we will undoubtedly drive and invest the greater part of our energy voyaging. The well-being of the drivers ought to be organized and a smooth drive ought to be guaranteed for everybody. Thinking along such lines we thought of coordinating an equipment framework which distinguishes the potholes utilizing an accelerometer and a spinner alongside a product which can quantify these outcomes on an ongoing premise and store the essential information on a cloud base.</p><h3>Problem Statement</h3><p>Potholes have been a difficult issue and have become a danger for safe street travel, so as to beat the issue we are proposing this framework utilizing Machine Learning and Image Processing. which will recognize the potholes and by doing so we can proficiently handle the issue.</p><p><strong>Scope and Objectives</strong></p><p>Potholes are a heavy issue and became a threat to safe road travel, so as to beat the problem we are proposing this technique using machine learning and image processing, which can detect the potholes and by doing so we will efficiently tackle the difficulty.</p><ul><li><em>Better road safety:</em> Machines aren’t at risk of human error and distractions, resulting in swift and appropriate responses in real-time road conditions.</li><li><em>Reduced commute time:</em> With vehicles communicating through one another.</li></ul><p>In India ordinarily, streets have speed breakers so the vehicle’s speed can be controlled to keep away from mishaps. Be that as it may, speed breakers are unevenly appropriated with lopsided and informal statures.</p><p>Potholes, shaped are because of substantial downpours and development of the overwhelming vehicles, additionally, become a significant explanation behind mishaps and loss of human lives. With the proposed framework has been made to underwrite drivers to avert the mishaps caused because of potholes and raised protuberances, using modern GPS systems, commute times is greatly reduced as self-driving vehicle decreases the “phantom effect” in modern-day traffic.</p><ul><li><em>Increased productivity:</em> Reduced commute times mean longer are often spent on what depends more.</li><li><em>Reduced expenditure:</em> Reduction in accidents will directly cause reduced expenditure on damages.</li><li><em>Environment-friendly:</em> Efficient performance driving forms of the self-driving car will result in lower emissions.</li></ul><h3>2. Research Method</h3><p>The research method for the project involves three main parts-data collections, training, and detection. The proposed vehicle and pothole detection technique detects vehicles and potholes in images with the transfer learning technique. Faster R-CNN and inception v2 models are the techniques used in the proposed model. The ultimate benefit of this proposed method is the least time for training along with very high accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KZlFs7bsH7_D3SvgRfTLQ.png" /></figure><h4>2.1. Transfer learning technique</h4><p>Transfer learning is a technique that involves training a neural network model on a problem that is similar to the solved one. The layers of the trained model use a new model to train on the problem of interest. The implementation of gained knowledge while resolving one problem to another related problem is known as the transfer learning technique. It is possible to save a significant amount of time with the transfer learning method. Any pre-trained model can be chosen and used in this method as a first step. A model that has all of its parameters trained refers to a pre-trained model. The final step will be to fine-tune the parameters.</p><p>The new dataset fetches to fine-tune the convolutional neural networks (CNNs) [11], [12]. And if the latest datasets are similar to an actual dataset, then the same weight is used to extract the features. Here this dataset is vastly divergent from these original datasets. Earlier layers of this CNN found a generic property. The layers of CNN [13], [14], on the other hand, become increasingly particular to the specifics of classes in the actual or real dataset. As a result, previous layers will aid in the extraction of current data features. Because of the fewer amount of data, it fixes the earlier layers. The rest of these layers are retrained</p><h4>2.2. Architecture of F-RCNN</h4><p>The faster region-based convolutional neural network is also known as F-RCNN or Faster R-CNN. First of all, it is necessary to understand the Fast R-CNN before moving on to faster RCNN. Fast RCNN (fast region-based CNN) is a detector. The fast region-based convolutional neural network uses external proposals. External selective search, a convolutional neural network with maximum pooling, fully connected layers, region of interest pooling layer, and then output layers are among the components. With the help of convolutional neural network and pooling layers — max-pooling layers, Fast RCNN receives an input image. It extracts the convolutional feature map. The region of interest pooling layer plays a salient role. The fully connected layer accepts fixed sizes only. As a result, the ROI pooling layers convert CNN’s output into a predetermined size. Fast RCNN becomes a faster region-based convolutional neural network when fast RCNN combines with a region proposal network. So, the main dissimilarity between fast region-based convolutional neural network and faster region-based convolutional neural network is only about the region proposal. The fast region-based convolutional neural network has an external selective search [15]. Region proposal network combines with the Architecture in a faster region-based convolutional neural network. region proposal network also chooses where to look in the image to reduce computational complexity and requirements. It mainly scans this input image. It then generates k output boxes, all with two scores representing probability for an object’s availability [16], [17]. Figure 1 depicts the F-RCNN architecture.</p><h4>2.3. Dataset</h4><p>The datasets identified and used in this proposed work are, the traffic surveillance dataset and the Pothole detection dataset. The Traffic Surveillance dataset is composed of 400 images that include different types of vehicles on the road. This dataset is for vehicle detection. This dataset provides images to perform vehicle detection. The Pothole detection dataset is an image dataset that contains around 665 images of roads with potholes. This dataset is from Kaggle. This dataset mainly includes images with different types of potholes on roads. This dataset is for detection models and can work as proof of concept (POC)/proof of value (POV) for the maintenance of roads. For this project, the necessary data and images of both vehicles and potholes are gathered from various sources.</p><h4>2.4. Data pre-processing</h4><p>There are over a thousand images in the dataset. The vehicle detection and pothole detection tasks consider as uncomplicated only if the region in those pictures containing the road has been cropped. Later it is utilized in the detection. Also, it requires extra time in order to crop one thousand or more images. All of the images are labelled. Then a comma-separated values (CSV) file is created. This CSV file includes the name of the image, path, dimension of the image, and coordinates of the vehicles and potholes. Then TfRecords for the dataset are created. It feeds and fine-tunes the Inception model. The image size is 3680x2760 pixels.</p><h4>2.5. Detection of vehicles and potholes</h4><p>After the pre-processing of the data, a model to detect vehicles and potholes has created. The model has been fine-tuned using the Inception ResNet 50 architecture [24], [25]. Training requires a configuration file. There are nine different classes in this configuration file. Ambulance, auto, bus, car, motorcycle, pothole, potholeGroup, truck, and van are the nine classes. The proposed system will take some time to train the model, depending on the hardware configuration. Once the training completes, the testing process begins. During testing, the model performed admirably. It can, however, be improved.</p><h4>2.6. Object Detection Algorithms</h4><p>CNN is short for Region-based Convolutional Neural Network. The algorithm was started by Ross Girshick and others.</p><p><a href="https://towardsdatascience.com/r-cnn-fast-r-cnn-faster-r-cnn-yolo-object-detection-algorithms-36d53571365e">R-CNN, Fast R-CNN, Faster R-CNN, YOLO — Object Detection Algorithms</a></p><p>R-CNN is the first in a series of related algorithms, the next is Fast R-CNN and after that Faster R-CNN. Then everybody gave up on the Fast superlatives, after all, you Only Look Once. All of these basically do the same thing which is to detect and classify objects in an image. Plain vanilla CNNs classify the object that stands out the most in the query image. R-CNNs can classify more than one object in the image.</p><p>R-CNN classify many objects by first developing Region Proposals in the image where objects that can be classified may be. It does this by using another algorithm known as Selective Search. Fast R-CNN uses Selective Search on the layers of the CNN itself to identify Region Proposals. Faster R-CNN uses an object detection algorithm that allows the CNN itself to learn the Region Proposals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*ySdNrm9ObcdXa57X" /></figure><p>Fast R-CNN</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*SDnwdF9mEkvQd08Z" /></figure><p>Faster R-CNN</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*bS4a3SQABOqtknqg" /></figure><p>Up to this point, I have used the general term CNN. ResNet, short for Residual neural network, is a CNN that follows a particular architecture. <a href="https://en.wikipedia.org/wiki/Residual_neural_network">Residual neural network — Wikipedia</a></p><h4>2.7. ResNet</h4><p>“A residual neural network (ResNet) is an artificial neural network (ANN) of a kind that builds on constructs known from pyramidal cells in the cerebral cortex. Residual neural networks do this by utilizing skip connections, or shortcuts to jump over some layers. Typical ResNet models are implemented with double- or triple-layer skips containing nonlinearities (ReLU) and batch normalization. An additional weight matrix may be used to learn the skip weights; these models are known as HighwayNets. Models with several parallel skips are referred to as DenseNets.”</p><p>ResNet 50 would indicate a ResNet with 50 layers. It is one of the CNNs provided by Keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oBoxbiXmG-itfEYb.png" /></figure><h3>3. TensorFlow Object Detection API Installation</h3><ul><li>Now that you have installed TensorFlow, it is time to install the TensorFlow Object Detection API.</li></ul><h4>3.1. Downloading the TensorFlow Model Garden</h4><ul><li>Create a new folder under a path of your choice and name it TensorFlow. (e.g. C:\Users\sglvladi\Documents\my_object_detection_project).</li><li>From your Terminal cd into the TensorFlow directory.</li><li>To download the models you can either use Git to clone the TensorFlow Models repository inside the TensorFlow folder, or you can simply download it as a ZIP and extract its contents inside the TensorFlow folder. To keep things consistent, in the latter case you will have to rename the extracted folder models-master to models.</li></ul><pre>!git clone <a href="https://github.com/tensorflow/models.git">https://github.com/tensorflow/models.git</a></pre><ul><li>You should now have a single folder named models under your TensorFlow folder, which contains another 4 folders as such:</li></ul><pre># Diractory Should be look like this.<br>PotholeCaseStudy/<br>└─ models/<br>   ├─ community/<br>   ├─ official/<br>   ├─ orbit/<br>   ├─ research/<br>   └── ...</pre><h3>4. Training Custom Object Detector</h3><h4>4.1. Preparing the Workspace</h4><ul><li>Now create a new folder under PotholeCaseStudy and call it workspace. It is within the workspace that we will store all our training set-ups. Now let’s go under workspace and create another folder named “pothole_training”.</li></ul><pre># This is formatted as code<br>PotholeCaseStudy/<br>├─ models/<br>│  ├─ community/<br>│  ├─ official/<br>│  ├─ orbit/<br>│  ├─ research/<br>│  └─ ...<br>└─ workspace/<br>   └─ pothole-training/</pre><ul><li>The training_demo folder shall be our training folder, which will contain all files related to our model training. It is advisable to create a separate training folder each time we wish to train on a different dataset. The typical structure for training folders is shown below.</li></ul><pre># This is formatted as code<br><br>pothole-training/<br>├─ annotations/<br>├─ exported-models/<br>├─ images/<br>│  ├─ test/<br>│  └─ train/<br>├─ models/<br>├─ pre-trained-models/<br>└─ README.md</pre><p><strong>Here’s an explanation for each of the folders/filers shown in the above tree:</strong></p><ol><li><strong>annotations</strong>: This folder will be used to store all *.csv files and the respective TensorFlow *.record files, which contain the list of annotations for our dataset images.</li><li><strong>exported-models</strong>: This folder will be used to store exported versions of our trained model(s).</li><li><strong>images</strong>: This folder contains a copy of all the images in our dataset, as well as the respective *.xml files produced for each one, once labelImg is used to annotate objects.</li><li><strong>images/train</strong>: This folder contains a copy of all images, and the respective *.xml files, which will be used to train our model.</li><li><strong>images/test</strong>: This folder contains a copy of all images, and the respective *.xml files, which will be used to test our model.</li><li><strong>models</strong>: This folder will contain a sub-folder for each of training job. Each subfolder will contain the training pipeline configuration file *.config, as well as all files generated during the training and evaluation of our model.</li><li><strong>pre-trained-models</strong>: This folder will contain the downloaded pre-trained models, which shall be used as a starting checkpoint for our training jobs.</li><li><strong>README.md</strong>: This is an optional file which provides some general information regarding the training conditions of our model. It is not used by TensorFlow in any way, but it generally helps when you have a few training folders and/or you are revisiting a trained model after some time.</li></ol><h3>5. Data Preprocessing</h3><p>TensorFlow requires a label map, which namely maps each of the used labels to an integer value. This labelled map is used both by the training and detection processes.</p><ul><li>Below we show a label map (<strong>label_map.pbtxt</strong>), as our dataset contains labels “pothole”:</li><li>item { id: 1 name: &#39;pothole&#39;}</li><li>Label map files have the extension <strong>.pbtxt</strong> and should be placed inside the “training_demo/annotations” folder.</li></ul><h4>5.1. Create TensorFlow Records</h4><p>Now that we have generated our annotations and split our dataset into the desired training and testing subsets, it is time to convert our annotations into the so-called TFRecord format.</p><p><strong>Convert *.xml to *.record</strong></p><ul><li>To do this we can write a simple script that iterates through all *.xml files in the training_demo/images/train and training_demo/images/test folders, and generates a *.record file for each of the two. Here is an example script that allows us to do just that:</li></ul><pre># Code Tf record</pre><h4>5.2. Create train data:</h4><pre>python generate_tfrecord.py -x [PATH_TO_IMAGES_FOLDER]/train -l [PATH_TO_ANNOTATIONS_FOLDER]/label_map.pbtxt -o [PATH_TO_ANNOTATIONS_FOLDER]/train.record</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*WtOol4JC2BqzOrlk03n0pg.png" /></figure><h4>5.3. Create test data:</h4><pre>python generate_tfrecord.py -x [PATH_TO_IMAGES_FOLDER]/test -l [PATH_TO_ANNOTATIONS_FOLDER]/label_map.pbtxt -o [PATH_TO_ANNOTATIONS_FOLDER]/test.record</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*JOY150NsbqeA9drj3tzP6w.png" /></figure><h3>6. Exploratory Data Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9TPguf77UiMsmwL2audSQ.png" /></figure><h4>6.1. Observations :</h4><ul><li>It is evident from the above figures that both our train and test set images follow similer Height and Width distribution.</li><li>Since all the images have different dimensions, we need to fix the height and width constant for every image to follow.</li><li>We need to perform this in such a way that data loss is least. For smaller images, we will need to do appropriate padding.</li></ul><h3>7. Model Training</h3><h4>7.1. Configuring a Training Job</h4><ul><li>we will not be creating a training job from scratch, but rather we will reuse one of the pre-trained models provided by TensorFlow. If you would like to train an entirely new model, you can have a look at TensorFlow’s tutorial.</li><li>The model we shall be using in our examples is the SSD ResNet50 V1 FPN 640x640 model, since it provides a relatively good trade-off between performance and speed. However, there exist a number of other models you can use, all of which are listed in TensorFlow 2 Detection Model Zoo.</li></ul><p><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md"><strong>Download Pre-Trained Model</strong></a></p><ul><li>To begin with, we need to download the latest pre-trained network for the model we wish to use. This can be done by simply clicking on the name of the desired model in the table found in TensorFlow 2 Detection Model Zoo. Clicking on the name of your model should initiate a download for a *.tar.gz file.</li></ul><pre>pothole_training/<br>├─ ...<br>├─ pre-trained-models/<br>│  └─ ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/<br>│     ├─ checkpoint/<br>│     ├─ saved_model/<br>│     └─ pipeline.config<br>└─ ...</pre><h4>7.2. Configure the Training Pipeline</h4><ul><li>Now that we have downloaded and extracted our pre-trained model, let’s create a directory for our training job. Under the training_demo/models create a new directory named my_ssd_resnet50_v1_fpn and copy the training_demo/pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/pipeline.config file inside the newly created directory. Our training_demo/models directory should now look like this:</li></ul><pre>training_demo/<br>├─ ...<br>├─ models/<br>│  └─ my_ssd_resnet50_v1_fpn/<br>│     └─ pipeline.config<br>└─ ...</pre><p>In order to train Object Detection Model modify the pipeline.config file:</p><p><strong>Line 3</strong> — <strong>num_classes</strong>: 1 <em># Set this to the number of different label classes eg- if we have two classes(cat and dog) then num_classes will be 2</em></p><p><strong>Line 131 — batch_size: </strong>8 <em># Increase/Decrease this value depending on the available memory (Higher values require more memory and vice-versa).</em></p><p><strong>Line 161 — fine_tune_checkpoint:</strong> “pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0” # Path to checkpoint of pre-trained mode.</p><p>Here, we have to put path of downloaded pre-train model for transfer learning</p><p><strong>Line 167 — fine_tune_checkpoint_type: </strong>“detection” <em># Set this to “detection” since we want to be training the full detection model</em></p><p>If we have classification problem then make it as “classification”</p><p><strong>Line 168 — use_bfloat16: </strong>false <em># Set this to false if you are not training on a TPU.</em></p><p><strong>Line 172 — label_map_path: </strong>“annotations/label_map.pbtxt” <em># Path to label map file</em></p><p><strong>Line 174 — input_path:</strong> “annotations/train.record” <em># Path to training TFRecord file</em></p><p><strong>Line 182 — label_map_path:</strong> “annotations/label_map.pbtxt” <em># Path to label map file</em></p><p><strong>Line 186 — input_path:</strong> “annotations/test.record” <em># Path to testing TFRecord</em></p><p>Once the above changes have been applied to our config file, go ahead and save it.</p><h3>8. Training the Model</h3><p>Before we begin training our model, let’s go and copy the TensorFlow/models/research/object_detection/model_main_tf2.py script and paste it straight into our training_demo folder. We will need this script in order to train our model.</p><p>Now, to initiate a new training job, open a new Terminal, cd inside the training_demo folder and run the following command:</p><pre>python model_main_tf2.py --model_dir=models/my_ssd_resnet50_v1_fpn --pipeline_config_path=models/my_ssd_resnet50_v1_fpn/pipeline.config</pre><p>Once the training process has been initiated, you should see a series of printouts similar to the one below (plus/minus some warnings):</p><h3>9. Exporting a Trained Model</h3><p>Once your training job is complete, you need to extract the newly trained inference graph, which will be later used to perform the object detection. This can be done as follows:</p><ul><li>Copy the TensorFlow/models/research/object_detection/exporter_main_v2.py script and paste it straight into your pothole_training folder.</li><li>Now, open a Terminal, cd inside your pothole_training folder, and run the following command:</li></ul><pre>python .\exporter_main_v2.py --input_type image_tensor --pipeline_config_path .\models\my_ssd_resnet50_v1_fpn\pipeline.config --trained_checkpoint_dir .\models\my_ssd_resnet50_v1_fpn\ --output_directory .\exported-models\my_model</pre><p>After the above process has completed, you should find a new folder my_model under the pothole_training/exported-models, that has the following structure:</p><pre>pothole_training/<br>├─ ...<br>├─ exported-models/<br>│  └─ my_model/<br>│     ├─ checkpoint/<br>│     ├─ saved_model/<br>│     └─ pipeline.config<br>└─ ...</pre><h3>10. Inference Pipeline</h3><h4>10.1. Putting everything together</h4><p>The code shown below loads an image, runs it through the detection model and visualizes the detection results, including the keypoints.</p><p>Note that this will take a long time (several minutes) the first time you run this code due to tf.function’s trace-compilation — on subsequent runs (e.g. on new images), things will be faster.</p><p>Here are some simple things to try out if you are curious:</p><ul><li>Modify some of the input images and see if detection still works. Some simple things to try out here (just uncomment the relevant portions of code) include flipping the image horizontally, or converting to grayscale (note that we still expect the input image to have 3 channels).</li><li>Print out detections[‘detection_boxes’] and try to match the box locations to the boxes in the image. Notice that coordinates are given in normalized form (i.e., in the interval [0, 1]).</li><li>Set min_score_thresh to other values (between 0 and 1) to allow more detections in or to filter out more detections.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b632630c72808581d24c95ff1a36742a/href">https://medium.com/media/b632630c72808581d24c95ff1a36742a/href</a></iframe><h3>11. Inferences Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7MAcOo7vLf4w_AvP8Ph_vA.png" /></figure><h3><strong>13. FUTURE ENHANCEMENTS</strong></h3><p>In a single model, there will be a development of traffic signal detection, and lane detection and all the detections will be done in a very single model. For security purposes they are going to create protective barriers, it is going to increase the potential vulnerabilities, and the usage of the bandwidth is going to be very efficient. They are going to provide specialization and abstraction. There is going to be one layer that misses the security, deployment and prototyping link between all the devices.</p><h3>14. References</h3><ol><li>C. Ng, T. Law, F. Jakarni, and S. Kulanthayan, “Road infrastructure development and economic growth,” <em>in IOP conference series: materials science and engineering</em>, IOP Publishing, vol. 512, no. 1, Article ID 012045, 2019. View at: <a href="https://scholar.google.com/scholar_lookup?title=Road%20infrastructure%20development%20and%20economic%20growth&amp;author=C.%20Ng&amp;author=T.%20Law&amp;author=F.%20Jakarni&amp;author=S.%20Kulanthayan&amp;publication_year=2019">Google Scholar</a></li><li>S. Rahman, <em>A; Patel, “Pothole Image Dataset. Kaggle</em>, 2020, <a href="https://www.kaggle.com/sachinpatel21/pothole-image-dataset/">https://www.kaggle.com/sachinpatel21/pothole-image-dataset/</a>.</li><li>W. health, <em>Statistics, “Injury Deaths Rise in Rank</em>, 2008, <a href="https://www.who.int/violence_injury_prevention/key_facts/VIP_key_fact_3.pdf/">https://www.who.int/violence_injury_prevention/key_facts/VIP_key_fact_3.pdf/</a>.</li><li>K. C. Wang, “Challenges and Feasibility for Comprehensive Automated Survey of Pavement conditions,” in <em>Proceedings of the Applications of Advanced Technologies in Transportation Engineering (2004)</em>, pp. 531–536, Beijing, China, May 2004. View at: <a href="https://scholar.google.com/scholar_lookup?title=Challenges%20and%20Feasibility%20for%20Comprehensive%20Automated%20Survey%20of%20Pavement%20conditions&amp;author=K.%20C.%20Wang">Google Scholar</a></li><li>K. Chang, J. Chang, and J. Liu, “Detection of pavement distresses using 3d laser scanning technology,” in <em>Proceedings of the Computing in Civil Engineering (2005)</em>, pp. 1–11, Cancun, Mexico, May 2005. View at: <a href="https://scholar.google.com/scholar_lookup?title=Detection%20of%20pavement%20distresses%20using%203d%20laser%20scanning%20technology&amp;author=K.%20Chang&amp;author=J.%20Chang&amp;author=J.%20Liu">Google Scholar</a></li><li>Z. Hou, K. C. Wang, and W. Gong, “Experimentation of 3d pavement imaging through stereovision,” in <em>Proceedings of the International Conference on Transportation Engineering 2007</em>, pp. 376–381, Chengdu, China, July 2007. View at: <a href="https://scholar.google.com/scholar_lookup?title=Experimentation%20of%203d%20pavement%20imaging%20through%20stereovision&amp;author=Z.%20Hou&amp;author=K.%20C.%20Wang&amp;author=W.%20Gong">Google Scholar</a></li><li>P. Harikrishnan and V. P. Gopi, “Vehicle vibration signal processing for road surface monitoring,” <em>IEEE Sensors Journal</em>, vol. 17, no. 16, pp. 5192–5197, 2017.View at: <a href="https://scholar.google.com/scholar_lookup?title=Vehicle%20vibration%20signal%20processing%20for%20road%20surface%20monitoring&amp;author=P.%20Harikrishnan&amp;author=V.%20P.%20Gopi&amp;publication_year=2017">Google Scholar</a></li><li>B. X. Yu and X. Yu, “Vibration-based system for pavement condition evaluation,” in <em>Proceedings of the Applications of Advanced Technology in Transportation</em>, pp. 183–189, Chicago, IN, USA, August 2006. View at: <a href="https://scholar.google.com/scholar_lookup?title=Vibration-based%20system%20for%20pavement%20condition%20evaluation&amp;author=B.%20X.%20Yu&amp;author=X.%20Yu">Google Scholar</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a422ea4b5844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content-based Journal Recommendation Engine]]></title>
            <link>https://medium.com/@pratiksahu147/content-based-journal-recommendation-engine-92ff8d5249e8?source=rss-302684a33a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/92ff8d5249e8</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Prateek Sahu]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 03:17:19 GMT</pubDate>
            <atom:updated>2023-02-01T09:44:54.593Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>When you watch your favourite song on youtube, read blog of your interest on medium and while shopping at amazon, you’ll get recommendations based on your interest and most of the time you like those recommendations. Here, we’ll discuss how we can build these kind of RecSys end-to-end. I promiss you’ll build your own recommendation system, if you just follow this blog.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4rUIEYFIEmk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4rUIEYFIEmk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4rUIEYFIEmk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/07f59b87e2c788082c2ac93024f97558/href">https://medium.com/media/07f59b87e2c788082c2ac93024f97558/href</a></iframe><h3><strong>Business Problem</strong></h3><p>A huge number of academic papers are coming out from a lot of conferences and journals these days. In these circumstances, most researchers rely on key-based search or browsing through proceedings of top conferences and journals to find their related work. To ease this difficulty, we propose a Personalized Academic Research Paper Recommendation System, which recommends related articles, for each researcher, that may be interesting to her/him. In this paper, we first introduce our web crawler to retrieve research papers from the web. Then, we define similarity between two research papers based on the text similarity between them. Finally, we propose our recommender system developed using collaborative filtering methods. Our evaluation results demonstrate that our system recommends good quality research papers.</p><h3>Content-based recommendation system</h3><p>Content-based recommendation systems recommend items to a user by using the similarity of items. This recommender system recommends products or items based on their description or features. It identifies the similarity between the products based on their descriptions. It also considers the user’s previous history in order to recommend a similar product.</p><p>Example: If a user likes the novel “Tell Me Your Dreams” by Sidney Sheldon, then the recommender system recommends the user to read other Sidney Sheldon novels, or it recommends a novel with the genre “non-fiction”. (Sidney Sheldon novels belong to the non-fiction genre).</p><p>As I mentioned above, we are using goodreads.com data and don’t have user reading history. Hence, we have used a simple content-based recommendation system. We are going to build two recommendation systems by using a book title and book description.</p><p>We need to find similar books to a given book and then recommend those similar books to the user. How do we find whether the given book is similar or dissimilar? A similarity measure was used to find this.</p><h3>Data</h3><p><a href="https://www.kaggle.com/datasets/Cornell-University/arxiv">Journal dataset</a> is a mirror of the original ArXiv data. Because the full dataset is rather large, this dataset provides only a metadata file in the json format. This file contains an entry for each paper, containing:</p><p>id: ArXiv ID (can be used to access the paper, see below)</p><p>submitter: Who submitted the paper</p><p>authors: Authors of the paper</p><p>title: Title of the paper</p><p>comments: Additional info, such as number of pages and figures</p><p>journal-ref: Information about the journal the paper was published in</p><p>doi: [<a href="https://www.doi.org]%28digital/">https://www.doi.org](Digital</a> Object Identifier)</p><p>abstract: The abstract of the paper</p><p>categories: Categories / tags in the ArXiv system</p><p>versions: A version history</p><h3><strong>Exploratry Data Analysis</strong></h3><p>In EDA, we’re going to see only data visualisations and their descriptive analysis, you can see all code of EDA on GitHub. It’s easy to understand, readable and well-maintained as I promise you’ll get end-to-end experience in this blog. The research paper dataset itself is very large so instead of taking the whole data let’s pick only those research papers which are published after 2020 which is 336,303 million.</p><h4><strong>Title</strong></h4><ol><li>Title word count of 75% of papers is 12 word per article.</li><li>Maximum word count for Title is 43 words and minimum is 1 word.</li><li>We can see there’re 3 duplicate Title with unique ID.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*dmW7vEJu1bdWwHNH_Uvk-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*JhvuTJT09ITW7ZTof7YhGg.png" /></figure><h4>Abstract</h4><ol><li>Word count for abstract for 74% of research paper is 198 word per article.</li><li>Maximum word count for abstract is 498 words and minimum is 3 words.</li><li>We also have 2 duplicate abstract in our dataset.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*A4mn5v2S4JPVKWJ-sYK6nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*ufKy0DMT9XF5YlNu9GM-PQ.png" /></figure><h4>General Category</h4><ol><li>75% of papers belongs from atmost 2 general categories.</li><li>Maximum number of general category per artical is 6 and minimum is 1.</li><li>Maximum article belongs from ‘CS’ category that is 83632 since year 2021.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*XVVKZjwrtuU2_aqEcrdMWQ.png" /></figure><h4>Category (Sub-Category)</h4><ol><li>75% of papers belongs from atmost 2 sub categories.</li><li>Maximum number of sub-category per artical is 8 and minimum is 0.</li><li>We’ve 29492 articals which sub-category is untagged.</li></ol><h3>Data Preprocessing</h3><p>In this case study we are majorly dealing with text data when it’s a case of text so the most important task to do is text preprocessing. Raw text data might contain unwanted or unimportant text due to which our results might not give efficient accuracy, and might make it hard to understand and analyze. So, proper pre-processing must be done on raw data.</p><h4>Remove punctuation</h4><p>The following code removes this set of symbols [!”#$%&amp;’()*+,-./:;&lt;=&gt;?@[\]^_`{|}~]:</p><h4>Remove stop words</h4><p>In general, stopwords are the most common words in a languagesuch as “and”, “an”, “at” in English, which are considered unnecessary and useless in text mining applications. These words can be pronouns (I, me, my, mine, myself, etc.), prepositions (on, in, next to, behind, under, around, etc.), conjunctions (once, until, when, why, since, after, etc.), articles (a, an, the), and auxiliary verbs (be, do, have, will, can, may, etc.).</p><h4>Lemmatization</h4><p>The aim of lemmatization[1], like stemming, is to reduce inflectional forms to a common base form. As opposed to stemming, lemmatization does not simply chop off inflections. Instead it uses lexical knowledge bases to get the correct base forms of words.</p><h4>Stemming</h4><p>The aim of the stemming is to take words as they occur in a text to reduce them to root forms by removing their affixes such as prefixes (cutting off the beginning of the word) and suffixes (cutting off the end of the word) according to some grammatical rules.</p><p>We can apply stemming to derivatives of the word such as number (cat, cats), tense (play, played, playing), gender (actor, actress), pronouns (I, me, my, mine), person (hate, hates), and aspect (become, became). For instance, the words select, selected, selecting, selects all can be stemmed to the word “select”. As it is seen, we cut off the end of the words which are semantically related to their root form. In this way, we reduce the number of words in memory space and save time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Hg_XwMtH_Ukb-uUc-mXrQ.png" /></figure><h3>Data Transformation and Data Modeling</h3><p>Everything in machine learning is numbers wether it is text, image or audio data at the end we’ve to transform our data into numbers.</p><p>Let’s discuss the technique that we’re going to use for data transformation.</p><h4>TF-IDF Vectorizer</h4><p>TF-IDF stands for term frequency-inverse document frequency. TF-IDF weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus.</p><ul><li><strong>Term Frequency (TF)</strong>: is a scoring of the frequency of the word in the current document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. The term frequency is often divided by the document length to normalize.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*rkM0DvWHRgYomkHQ.png" /></figure><ul><li><strong>Inverse Document Frequency (IDF)</strong>: is a scoring of how rare the word is across documents. IDF is a measure of how rare a term is. Rarer the term, more is the IDF score.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*Bd5qNiciAC6OMJYH.png" /></figure><h4>Word2vec</h4><p>Word2vec is <strong>a technique for natural language processing published in 2013</strong>. The word2vec algorithm uses a neural network model to learn word associations from a large corpus of text. Once trained, such a model can detect synonymous words or suggest additional words for a partial sentence.</p><h4>Data Modeling</h4><p>Here Data Modeling will be done on the bases of cosine similarity, we are not going do any training.</p><p>Core Functionality —</p><ul><li>Transform data into numbers by choosing any of the technique from Bag of Words, TF-IDF or Word to Vec.</li><li>When user select any journal, it’ll take the Title, Abstract or both and find the distance of selected journal with rest of them that are stored into database. Sort the distances into increasing order and show to those journals to user which has smallest distance.</li></ul><p>In the below code we have <strong>bagOfWords_tfidf_model</strong> function which takes parameter <strong>doc_id</strong>(selected journal document id), <strong>num_result</strong>(number of recommendations), <strong>data</strong>(text data) and <strong>features</strong>(transformed data after tfidf or BOW).</p><ul><li>If you see in the line 2 and 17 below code, we’ve used pairwise_distance function that is used for finding cosine simarity</li><li>Line-4 : Sort the distance into increasing order.</li><li>Line 8–13 : Featch the Record from Dataset</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anznJNioISpohVZgA_t9Hw.png" /></figure><h4>Results</h4><h4>Journal Recommendation based on Title</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdAndYSiPntNeLodj0gUAA.png" /></figure><h4>Journal Recommendation based on Abstract</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y2WE0y87gJVPzgM574Slw.png" /></figure><h4>Journal Recommendation based on Title and Abstract</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxuu2HkVdexqSQLLeBmnmQ.png" /></figure><p>Finally we are complete with our Journal Recommendation. If you have any kind of query you can write into comment box, I’ll try to solve your query.</p><h3>Referances</h3><p><a href="https://journals.tubitak.gov.tr/cgi/viewcontent.cgi?article=1344&amp;context=elektrik">[1] </a><a href="https://journals.tubitak.gov.tr/cgi/viewcontent.cgi?article=1344&amp;context=elektrik">MUHİTTİN IŞIK</a><a href="https://journals.tubitak.gov.tr/cgi/viewcontent.cgi?article=1344&amp;context=elektrik">— The impact of text preprocessing on the pr ocessing on the prediction of r ediction of review ratings</a></p><p>[2] <a href="https://medium.com/greyatom/an-introduction-to-bag-of-words-in-nlp-ac967d43b428">An Introduction to Bag-of-Words in NLP</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2uxXPzm-7FY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2uxXPzm-7FY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2uxXPzm-7FY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfb957d86565c8be92112b30ceac5e27/href">https://medium.com/media/cfb957d86565c8be92112b30ceac5e27/href</a></iframe><p><a href="https://www.kaggle.com/code/marlesson/building-a-recommendation-system-using-cnn-v2/notebook">Building a Recommendation System Using CNN - v2</a></p><p><a href="https://arxiv.org/pdf/1701.04783.pdf">https://arxiv.org/pdf/1701.04783.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92ff8d5249e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Similar Question Detection of using One Shot Learning and Siamese Network]]></title>
            <link>https://medium.com/@pratiksahu147/similar-question-detection-of-using-one-shot-learning-and-siamese-network-afdfcecddce?source=rss-302684a33a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/afdfcecddce</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[siamese-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ocr-tesseract]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prateek Sahu]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 18:26:46 GMT</pubDate>
            <atom:updated>2022-07-18T18:26:46.080Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog we’ll talk about similar objects, it can be Images, Voice, Music, Sentances, programing language code, answer sheet of exam, human behaviour etc. Let we have two similar objects so as a human being we can easily say these two objects are similar, but what if we’ve to do it for thousands or millions sets of two objects, if we do it manually we’ve to pay cost, cost in terms of energy and time for similarity detection. But In the world of automatation it can be possible in very less time. The only constraint is data, if we have data we can achive the automataion procress.</p><p>Data is one of the key challenge in machine learning, if we have large amount of data the accuracy of our ML model become more accurate. But most of the time data is not sufficient for model training.</p><p><strong>Problem Statement: </strong>Every semester Universities conduct exams for thier students for degree completion where some of the questions in the exam comes from previously years question papers, most of the universities follows this trend. Here,we have data in the form of pictures of questions, we’ve n no. similar questions that we’ve collected from various Question Banks in the form of pictures and the format of all pictures are same as you can see in the fig 2. University students wants an automatation system that can detect duplicate/similar questions occured in previous semesters exams during exam prepration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwX_s8krDIaAxkC4L4JgDg.jpeg" /><figcaption>Fig 1— Raw Data Sample</figcaption></figure><h3><strong>One Shot Learning</strong></h3><p>In deep learning large amount of data is the biggest concern for model training for similarity detection problem, but it isn’t mean we can’t train our DL model. we can do it by one shot learning algorithm with few samples of data.</p><p>Let we have three cluster of different category <strong>triangle, circle </strong>and <strong>rectangle </strong>and each set has 6 similar data points.</p><figure><img alt="Cluster of three different category tringle , rectangle and circle." src="https://cdn-images-1.medium.com/max/800/1*B8nLOmJg_JCCcU4y52ErOQ.jpeg" /><figcaption>Figure 1</figcaption></figure><p>Set 1 : S1 = {T1, T2, T3}</p><p>Set 2 : S2 ={C1, C2, C3}</p><p>Set 3 : S3 = {R1, R2, R3}</p><p>As we can see we have few data, but we can generate more sensible data for us with the help one shot learning algo. It make combinatation of similar data points and dissimilar data points.</p><h4>Combination of similar data points</h4><p>we have three sets S1, S2 and S3 and each set has 6 elements, we want to make combinatation of similar data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*fayVaPTjCFCD3zemHcmW7w.png" /><figcaption>Combination Formula</figcaption></figure><p>If we put this combination formula multiply by total no. of sets, we’ll get total no. of combinations of similar pairs. Here, <strong>n</strong> is total no. of items in a set and <strong>r </strong>no. of choosed item from a set.</p><p><strong>Total no. of combination of similar pairs = C(n, r) * Total no. of sets</strong></p><p>C(3, 2) * 3 = 9</p><p>In Table 1, we’ve three columns, <strong>Feature 1</strong> contains first item of pair and <strong>Feature 2</strong> contains second item of pair and <strong>Is Similar</strong> is binary representation of pair whether a pair is similar or not. Here we’ve 9 rows which are the combinations of simalar pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOyCEYY3rNRATgKasYowGg.png" /><figcaption>Table 1</figcaption></figure><h4>Combination of non-similar data points</h4><p>In above we’ve seen how to prepare conbination of similar pairs now we’re going to see how can we create non-similar pairs.</p><p>In order to create non similar pairs we’ll use the same <em>combination formula </em>but in different way<em>. I</em>f we put this combination formula where, <strong>n</strong> is total no. of sets and <strong>r </strong>total no. of choosed set from all sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdW2WvY45nmaz_llSR13Qw.png" /></figure><p>Total no. of non similar pairs = C(3, 2 ) * 3 * 3 = 27</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whDKvBp1VHwOlqBry1fbIw.png" /><figcaption>Table 2</figcaption></figure><p>Table 2 is extended version of Table 1 all feature columns are same as Table 1, <strong>Feature 1</strong> contains first item of pair and <strong>Feature 2</strong> contains second item of pair and <strong>Is Similar</strong> is binary representation of pair whether a pair is similar or not. Here we’ve 27 rows which are the combinations of non simalar pairs.</p><p>So, that’s all about the one shot learning, as of now we’ve seen it with toy example , now it’s time see real world problem and its implementation. We’ll end up <strong>one shot learning </strong>with a dataset which is similar to the Table 1 and Table 2.</p><h3><strong>Data Extraction</strong></h3><p>In this section we’re going to extract questions from given images of questions. In order to get output we’ve to follow all steps that are mentioned in Fig-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2MLcxfzga0nUSpwXaBmHUw.jpeg" /><figcaption>Fig-2</figcaption></figure><p>In fig-3 we’ve image which have 4 questions and all questions are similar, In the further steps we’ll extract questions from this image and will apply one shot learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHLaToX1O2DVJNUlP2sF0A.jpeg" /><figcaption>Fig-3</figcaption></figure><h4><strong>Step 1 : Convert text from image</strong></h4><p>In step 1, we’re going to convert the image in the form of text. In order to get text we’ll use <a href="https://pypi.org/project/opencv-python/"><strong>open cv</strong></a><strong> </strong>that is use for read image and <a href="https://medium.com/@marioruizgonzalez.mx/how-install-tesseract-orc-and-pytesseract-on-windows-68f011ad8b9b"><strong>pytesseract</strong></a><strong> </strong>which help to recognize optical character in image.</p><p>Try to understand code throughly line by line so you’ll get good understanding of this case study. I’ll also explain the important and core part of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fm3IYvBHpbRwLwoTDG9Lyg.png" /><figcaption>Code 1</figcaption></figure><p>Let’s have look on the code, we have textExtration function that take image as an input and returns text from image. We’ll see textExtraction function into two section —</p><ol><li><strong>Line no. 2–8 : </strong>In these line first we read our given image then convert it into grayscale form. In order to get text from the image we need binarized image so we use cv2.threshold funtion from opencv. Now we’re all set to use tessereact, here we’ll not discuss more about configuration part of tessereac, if you want to know more about it refer documentation of <a href="https://tesseract-ocr.github.io/">tessereact</a>. In line no. 8, we apply tessereact.image_to_data function which takes binarized image as parameter and returns dictionary.</li><li><strong>Line no. 9–29 : </strong>These lines are totally optional for us because these lines are used only for text annotation. It recognize text in the image basically it create box around the word as you can see in the fig-4. In line 18 we itterrate all words that we get from tessereact and stored into list. and returns text the we get from image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5YLo7VmpYhgI2oEcJ86qg.png" /></figure><h4><strong>Step 2: Extract question from the text with the help of RegEx</strong></h4><p>Currently we have samples that contain only questions part, what if we have whole page where we have queations and its answers. Then we need to extract only questions part from the whole text and that we can do with the help of regex. As of now we have sample images which contain only question so we are not going to apply regex. In code 2 we call textExtration function which return text from of the image. In first print statement we can see the data type of the text that is string type and secound print statement shows the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6koEcE6HS9ceqDsRmeBfgg.png" /><figcaption>Code 2</figcaption></figure><p>Here we’ll split our similar questions with “Or” that are shown in the red box in the above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzwZNZOxNRitI44ZlH8PFw.png" /></figure><h4><strong>Step 3 : Apply one shot learning on similar/non-similar question</strong></h4><p>In the below code snippet we have function <strong>getQuestionPartDataset</strong> which take list of all question, delimiter in our case delimiter is “Or”, subject name eg. Data Communication, Operating Systems etc.. and stream name eg. Electronics and Comm. , CSE, Mechanical Engineering etc..</p><h4><strong>let break this function into parts —</strong></h4><ul><li><strong>Generating Similar Question Pair</strong> (Line 16–20) : Here use delimited questions and split with delimiter, so we get a list of splited question then we pass that list into <strong>product</strong> function, it gives us combination of similar questions. As you can see in line 20 we append a tupple of pair of questions, subject name, stream name and IsSimilar.</li><li><em>Note : Similar question denoted by 1 (</em><strong><em>similar =1</em></strong><em>) and non-similar denoted by 0 (</em><strong><em>not_similar</em></strong><em>)[As you can see in line 6–7]</em></li><li><strong>Generating Non-Similar Question Pair </strong>(Line 23–29) : Currently in <strong>allQuestionList</strong>(parameter) has only similar questions with delimiter “<strong>Or”. </strong>Here we use nested loop for getting non-similar questions, first loop take first question from <strong>allQuestionList </strong>and split it then nested loop take next question from <strong>allQuestionList </strong>and split this also. Now we have two splited pair of questions and we have nothing similar between both pair. So, now we can create combination non-silimar question with the help of <strong>product </strong>function by passing our both splited list into it.</li><li><strong>Remove Duplicate Question Pair </strong>(Line 35) : In the below figure you can able to see for row 0, 3 and 4 have duplicate pair. So, we have to remove those records from our dataset. We can drop those records with pandas function <strong>DataFrame</strong>.<strong>drop()</strong>, here we add conditions for duplicacy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kjGTnki-Q4K7-a69rmXMw.png" /><figcaption>Fig-4 : Duplicate Quesion Pair</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aee5de81de73b26b8dd4081fa86eb72/href">https://medium.com/media/9aee5de81de73b26b8dd4081fa86eb72/href</a></iframe><h3>Final Dataset</h3><p>We are ready with our final data that we are going to use for classification technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6GrkLqb3nN2lGYLIoCxSA.png" /><figcaption>Final Dataset</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afdfcecddce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Music Generate by Deep RNN - Case Study]]></title>
            <link>https://medium.com/@pratiksahu147/music-generate-by-deep-rnn-case-study-d8f979e6c104?source=rss-302684a33a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f979e6c104</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Prateek Sahu]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 06:53:13 GMT</pubDate>
            <atom:updated>2021-09-22T06:53:13.738Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A full guide to generate “meaning full” music.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*jBxd_q-KHFZEOJB5DEN-bA.jpeg" /></figure><p>Have you ever wondered, will our computer generate music for us by some computation only? — May be, Yes..</p><p>In the world of A.I, it’s possible to compose meaning full music that makes your mood harmonious.</p><blockquote>In this case study, I’ll try to cover all the aspect that will generate music by Deep learning and try to explain each concept step by step that we’re going to use in this case study with code.</blockquote><p><strong>Before delving deeper into the case study, I’d like to show ingredient of our music director.</strong></p><ol><li><strong>Data Collection</strong></li><li><strong>Data Preparation</strong></li><li><strong>Model Architecture</strong></li><li><strong>Model Training</strong></li></ol><p>Note :</p><h3>1. Data Collection</h3><p>— <strong>Data Understanding</strong></p><p>How music is generate?</p><p>— If we talking about Indian classical music there are “SARGAM”, we can compose very quality kind music with the help of these sargam <strong>- sa , re, ga, ma, pa, dha, ne </strong>with the permutation and combination of these notes, we can generate beautiful harmonious music for others and us.</p><p>— If we talking about western music things are almost similar here we use English notation <strong>C, D, E, F, G, A, B </strong>and we can compose beautiful music with the help of ABC notation.</p><p>— If you are curious to know more about music notations, I’d recommend to <a href="https://en.wikipedia.org/wiki/Musical_note"><strong>read this</strong></a><strong> </strong>article, it’s equally important to have little bit domain knowledge of project/case study.</p><p><strong>Types of data for music -</strong></p><ol><li>Sheet Music</li><li>ABC Notation data</li><li>MIDI data</li><li>MP3 (basically we avoid this, you’ll know soon)</li></ol><p>So, for this case study we’re going to use ABC Notation data, this dataset consist two parts:</p><ul><li>Settings of music</li><li>Notations/Tabs of Instrument (Sargam)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-_svazLiBwE8vDJ4UmeUw.jpeg" /></figure><p>You can see the sample of data, where initial part is settings and lower part is music notations.</p><p>I think by just seeing this sample of data set , you probably get it how things going to work and generate music for us.</p><p>The picture will be more clear, when you know how these music note going to play.</p><p>Do one thing click at the <a href="https://www.abcjs.net/abcjs-editor.html">link</a> and play the music that music is generated when we add this kind of sample(ABC notation data) to “Music Notation editor”.</p><blockquote><strong>Here is a link for dataset — </strong><a href="http://abc.sourceforge.net/NMD/"><strong><em>data</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*U-D-RhBe_vJ3pLs_SN9_hQ.gif" /></figure><p>Now we move forward to next step — Data Preparation.</p><h3><strong>2. Data Preparation</strong></h3><p>Data preparation is very important step, In the context of deep learning we don’t need to do feature engineering because DL will learn feature by itself, that is one of the reason why deep learning become more popular.</p><blockquote>Large data leads to good deep learning models</blockquote><p>But the problem is resources, if we directly push so big data for training in RAM then there will be very high chance of crashing of our computer machine. That’s why we need to do Data Preparation.</p><p>In order to beware this problem, we generate our data batch wise for training.</p><h4>Generate data batch wise</h4><p>In order to send data to RAM we will create batches of whole data.</p><p>I’d like to show you 3D visualization how our data stores in batches, this part is most important and challenging task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*thk2m6ppr-gNOvj5CKdqoQ.jpeg" /></figure><p>We create ‘n’ number of batches for training, during training each batch goes to RAM and trained it for model.</p><p>Here we have X-train and Y-train , we create “Y-train” from “X-train”.</p><p>Let first talking about “X-train”, we have “samples” and “Sequence of words/Music notes” , In whole context we can say we’ve matrix of (sample size * Sequence of music notes), where each block store “word/music note” from original dataset.</p><p><em>Note : Don’t worry about data preprocessing(like removing space, html tag, lower case etc), Deep Learning will take care of it and learn from it.</em></p><p>let suppose, first block of our X-train contain “C” note then next block in same row contain “G” in a sequence it will fill.</p><p><em>N</em>ote : Notes does not stores randomly, it stores in the same sequence as we have in original data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*n6L0ygyGFGjMa29FzBnWhw.png" /></figure><p>If you open this image, you’ll see index and each index has some unique character, this we called vocabulary.</p><p>Means in our whole dataset each element belongs to this vocabulary.</p><p>So, we talked about X-train, now we’re going to talk about Y-train.</p><p>Now before talking about Y-train, I’d like to talk about what exactly we want as a predicted output.</p><p>Whenever we give some music note as an input, we wants that it can predict next possible music note character of music.</p><p>So, when we create Y-train, we filled it in such a way that whatever music note present in first block(row wise) of X-train then the next element of first block going to store at first block of Y-train. By this method we will fill the all blocks of Y-train.</p><p>Now the question is why are we using 3D matrices for Y-train ?</p><ul><li>Size of Y-train is (sample <strong>x</strong> sequence of notes <strong>x </strong>vocabulary size)</li><li>Instead of add directly music notes into Y-train, we make 3rd axis with the size of vocabulary, and the index value will be unique notes/vocabulary.</li><li>let suppose, we’ve to add “C” note into Y-train then we see index of vocabulary axis and write “1” at the index of “C” and others will be “0”. You’ve also see this kind of thing in <strong>one-hot-encoding.</strong></li></ul><blockquote>example — Let our Y-train is size of Y[5 * 8 *3] , and we have to add “C” in the first block of <strong>Y </strong>where the index of 3rd axis is “A”, “B”, “C”.</blockquote><blockquote>Then add<strong> — Y[0][0][‘C’] = 1.</strong></blockquote><h3>3. Model Architecture</h3><p>This part is going to be interesting and simple, in this part we’re going to learn “Char RNN”.</p><h4>Char RNN</h4><ul><li>In a very simple way we can say, Char RNN gives an output for each corresponding input, it is one kind of many-to-many RNN.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*CHRfukHzGLnWL__EnWKF8g.jpeg" /><figcaption>Char RNN</figcaption></figure><p>I’d like to show you model architecture that we’re going to use for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*LITHawVmdfZVf-JorI7kPw.jpeg" /><figcaption>Model Architecture</figcaption></figure><p>Now I’m going to tell you what exactly happen in this picture.</p><ul><li><strong>Input — </strong>Take music notes as an input, remember don’t confuse with time stamp means the number of time stamp is depends on input. let suppose if we have 4 input then this architecture layer will be 4 times in a sequence.</li><li><strong>Embedding- </strong>Basically embedding is a technique to learn the similarity of vector , it gives us dense vector from a scalar value(we converted text into scalar) where each dense vector has some numbers that shows how similar this character/word with others. For knowing the mathematics intuition watch this <a href="https://www.youtube.com/watch?v=Fuw0wv3X-0o&amp;t=910s"><em>video</em></a><em>.</em></li><li><strong><em>LSTM — </em></strong>LSTM is a special type of RNN. It’s a very important part of architecture , of course other part are also equally important. but most of training part is depend on LSTM. If you don’t know what is LSTM exactly <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">click here</a>, read this beautiful blog.</li><li>Here we’ll see how we can achieve “Char RNN” architecture for our case study. If we talk about code, It’s very easy to achieve char RNN. we’ve to enable these parameter “<strong>return_sequence = True</strong>” and “<strong>stateful = True</strong>” in LSTM that’s it. but we’ll go little bit deep and try to understand what exactly these parameter do for us.</li></ul><ol><li><strong>return_sequence — </strong>When you enable this parameter, you will get the output for each corresponding input of sequence. Basically you will achieve “Char RNN” which is one of type of many-to-many RNN.</li><li><strong>stateful — </strong>It is used when we train our model batch wise, and also an important parameter to achieve the functionality of char RNN. First we see what happen if we disable this parameter —If you studied RNN you know very well that first sequence of RNN takes two things zero weight and given input and gives two output one goes to next sequence of RNN another give as predicted value. And this thing happen for every batches that we’ve created.</li></ol><p>— So, now what is the problem?</p><p>— My question is to you , Is it okay to give zero weight for every batch? No, because it may affect for model accuracy.</p><p>— So what we do, we enable <strong>stateful </strong>parameter whenever next batch come for training, it take some trained weight from previous batch as an input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Gu9GE9tB5XiGYwf69nAROw.jpeg" /><figcaption>Effect of stateful</figcaption></figure><ul><li><strong>Time Distributed —</strong> Before this I’d like tell you, how 1st layer look like in LSTM when we add no. of units of LSTMs as a first parameter.</li></ul><p>— eg. if we give 256 as a first parameter(no. of LSTM units) that means it give 256 LSTM parallel for 1st layer, and each parallel LSTM takes same input and give 256 output for next layer.</p><p>— Now come back to our topic <strong>Time Distribution, </strong>on top of last layer we add dense layer of Time Distribution which takes input from last layer of parallel LSTMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MWd5jXVCBYyJY1AgyaQ7Ug.jpeg" /></figure><ul><li><strong>Activation — </strong>I think you know very well what activation does. if not then no worry <a href="https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/">read this</a>. So here we add activation function that predict which music note is best.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*7ZELoVVnjQoR4mQL7U5BVA.png" /><figcaption>Code for Model Architecture</figcaption></figure><blockquote>Hurrah!!! We’ve done with model architecture , now time to train our model.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f979e6c104" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>