<?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 Ravindra Sharma on Medium]]></title>
        <description><![CDATA[Stories by Ravindra Sharma on Medium]]></description>
        <link>https://medium.com/@ravindrasharma-12517?source=rss-e92edf40ff2d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*worilevDiwqEkXMSeGoSoQ.jpeg</url>
            <title>Stories by Ravindra Sharma on Medium</title>
            <link>https://medium.com/@ravindrasharma-12517?source=rss-e92edf40ff2d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:29:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravindrasharma-12517/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[Data Science: A Business Perspective]]></title>
            <link>https://medium.com/swlh/data-science-a-business-perspective-3bd1b8e65557?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd1b8e65557</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 07:01:02 GMT</pubDate>
            <atom:updated>2024-08-22T04:57:26.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>Turning Data into Strategic Value</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qqjQQ0wW37Lbvkx50zPxg.jpeg" /><figcaption>Source: <a href="https://medium.com/p/3bd1b8e65557/edit">NeedPix</a></figcaption></figure><h4>INTRODUCTION</h4><p>Amid the rush to deploy data-driven solutions, there is a tendency to neglect the <strong>fundamental groundwork of comprehending the business problem</strong>, its prerequisites, and limitations. While attention often gravitates towards flashy algorithms and state-of-the-art technologies, the reality remains that the triumph of any data science endeavor hinges on its capacity to precisely <strong>tackle the underlying business requirements.</strong></p><p>For instance, in a previous role, I encountered the challenge of streamlining the loan approval process. Rather than immediately resorting to the implementation of intricate machine learning models for risk assessment, it is paramount to delve into the essence of the business problem and constraints, gaining profound insights into the finance domain.</p><p>Initially, by instituting simple rules grounded on factors such as existing debts and past loan defaults of a customer we managed to propel the progress from 0 to 30% percent automation in loan approvals while concurrently mitigating risks <strong>saving 2–3 hours of daily manual operations work</strong>. This underscores the significance of grasping the intricacies of the business landscape to foster impactful and scalable solutions.</p><p>Below is a detailed, step-by-step process along with lot of real world examples outlining how to approach a <strong>problem from a business lens and formulate a strategy</strong> for developing a data-driven solution.</p><h4><strong>BUSINESS OBJECTIVE</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o91u_xnX7FXrRS2ZOckTog.jpeg" /><figcaption>Source: <a href="https://www.needpix.com/photo/download/531924/business-businesswoman-success-team-teamwork-profit-marketing-plan-innovation">NeedPix</a></figcaption></figure><p>As data scientists, our typical emphasis lies in enhancing model performance, honing on metrics such as accuracy and precision. Nonetheless, it’s imperative to acknowledge that for most organizations, tangible impacts on <strong>critical business metrics take precedence over sophisticated ML metrics and </strong>sometimes both are not same. Thus, it becomes essential to discern between ML Objectives and Business Objectives, comprehending the anticipated outcomes in quantifiable terms.</p><p>For instance, suppose you’re part of the Data Science team at an e-commerce enterprise, and your assignment <strong>entails boosting revenue for the upcoming fiscal year.</strong> In this scenario, our initial action would involve <strong>precisely defining a Business objective followed by aligning it with an ML Objective.</strong> Subsequently, tracking both objectives is imperative to furnish a comprehensive solution. Below, is<strong> </strong>an outline accompanied by hypothetical figures to aid comprehension.</p><ul><li><strong>Business Objective:</strong> Increase overall sales revenue by 10%-15% in the next fiscal year.</li><li><strong>ML Objective:</strong> Develop a recommendation engine that increases the average order value by suggesting complementary products with a 30%-40% likelihood of purchase.</li><li><strong>Importance of Tracking the Business Objective:</strong> While the ML team focuses on optimizing the recommendation engine, the broader goal is to boost sales revenue. If the recommendation engine<strong> improves the average order value but doesn’t contribute to a significant increase in overall sales (e.g., if it leads to fewer overall transactions)</strong>, the project might not align with the ultimate business objective.</li></ul><blockquote>Monitoring the business objective ensures that the ML project contributes to the company’s financial growth, not just technical metrics.</blockquote><h4><strong>BUSINESS CONSTRAINTS</strong></h4><p>Business constraints in data science projects encompass factors like <strong>latency, cost, and resource availability.</strong> Understanding and managing these constraints is crucial for delivering practical and effective solutions. Failure to consider these constraints can lead to inefficient processes, increased costs, and delays in project delivery. Data scientists must carefully balance technical excellence with business realities to ensure the success of their projects.</p><ul><li><strong>Budget/Cost:</strong> Every project has an outline budget, before jumping on to building data science solutions it is crucial to adhere to the budget and plan resources accordingly so that the solution gives a positive ROI eventually, to explain this consider a scenario of a telecom company’s endeavor to predict customer churn through data science. Neglecting to ignore a cost budget could lead to to over-expenditure on things like data procurement, complex algorithms, and infrastructure. Despite a successful churn prediction, <strong>the project can surpass budget limitations, yielding a negative return on investment (ROI)</strong>. Recognizing the cost budget beforehand could help in building a more scalable solution by means of procuring cost-effective data sources, simpler algorithms, and cloud-based solutions eventually making money for the company. This strategic approach can optimize expenses while delivering actionable insights, ensuring a positive ROI and project sustainability.</li><li><strong>Data Scale: </strong>Understanding the <strong>scale of incoming data is crucial to prevent algorithm failure in data science solutions</strong>. For instance, an e-commerce platform planning to implement a recommendation system must anticipate data volume to avoid system crashes if the solution get deployed in production. To address scalability, teams can adopt distributed computing frameworks like Apache Spark. These technologies enable efficient processing of large volumes of data and dynamic resource scaling based on demand. Proactively designing solutions to handle scalability constraints ensures smooth operation, optimal performance, and enhanced user experience, supporting business growth.</li><li><strong>Latency requirements:</strong> Imagine a banking institution aiming to enhance fraud detection in online transactions. Currently, their system, boasting a 95% accuracy rate, suffers from high latency, triggering fraud alerts 10 minutes after suspicious activity. Beyond a 5 minutes threshold, it becomes nearly impossible to recover funds lost to fraud, resulting in an an average of ₹10000 loss per undetected transaction. By adopting a faster, albeit slightly less accurate model with a 5 minutes latency, the bank can prevent irrecoverable losses by catching fraud in time, at the cost of an additional operational overhead of reviewing some extra false positives which could be acceptable. This underscores the importance of understanding latency; even <strong>a small reduction in detection time can translate into substantial savings</strong>, making speed a critical factor in fraud prevention strategies.</li><li><strong>Interpretability</strong>: Ensuring interpretability in data science projects is fundamental for stakeholder trust. For example, in healthcare, complex machine learning models may accurately predict patient outcomes but if it lacks interpretability, it would hinder adoption by healthcare professionals. Recognizing the importance of interpretability allows for the development of models that not only deliver accurate predictions but also provide explanations in a clear and understandable manner. By prioritizing interpretability, data scientists ensure actionable insights trusted by stakeholders, ultimately improving decision-making and outcomes in critical domains like healthcare.</li></ul><p>In summary, these outlined constraints represent common requirements often encountered in business scenarios, although <strong>they may vary depending on the specific nature of the problem</strong> at hand.</p><h4><strong>DEVELOPING THE DATA SCIENCE SOLUTION</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYbymHifAk7aQ1pHm_IdMQ.png" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:CRISP-DM_Process_Diagram.png">WikiMedia</a></figcaption></figure><p>Upon establishing the business objectives and constraints, comes the step most of the data scientists are well versed with developing the actual solution. Below is a quick generalized summary of the steps involved under the development section using <strong>the example of detecting fraudulent transactions in finance</strong></p><ul><li><strong>Data Preparation:</strong> Data preparation involves collecting and organizing raw data from various sources, ensuring it is cleaned, formatted, and structured for analysis or model training. This step lays the foundation for accurate and reliable insights to be derived from the data.</li></ul><blockquote>In fraud detection, this step could involve collecting past transaction records, such as amounts, times, and customer details, from banking databases.</blockquote><ul><li><strong>Feature Engineering:</strong> Feature engineering entails selecting, creating, or transforming features from raw data to enhance model performance and capture relevant patterns or relationships. This process optimizes the input variables to improve the predictive power of machine learning algorithms.</li></ul><blockquote>For fraud detection, features like transaction frequency per day, average transaction amount, and unusual geographical activity can be derived to identify suspicious patterns.</blockquote><ul><li><strong>Model Development:</strong> Model development involves selecting and training machine learning algorithms on the prepared data to create predictive models that can accurately classify or predict outcomes based on input features. This step aims to create models that generalize well to unseen data and effectively address the problem at hand.</li></ul><blockquote>Machine Learning models like anomaly detection algorithms or ensemble methods can be tried to identify fraudulent transactions.</blockquote><h4><strong>DEPLOYMENT AND MONITORING</strong></h4><ul><li><strong>Integration with Decision-Making Processes: </strong>Integrating model outputs into decision-making processes is essential for deriving actionable insights and optimizing business operations. For example, in retail, a company may deploy a demand forecasting model to predict future sales volumes. These predictions can then inform inventory management decisions, such as determining optimal stock levels and replenishment schedules. By seamlessly integrating model outputs into decision-making workflows, businesses can improve resource allocation, minimize stockouts, and enhance overall operational efficiency.</li><li><strong>Monitoring and Feedback Loop Implementation: </strong>Continuous monitoring of model performance and the implementation of a feedback loop are critical for ensuring the effectiveness and relevance of deployed models. For instance, in healthcare, a predictive model may be deployed to identify patients at high risk of readmission. By monitoring model predictions and comparing them with actual outcomes, healthcare providers can assess the model’s accuracy and identify areas for improvement. Moreover, collecting feedback from clinicians and patients allows for iterative refinements to the model, ensuring that it remains aligned with evolving healthcare needs and delivers actionable insights to support clinical decision-making.</li></ul><h4><strong>CONCLUSION</strong></h4><p>In conclusion, it’s imperative to <strong>approach data science challenges through the lens of business</strong>, ensuring the delivery of solutions that truly serve organizational needs. By prioritizing this perspective, businesses can harness data more efficiently, facilitating growth and fostering a culture of data-driven decision-making.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd1b8e65557" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/data-science-a-business-perspective-3bd1b8e65557">Data Science: A Business Perspective</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[Demystifying Auto Correct]]></title>
            <link>https://medium.com/swlh/demystifying-auto-correct-b5a31b20bc04?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a31b20bc04</guid>
            <category><![CDATA[autocorrect]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 12:17:45 GMT</pubDate>
            <atom:updated>2023-12-14T12:17:45.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Empowering Error Free Writing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*5uPCutYYXRfi_e4CDFU6LQ.jpeg" /><figcaption>Source: <a href="https://www.pickpik.com/millennial-problem-whiteboard-writing-quote-quotation-41927">PickPik</a></figcaption></figure><h3>INTRODUCTION</h3><p>Raise your hand if you have ever been victimized by the auto correct! We have all been there at least once, battling with our mobile phones and keyboards, <em>I need to buy some “milk”</em> auto corrected to <em>I need to buy some “silk”</em>, I am sure silk is definitely not something that is on a grocery list of anyone. Jokes apart, we can’t deny the fact that auto-correct has now become an integral part of our lives, acting as a digital guardian and saving from embarrassments from spelling errors and typos slipping through. In this blog I aim to give a small peak behind the working of the auto correct!</p><h3>HISTORY</h3><p>The origin of spell checkers can be traced back to 1980’s with the integration of auto correct’s into word processing software&#39;s, later after the rise of smartphones in the 2000’s it slowly made its way into our daily lives. From its early days of correcting misspelled words to today’s context based suggestions, auto correction has come a long way and has transformed digital communication significantly</p><h3>WORKING</h3><p>Here, we are going to understand a very simple version of auto correct suggested by Peter Norvig, you can find the link to the article <a href="https://norvig.com/spell-correct.html"><em>here</em></a>.</p><p>Let’s break down the whole process and try to understand it piece by piece.</p><h4>I. Data Collection</h4><p>We usually begin with collecting a large corpus of correctly spelt words that would be used to the language model, the larger and diverse the corpus, the better is the language model, for understanding purposes lets take a small dataset and explain the subsequent steps using the same example</p><pre>corpus = &quot;To be, or not to be, that is the question.&quot;</pre><h4>II. Word Counts and Probabilities</h4><p>Once we have the corpus, we perform a word frequency analysis on it, the idea here is to <em>estimate the likelihood of a word occurring in natural language</em>, this helps in choosing the most likely word from the candidates for correct words</p><pre>#   WORD COUNTS<br>Counter({&#39;to&#39;: 2, &#39;be&#39;: 2, &#39;or&#39;: 1, &#39;not&#39;: 1, &#39;that&#39;: 1, &#39;is&#39;: 1, &#39;the&#39;: 1, &#39;question&#39;: 1})</pre><pre># WORD PROBABILITIES<br>P(to) = 0.2857<br>P(be) = 0.2857<br>P(or) = 0.1429<br>P(not) = 0.1429<br>P(that) = 0.1429<br>P(is) = 0.1429<br>P(the) = 0.1429<br>P(question) = 0.1429</pre><h4>III. Generating Candidate Words</h4><p>Candidate Corrections as the as the name itself suggests helps us identify potential corrections for a misspelt word, this step prepares a pool of option for for the autocorrect system to consider.</p><p>These candidates are calculated by an approach called <strong>edit distance</strong>, in simple words the approach looks at the mistyped word and t<em>ries to find out all the ways you could have made that mistake</em>, for example if you have typed “helo”, the typo occurred because you missed one letter hence adding one letter to the misspelt word will get you the correct, you can perform these edits in multiple ways to reach the correct word</p><ul><li>adding or removing letter</li><li>swapping letters</li><li>replacing letters</li></ul><p>If you need to perform just one of these edits to reach the correct word, then we can say the <em>misspelt word is one edit distance apart</em>, similar if you are required to do two small changes to reach the correct word the we can say we are two edit distances apart, here we are find all the candidate corrections upto two edit distances below are a couple of examples</p><pre>Candidates for &#39;tooo&#39;: {&#39;too&#39;, &#39;to&#39;, &#39;topo&#39;, &#39;tow&#39;, &#39;troo&#39;, &#39;tood&#39;, &#39;toe&#39;, &#39;tool&#39;, &#39;moo&#39;, &#39;zoo&#39;, &#39;roo&#39;, &#39;thoo&#39;, &#39;tono&#39;, &#39;tool&#39;, &#39;roo&#39;, &#39;yoo&#39;}</pre><pre>Candidates for &#39;qusstion&#39;: {&#39;question&#39;, &#39;busstion&#39;, &#39;usstion&#39;, &#39;qusation&#39;, &#39;qusstioon&#39;, &#39;qusstioin&#39;, &#39;ausstion&#39;, &#39;qunstion&#39;, &#39;qusssion&#39;, &#39;qusstian&#39;, &#39;qqusstion&#39;, &#39;qmsstion&#39;, &#39;qusption&#39;, &#39;qusstino&#39;, &#39;qusition&#39;, &#39;qusstion&#39;, &#39;qusstionp&#39;}</pre><h4>IV. AUTO CORRECT FUNCTION</h4><p>This method simply selects the most probable candidate out of all the candidates for the correction, a very simple approach is used here to pick the best candidate</p><ul><li>If it is a known word i.e a word belongs to the vocabulary then return as it is, otherwise</li><li>If there is a non empty list of known words (belonging to the vocabulary) tht are one edit away then choose the one with maximum likelihood from the word probabilities calculated in Step II, otherwise</li><li>If there is a non empty list of known words that are two edits away then choose the one with maximum likelihood from the word probabilities calculated in Step II, else</li><li>return the base word as it is</li></ul><p>Below is the example of how the auto correct will work on the two misspelt words we took as an example in Step III</p><pre>Corrected word for &#39;qusstion&#39;: question</pre><pre>Corrected word for &#39;tooo&#39;: too</pre><h3>CONCLUSION</h3><p>This was just a basic version of the auto correct to give an intuition of how it works behind the scenes, so that next time when you send an email or write a blog for that matter, you will have an appreciation of this unsung hero among us, with the advancement of algorithms in machine learning and deep learning auto-correct itself has come a long way, with having the ability to understand the context to give better suggestions and help enhance the quality of digital communication</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a31b20bc04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/demystifying-auto-correct-b5a31b20bc04">Demystifying Auto Correct</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[Recommender System from Scratch]]></title>
            <link>https://medium.com/data-science/recommender-system-from-scratch-fa6b70fc3e7f?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6b70fc3e7f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 04:01:34 GMT</pubDate>
            <atom:updated>2021-09-15T17:30:37.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Intuitive Walkthrough</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*bzaXusHcDzHN3INzH0pzLQ.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><h3>Introduction</h3><p>When I started my Machine Learning Journey, there were a few concepts that fascinated me a lot one such thing was the recommender systems. This was one of those ML applications you could see in see extensively in your day-to-day life. While shopping on amazon, buying clothes at Myntra, watching movies on Netflix, we had recommendations everywhere, and of course, the<strong> </strong>famous<strong> </strong><a href="https://en.wikipedia.org/wiki/Netflix_Prize#:~:text=The%20Netflix%20Prize%20was%20an,numbers%20assigned%20for%20the%20contest."><strong>Netflix Prize Competiton</strong></a>, reading about the competition, the teams, and their 2-year hustle in cracking the competition is something that got me pretty excited about the recommender systems ( I would suggest you guys, watch <a href="https://www.youtube.com/watch?v=ImpV70uLxyw">this</a> documentary of the winning team). This blog will try to give an intuitive walkthrough of building a very basic recommender system from scratch.</p><h3>Recommender System</h3><p>First things first, what exactly is a recommender system, here is how Wikipedia defines a recommender system.</p><blockquote>A recommender system is an information filtering system that seeks to predict the “rating” or “preference” a user would give to an item [1]</blockquote><p>Well, that pretty much sums it up, based on these predictions the system suggests/recommends relevant items to a customer.</p><p>Broadly speaking there are three types of approaches used to create a recommender system</p><ul><li>Collaborative Filtering (We will focus on this in the blog)</li><li>Content-Based Filtering</li><li>Hybrid (A mixture of the above two)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*YjXaIb5DxifSO_OXA6gdMA.png" /><figcaption>Source: Image by Author</figcaption></figure><h3>COLLABORATIVE VS CONENT</h3><p>Collaborative Filtering uses <strong>past user-item interactions to come up with new recommendations, </strong>for example, if a person liked a movie m1 and 5 other people liked m1 and at the same time liked movie m2 then the movie m2 can be recommended to this user ( to be specific this is an example of user-user collaborative filtering), whereas content-based filtering requires <strong>additional information about the users (like age, gender, etc)and items/movies (genre, duration of the movie, etc)</strong> to generate the prediction, the benefits of the collaborative approach is that they require <strong>no additional information on a user/item</strong> rather they extract useful patterns from the past user-item interactions to create its own features without needing of any extra information</p><h3><strong>TYPES OF COLLABORATIVE FILTERING</strong></h3><p>There are two types are collaborative filtering approaches</p><ul><li>Memory Based</li><li>Model-Based ( We will be building a model-based recommender system in this blog)</li></ul><h4><strong>Memory Based</strong></h4><p>Memory-based collaborative filtering uses the <strong>user-item interaction matrix</strong> directly and fetches similar users/items.</p><ul><li><strong>user-user similarity:</strong> It first finds most similar users w.r.t to our given query user and then predicts the item preference based on the top similar customers rating, for example, if we want to predict how a customer C would be given a rating to a movie m1, then we will take a weighted sum of ratings given by users similar to that user, <strong>“Users who are similar to you also liked..”</strong></li><li><strong>item-item similarity:</strong> the methodology is similar to user-user similarity, the only difference is here the similarity computation is centered around item instead of user, lets say we want to predict movies to a user then we will first find the highest rated movie by the user and find similarity of this movie w.r.t all other movies and suggest top K movies <strong>“Users who liked this item also liked..”</strong></li></ul><p>For Similarity computation, we use <strong>Pearson correlation coefficients or Adjusted Cosine similarity</strong> (Centering ratings around zero to avoid assuming non rated items as negative items, 0 being not liking at all)</p><p>The main difference between a model-based and memory-based approach is that we are <strong>not learning any parameters/solving any optimization problem</strong> in the memory-based approach, the recommendations are given simply by computing similarity from the user-item matrix.</p><p>The major problem with the memory-based approach is that it is not scalable, as the user base increases the user-item matrix gets more sparse and computing similarity becomes difficult (especially computing user-user similarity).</p><h4>Model-Based</h4><p>Now we move on to a model-based approach, but before that let&#39;s discuss a bit about Matrix Factorization</p><p>Matrix Factorization breaks down a matrix into factors, in ML terms there exists a low dimensions latent space of features where we can represent both items and users, an approximation of the user-item matrix can be obtained by multiplying these user-item matrices.</p><p>As an example let’s assume we have broken down the user-movie matrix into 3 latent dimensions, this is not what it means exactly but to give you an intuition we can think of these 3 latent vectors as genres of movies like Action, Comedy, Romantic. Hence when we represent a user and a movie into these three dimensions we essentially try to break down the users, movies into these concepts/genres.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*27ECaAvN1FkjjxWXKZ3hVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*Nbf2_T5m_3HkgbEdsdUUMw.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Like in the above examples we have represented the users, movies in their latent dimension representation with each dimension representing a genre, this latent vector representation helps in <strong>computing an interaction b/w users and items and eventually help in recommending an item, </strong>for example, User A likes more of action movies, now if we compute cosine similarity of User A with all the three movies we would find Singham to have the highest similarity since it has a high value in the action genre hence suggesting this is most likely an action movie. <em>( Note: This is just an example to get an intuition of things, these latent vectors don’t have such direct interpretability )</em></p><h3><strong>CODE</strong></h3><p>Enough of the theory let&#39;s talk code! we will build a very simple model-based recommender system. To solve a machine learning problem (supervised) we always have an <strong>optimization problem, a function which we try to maximize/minimize</strong> to reduce the cost without overfitting the data and in the process learn our model parameters through techniques like gradient descent. So first let us define our optimization problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*l5nqrruvmehyBeu9BhCvcQ.gif" /><figcaption>Source: Image by Author</figcaption></figure><p>Where the predicted rating (r_hat) is computed as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*Zq0jvRdCa2Dg7DKrRvxvVA.gif" /><figcaption>Source: Image by Author</figcaption></figure><p>The optimization function might look a bit intimidating, but let&#39;s try to break it down piece by piece.</p><p>Just like any other cost function, this cost function can be broken down into two parts, the <strong>net cost associated</strong> which is calculated in the first part (actual-predicted) and the second term is the <strong>regularization term.</strong></p><p>Now let&#39;s understand these learnable parameters and the final prediction calculation clearly.</p><p>We can break down the predicted rating into four parts</p><ul><li><strong>Global Mean (mu):</strong> Global mean is the average rating of all the ratings in our training dataset, this term can be thought of as <strong>our baseline prediction rating</strong> and the model learns how much to tweak around this to get the right prediction.</li><li><strong>User Bias:</strong> User bias can be thought of as a <strong>term capturing a user’s behavior,</strong> for example, some users are too critical as compared to others hence they tend to give slightly lower ratings.</li><li><strong>Movie Bias:</strong> movie bias can be thought of as a term <strong>capturing a movie’s popularity</strong> for example there are some cult classic movies like Avatar, Shawshank Redemption which usually have high ratings hence these movies tend to have a higher rating for a recommendation.</li><li><strong>User-Movie Interaction:</strong> Finally we have a term that is calculated based on the interaction between a specific user and movie by computing similarity b/w user and movie latent vectors (explained in the above section)</li></ul><p>Well then that’s pretty much it, we have defined our optimization function and now we need to minimize our cost, in this case, we take RMSE as our performance metric.</p><h4><strong>DATASET</strong></h4><p>We have taken a very popular dataset called the <a href="https://grouplens.org/datasets/movielens/100k/">MovieLens 100k</a> [2], this dataset comprises 100k ratings ranging from 1 to 5, from 943 users on 1682 movies, and made a time-based train-test split of 80–20 i.e used first 80% ratings for training and remaining 20% for testing.</p><p>We have already defined our cost function, now we will be computing gradients and updating the model parameters to minimize this cost.</p><pre><strong>for</strong> each epoch:</pre><pre>   <strong>for</strong> each pair of (user, movie):</pre><pre>   b_i =  b_i - learning_rate * dL/db_i</pre><pre>   c_j =  c_j - learning_rate * dL/dc_j</pre><p>To keep things simple we are keeping <strong>user_bias</strong> and <strong>movie bias</strong> only as trainable parameters, we are computing User and Movie vectors using SVD ( you can think of SVD as a Matrix Factorization Technique).</p><p>Here <strong>b_i is an array of user biases</strong> where the dimension of this array is equal to total users (max user index) in our training set ( each user having a bias) while<strong> c_j refers to the total movies</strong> (max movie index) in our training set.</p><p>her <strong>dl/db_i refers to derivative w.r.t user bias and dl/dc_j refers to derivative w.r.t movie bias</strong>.</p><p>First let us set an upper bound of our RMSE, by calculating from RMSE from simply setting all the predicted ratings to the global average rating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*jGes5zmW84bxHL4vb8t61g.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Now we know the upper bound i.e anything around 3.5 is as good as predicting everything as a global average, we have defined our custom-fit method for our recommender method, below is the code</p><pre><strong>def fit_recommender</strong>(total_epochs,learning_rate,train_sparse_matrix,train_df,test_df,svd_components = 5):<br>    <em>&#39;&#39;&#39;learns parameters for the recommednder&#39;&#39;&#39;</em><br>    total_train_mse = []<br>    total_test_mse = []<br>    U1, Sigma, V1 = randomized_svd(train_sparse_matrix,      n_components=svd_components,n_iter=2, random_state=24)<br>    total_train_mse = []<br>    total_test_mse = []<br>    <strong>for</strong> epoch in range(total_epochs):<br>        <strong>for</strong> user,movie,rate in train_df[[&#39;user&#39;,&#39;movie&#39;,&#39;rating&#39;]].values:<br>            b_i[user] = b_i[user] - learning_rate *  <strong>derivative_db</strong>(user,movie,rate,U1,V1,mu,alpha) <br>            c_j[movie] = c_j[movie] - learning_rate *  <strong>derivative_dc</strong>(user,movie,rate,U1,V1,mu,alpha)<br>        train_error = get_prediction(train_df,b_i,c_j,mu)<br>        test_error = get_prediction(test_df,b_i,c_j,mu)<br>        total_train_mse.append(train_error)<br>        total_test_mse.append(test_error)<br>        <strong>print</strong>(&quot;After Epoch {}------Train rmse:{}  Test rmse:{}&quot;.format(epoch,train_error,test_error))<br>     <strong>print</strong>(&quot;=======================================================&quot;)</pre><p>Our fit method first calculates user, movie latent vector representation using truncatedSVD (ideally these users, movie representations also should be learned during the training process) and then later learns the user, movie biases during each epoch by performing gradient descent steps, below are the results once we run our custom-fit method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*NVbLYtzmHKbMnxcZD0dulA.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Both Train and Test RMSE’s are better than our baseline model, hence we can conclude model did learn some hidden patterns from the data in the form of these user and movie biases</p><p>Now you might feel this is a bit too much manual work, don’t we have something like scikit_learn where we just call the fit method and everything is done automatically, well you are in for a <strong>surprise, </strong>all of this and much more could be done by this <strong>amazing library called surprise used for building and testing recommender systems</strong>.</p><p>We need to build the dataset a bit differently for surprise to work</p><pre><strong>from</strong> surprise <strong>import</strong> Reader, Dataset<br>reader = Reader(rating_scale=(1,5))<br><em># create the traindata from the dataframe...<br></em>train_data = Dataset.load_from_df(train_df[[&#39;user&#39;, &#39;movie&#39;, &#39;rating&#39;]], reader)<br><em># build the trainset from traindata.., It is of dataset format from s</em>urprise library..<br>trainset = train_data.build_full_trainset() # we have to convert testset into list tuples of user,movie,rating<br>testset = list(zip(test_df.user.values, test_df.movie.values, test_df.rating.values))</pre><p>From the dataset class we call the load_from_df function which builds the trainset in the required format, now let&#39;s build our recommender system</p><pre><strong>def</strong> run_surpise(surprise_algo,trainset):<br>    svd.fit(trainset)<br>    train_preds = svd.test(trainset.build_testset())<br>    train_actual_ratings, train_pred_ratings = <strong>get_ratings</strong>(train_preds)<br>    train_rmse = <strong>get_errors</strong>(train_preds) <br>    test_preds = svd.test(testset)<br>    test_actual_ratings, test_pred_ratings = get_ratings(test_preds)<br>    test_rmse = get_errors(test_preds)    <br>    print(&quot;Train RMSE : {}  Test RMSE : {}&quot;.format(train_rmse,test_rmse))</pre><p>Now let’s run our surprise model and see the results ( the optimization function is the same as we had discussed above and now along with the user, movie bias <strong>we are learning the user, item latent vectors</strong> from the training set as well i.e the matrix factorization is performed using machine learning)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*-Msmwk3BUKFswyTHU7KgXw.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Not bad both train and test RMSE improved, this is just one algorithm, surprise has many other prediction algorithms to use please feel free to read out the official <a href="https://surprise.readthedocs.io/en/stable/getting_started.html">documentation</a> for surprise and try out others, it is just like scikit-learn, just plug and play.</p><h4>COLD START PROBLEM</h4><p>Before concluding, I would like to discuss one major drawback of the collaborative filtering approaches i.e cold-start problem. There would be some users/movies in the test-set that didn’t appear in the training set at all hence you can’t use collaborative approaches since you don’t have any past interactions for these movies/users. To handle the cold-start problem we can introduce additional user-level, item-level features like age of the user, the genre of movie, etc, basically merging content-based and collaborative approaches to get better predictions.</p><h3><strong>CONCLUSION</strong></h3><p>This blog was meant to give a high-level overview of the recommender systems to get you started. For those who are interested, I would recommend getting some hands-on experience by trying it out on the actual dataset. Below is the link to the Github repository for the code mentioned in the blog</p><p>Repository Link: <a href="https://github.com/ravi207/RecommenderSystem/blob/main/recommender_system.ipynb">https://github.com/ravi207/RecommenderSystem/blob/main/recommender_system.ipynb</a></p><p>Here are some good resources which I found really useful.</p><ul><li><a href="https://www.researchgate.net/publication/223460749_The_BigChaos_Solution_to_the_Netflix_Grand_Prize">https://www.researchgate.net/publication/223460749_The_BigChaos_Solution_to_the_Netflix_Grand_Prize</a></li><li><a href="https://www.youtube.com/watch?v=UyAfmAZU_WI">https://www.youtube.com/watch?v=UyAfmAZU_WI</a></li><li><a href="https://www.youtube.com/watch?v=h9gpufJFF-0">https://www.youtube.com/watch?v=h9gpufJFF-0</a></li></ul><h3><strong>REFERENCES</strong></h3><p>[1] <a href="https://en.wikipedia.org/wiki/Recommender_system">https://en.wikipedia.org/wiki/Recommender_system</a></p><p>[2] F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets: History and Context. ACM Transactions on Interactive Intelligent Systems (TiiS) 5, 4: 19:1–19:19. <a href="https://doi.org/10.1145/2827872">https://doi.org/10.1145/2827872</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6b70fc3e7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/recommender-system-from-scratch-fa6b70fc3e7f">Recommender System from Scratch</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[Model Deployment using Flask]]></title>
            <link>https://medium.com/data-science/model-deployment-using-flask-c5dcbb6499c9?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5dcbb6499c9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Mon, 17 May 2021 09:25:39 GMT</pubDate>
            <atom:updated>2021-08-31T05:05:55.927Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making consumable models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*W2s9FMfOSadzjMV25-v4bQ.png" /><figcaption>Source: <a href="https://thenounproject.com/term/launch-project/2041279/">Noun Project</a></figcaption></figure><h3>INTRODUCTION</h3><blockquote>No matter how awesome model you have built, it would not give any value sitting in a jupyter notebook.</blockquote><p>Often we focus a lot in the EDA, Model Development part, however there is one more major aspect that we tend to miss out i.e creating an end to end application or deploying the model, after all that hard work and efforts that you had put in developing your model it is equally important that you give it in a usable form that can be consumed by the end user directly. Moreover building an application around the code you have developed helps you make you make your work more presentable and helps you showcase your work better.</p><h3>FLASK</h3><p>Flask is a a <strong>web application framework written in python</strong>, in simple terms it helps end users interact with your python code (in this case our ML models) directly from their web browser without needing any libraries,code files, etc.</p><p>Flask enables you to create web applications very easily, hence enabling you to focus your energy more on other important parts of a ML lifecycle like EDA, feature engineering, etc. Here in this blog I will give you a walkthrough on how to build a simple web application out of your ML Model and deploying it eventually.</p><h3>DIRECTORY STRUCTURE</h3><p>First let’s have a look at our directory structure, this will give us a broader picture of the overall project and it is also useful to know it when you working with flask, I have saved the project under a main directory called <strong>ML_Model_deployment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*LZSBiEfCJSccHEhVAVjiFg.png" /><figcaption>Source: Image by Author</figcaption></figure><ul><li><strong>templates</strong> :- This folder contains the html files <em>(index.html, predict.html)</em> that would be used by our main file <em>(app.py)</em> to generate the front end of our application</li><li><strong>app.py</strong> :- This is the main application file, where all our code resides and it binds everything together.</li><li><strong>requirements.txt</strong> <strong>:-</strong> This file contains all the dependencies/libraries that would be used in the project <em>(whenever a virtual environment is created it can use this requirements file directly to download all the dependencies you need not to install all the libraries manually, you just need to put all of them in this file)</em></li><li><strong>model.pkl</strong> <strong>:-</strong> This is our classification model, that we would be using, in this cases it is a Logistic Regression Model, which I had trained already.</li><li><strong>vectorizer.pkl :-</strong> This is vectorizer file that is used to convert text into a vector for the model to process, in this case we have used a tf-idf vectorizer</li><li><strong>Procfile :-</strong> This is a special file that would be required when we would be deploying the application in a public server (heroku)</li></ul><h3>UNDERSTANDING THE CODE</h3><p>I have taken the a problem called <strong>Quora Insincere Questions Classification</strong> hosted as a competition on Kaggle, basically it is a classification problem where quora is trying identify insincere questions i.e those founded upon false premises, or that intend to make a statement rather than look for helpful answers, you can read more about the problem statement in <a href="http://those founded upon false premises, or that intend to make a statement rather than look for helpful answers">here</a>.</p><p>Now that we are through with all the introduction part, let’s talk code!</p><pre><strong>from</strong> flask <strong>import</strong> Flask<br>app = Flask(__name__)</pre><p>Just like any other python class object, at the end this app is nothing but just an object of class Flask which would do all the heavy lifting for us, like handling the incoming requests from the browser (in our case the question that user enters) and providing with appropriate responses (in this case our model prediction) in some nice form using html,css. We will gradually see all these things and how this app object fits in solving all of it.</p><p>Next piece might look a bit intimidating, but don’t worry we will try to understand it piece by piece.</p><pre><a href="http://twitter.com/app"><strong>@app</strong></a><strong>.route(&#39;/&#39;)<br></strong>def index():<br>    return flask.render_template(&#39;index.html&#39;)</pre><pre><a href="http://twitter.com/app"><strong>@app</strong></a><strong>.route(&#39;/predict&#39;, methods=[&#39;POST&#39;])<br>def</strong> predict():<br>    to_predict_list = request.form.to_dict()<br>    review_text = pre_processing(to_predict_list[&#39;review_text&#39;])<br>    prob = clf.predict_proba(count_vect.transform([review_text]))<br>    if prob[0][0]&gt;=0.5:<br>        prediction = &quot;Positive&quot;<br>   else:<br>        prediction = &quot;Negative&quot;</pre><pre><strong>return</strong> flask.render_template(&#39;predict.html&#39;, prediction = prediction, prob =np.round(prob[0][0],3)*100)</pre><p>The first line <strong>@app.route (‘/index’)</strong> is a decorator, in simple words it just maps the the method defined below it to the URL mentioned inside the decorator, i.e whenever user visits that URL <strong>‘/’ </strong><em>(the complete address would have an ip address and a port number as well, something like http://127.0.0.1:5000/)</em>, <strong>index()</strong> method would be called automatically, and the index() method returns our main HTML page called <strong>index.html</strong> <em>(in our case index.html provides a text box to the user where he could enter his question)</em></p><p>The <strong>flask.render_template()</strong> looks for the this <strong>index.html</strong> file in the <strong>templates folder</strong> that we created in our main directory and dynamically generates/renders a HTML page for the end user, I will explain the dynamic part in a bit</p><p><em>(Note: Since predict word is used in multiple contexts, so to avoid any confusion I will refer predict() as the predict method defined in our code, predict.html as the predict template stored in our template folder and /predict as the predict URL )</em></p><p>Now we have another decorator <strong>@app.route (‘/predict’)</strong>, this one maps the<strong> predict()</strong> method with the <strong>/predict</strong><em> </em>URL<em> </em>, this predict() method as the name suggests takes the input given by the user, does all the preprocessing, generates the final feature vector, runs the model on it and gets the final prediction. Now let us focus on the rendering dynamic HTML page part, sometimes we need to to put information dynamically in the HTML page, like in this case itself our <strong>predict.html</strong> page would need the prediction value to render the page properly , which is available only when the user enters the text and hits the submit button in our <strong>index.html</strong> page, this is where the <strong>render_template</strong> comes into picture, in the predict.html page we have already created placeholders (will talk about these placeholders in a while) for these variable values, <strong>this render_template takes the predict.html in the templates folder and the predicted values eventually puts them together to generate/render the final HTML page, in this case HTML page containing the prediction, </strong>neat right?</p><p>Now let’s have a quick look at the <strong>predict()</strong> method in our main code, first line inside the method i.e <strong>to_predict_list = request.form.to_dict(), </strong>it takes the user entered text, when clicked on the submit button in our form <strong>a json is returned containing key value pairs having responses</strong>, when the submit button is clicked this <strong>/predcit URL is called and responses are sent to the page corresponding to this URL as a json </strong>and we had seen it earlier as well, once this /predict URL is called, the associated predict() method is invoked automatically which takes this json and the output template (predict.html) and puts it together to generate our final output. (We have an output section at the end where we will actually look at the results of all the things discussed here)</p><p>Now before moving further on the code, let us have a look at our <strong>index.html</strong>, which is responsible for taking input text from the user, and eventually displaying the final output by calling the <strong>/predict</strong> URL</p><pre>&lt;form action=&quot;/predict&quot; method=&quot;POST&quot; target=&quot;_blank&quot;&gt;<br> &lt;textarea name=&quot;review_text&quot; placeholder=&quot;Enter your question here...&quot; rows=&quot;10&quot; cols=&quot;15&quot;&gt;&lt;/textarea&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>  &lt;/form&gt;</pre><p>Here is the small piece of the index.html where the <strong>form is created</strong>, we can see a field called <strong>action</strong> this means, that the form data is sent to the page specified in the <strong>action attribute </strong>and the <strong>method attribute</strong> tells us how this form data is shared, here we have used <strong>POST method</strong> which simply means that this form data is shared as a json (in the form of key-value pairs), while we are at it let us also look at our second template file i.e <strong>predict.html </strong>template as well, basically it takes the prediction output and displays the result according to the output values , hence we need two major things in our predict.html template here to achieve this</p><ul><li>A <strong>variable/placeholder</strong> for the prediction output</li><li>A<strong> basic if/else logic</strong> to display results based on the prediction values</li></ul><p>Below is a small snippet from the predict.html page which prints a message and an image based on the prediction results</p><pre><strong>{% if prediction == &quot;Negative&quot; %}</strong><br>   <br>      &lt;h1&gt; THIS IS NOT A GENUINE QUESTION   &lt;/h1&gt;<br>  &lt;img src=&quot;<a href="https://i.pinimg.com/564x/b0/41/75/b04175fd1ffbefdc02d90136c262a6e3.jpg">https://i.pinimg.com/564x/b0/41/75/b04175fd1ffbefdc02d90136c262a6e3.jpg</a>&quot; width=250&gt;<br>     &lt;progress value= <strong>{{prob}}</strong> max=&quot;100&quot;&gt;</pre><p>writing code/vairables inside the html page is extremely simple, flask uses a <strong>web templating engine called Jinja2</strong> which helps you embed you code/variables inside html</p><ul><li><strong>{{}}</strong> is used to add variables/placeholders (this prob variable is passed already by the render_template inside predict() method)</li><li><strong>{ % %}</strong> to write statements like if-else conditions/for loops,etc</li></ul><p>Now, coming back to the original code in the predict() method, once we get the input text from the form response we pass this text to our preprocessing function, where we perform some basic NLP preprocessing like converting to lowercase, some tokenizations, word lemmatizations. Below is the preprocessing function definition</p><pre><strong>def</strong> pre_processing(text):<br>    lemmatizer = WordNetLemmatizer()<br>    text = text.lower()<br>    text = re.sub(&#39;[0-9]+&#39;,&#39;num&#39;,text)<br>    word_list = nltk.word_tokenize(text)<br>    word_list =  [lemmatizer.lemmatize(item) for item in word_list]<br>    return &#39; &#39;.join(word_list)</pre><p>After the pre-processing we call in our <strong>vectorizer and model</strong>, which we have already defined and saved during training phase, our count_vectorizer converts the text to the numeric vector and the model gives the prediction probability from it, later these values are given into render_template to generate the overall html page containing the output.</p><h3>DEPLOYMENT and OUTPUT</h3><p>Now let us have a look at the final result, how everything looks like once we deploy it, first I will deploy it in my local machine and later we will deploy it in a public server. Deployment is very simple you simply set up your python environment and run the app.py application, since I already have Anaconda installed in my computer I will run the app.py file from there, otherwise you can create your separate virtual environment install all the dependencies their and run it from there, you don’t need the entire anaconda package to run it, you just need python and the libraries that were used in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*Bvcmb03mJsOzbIFttrV5Sw.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Once you have opened you anaconda prompt, just go to the main folder (ML_Model_deployement in this case) where everything is residing and simply run the maint python code file (app.py), just look at the last line it says running on <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a> this is where our web application is running, you can copy this URL and paste it in your web browser and see the web application, here 127.0.0.1 is an <strong>ip address</strong> for locahost i.e the your own machine (just like we have a house address, ip address is a unique address to identify your machine on the internet or a local netwrok )and 5000 is the port number, this is where your web application resides in the server (think of it as a doorway to access your application). Now let us copy this URL on our browser and see how the homepage looks like (kindly pardon my frontend skills, I have a very limited experience there)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdQtUAf4ZzjXJKsl4mN1Ng.png" /><figcaption>Source: Image by Author</figcaption></figure><p>Now let us type out some questions from both classes and see how our prediction page looks like, first lets look at a genuine question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToaVixXfc81NosRDZhgdUA.gif" /><figcaption>Source: Video by Author</figcaption></figure><p>Now we will type an insincere/non genuine question and see how the results look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKiJNFybrYaTn4jBOUL77Q.gif" /><figcaption>Source: Video by Author</figcaption></figure><p>Just like we deployed in our local machine, we can deploy it in a public web server and make our application accessible for everyone on the web. Here I have used <strong>heroku</strong> to deploy my application.</p><p>Heroku is <strong>PAAS (Platform as a service app)</strong> which enables developers to deploy their applications on the web and it does offer a free plan!, deploying in heroku is very simple, you can directly link you github repository to heroku(I will share both the link of the github repo and the web application at the end). You just need to add two special files <strong>requirements.txt </strong>and <strong>Procfile(without any extensions)</strong>, we have already discussed about the requirements file while discussing about the directory structure now let us talk a bit more about this Procfile. Basically Procfile tells heroku about a set of processes/commands that needs to be run beforehand, the Procfile looks something like this</p><pre>web: gunicorn app:app</pre><p>The <strong>web</strong> commands tells heroku to start a web server using gunicorn (a web server that helps you run python applications) and the <strong>first app</strong> refers to our main <strong>app.py</strong> file and the second one refers to the <strong>flask instance app</strong>, it can very well have different names as well, if you have any doubts regarding deployment you can refer to this amazing <a href="https://www.youtube.com/watch?v=mrExsjcvF4o">video</a> tutorial, it contains a complete step by step tutorial for deployment in heroku.</p><h3>CONCLUSION</h3><p>If you found this tutorial helpful then please do share it with your friends, below are the links to the github repository and the web application deployed in heroku. To get a feel of it, I would strongly recommend to try it once on your own, if you have already worked on some ML projects in the past then try to deploy those models instead, in this way you will get a much better understanding.</p><p><strong>Github Repository :-</strong> <a href="https://github.com/ravi207/Model_Deployment">https://github.com/ravi207/Model_Deployment</a></p><p><strong>Web Application</strong> :- h<a href="https://question-classification.herokuapp.com/">ttps://question-classification.herokuapp.com/</a></p><p><em>(Note: I have a trained a very basic Logistic Regression model using a tf-idf vectorizer on a small subset of the overall dataset, so model predictions won’t be that great, right now it is able to identify a specific type insincere questions that are having some specific hate words that it learnt from the dataset during training)</em></p><p>In case you have any suggestions or doubts then please feel free to me at</p><p>LinkedIn : <a href="https://www.linkedin.com/in/ravindra-sharma-832a04156">https://www.linkedin.com/in/ravindra-sharma-832a04156</a></p><p>HAPPY LEARNING!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5dcbb6499c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/model-deployment-using-flask-c5dcbb6499c9">Model Deployment using Flask</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[KERAS : Under the Hood]]></title>
            <link>https://medium.com/data-science/keras-under-the-hood-afb2cb86b4fa?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb2cb86b4fa</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 14:05:37 GMT</pubDate>
            <atom:updated>2021-04-05T15:39:21.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>KERAS: Under The Hood</h3><h4>Understanding model architectures in keras</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aD--c6ImmGySfWf1sNR6hg.jpeg" /><figcaption>Source: <a href="https://pixabay.com/illustrations/matrix-full-program-data-code-3145364/">Pixabay</a></figcaption></figure><h3>INTRODUCTION</h3><p>Getting started with deep learning has become very simple and convenient, all thanks to wonderful duo of keras and tensorflow. You just need to do some imports, define some layers and bingo, you have your deep learning architecture ready to be trained and eventually give some amazing results. Keras has made such an amazing abstraction that even a total stranger to the topic as well can start training their own deep learning models. However if you are calling yourself a Data Scientist/Machine Learning Engineer then having some basic understanding of what’s happening under the hood is a must, I am not saying you need to exactly know the hundreds of lines of code behind it but at least have a some understanding what those lines of code are doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*toBL6XleRkwABSwTAFaY_g.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><h3>GETTING STARTED</h3><p>Without wasting anytime lets dive into some of the most commonly used keras components and try to understand them piece by piece, this will involve a basic understanding of Object Oriented Programming but don’t worry I will try to keep it as simple as possible. I will take a very simple deep learning architecture and and then try to explain the working line by line, in order to explain things better I have created create a custom dense layer that I would be using in my architecture.</p><pre><strong>class</strong> <em>MyDenseLayer</em>(tf.keras.layers.Layer):<br>    <br>    <strong>def</strong> <em>__init__</em>(self, nodes):<br>        super(MyDenseLayer, self).__init__()<br>        self.num_outputs = nodes<br>    <br>    <strong>def</strong> <em>build</em>(self, input_shape):<br>        print(&quot;=&quot;*20)<br>        print(&#39;we are here in build&#39;)<br>        self.kernel = self.add_weight(&quot;kernel&quot;,shape=      [int(input_shape[-1]),self.num_outputs],dtype=tf.float32)        <br>    <br>    <strong>def</strong> <em>call</em>(self, input):<br>        print(&#39;=&#39;*20)<br>        print(&#39;we are here in call&#39;)<br>        <strong>return</strong> tf.matmul(input, self.kernel)</pre><p>You might be wondering what are these build/call methods inside, I will dig deeper into their details in a while and below is a very simple model architecture using <em>keras Functional API</em>.</p><pre>input_layer = Input(shape = (5,))<br>dense_layer  = MyDenseLayer(nodes=10)<br>dense_layer_op = dense_layer_one(input_layer)<br>model = Model(inputs = input_layer,outputs = dense_layer_op)</pre><p>Now let us look at the architecture and try to understand it line by line. First line is pretty straightforward, we are creating an object of a class called Input which basically creates a symbolic <strong>tensor/placeholder</strong> <em>(it means we don’t need actual input data here, instead a block of memory is reserved for data to flow in the network later)</em> this tensor tells the network what will be the size of the input that would be given to the model and this is generally the entry point into the network, in the shape argument we specify the dimensions of input vector. ( (5,) means input is 1x5 vector and the batch size is not decided yet i.e model can take any batch size that would be defined later during model fitting)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*v9SVj6faTlHAdWMKY0hU7Q.png" /><figcaption>Pictorial Representation of placeholder (Image by Author)</figcaption></figure><p>Second and third lines are where the actual thing begins, here we define the very first layer of our neural network architecture. Second line creates an object of our custom layer class, this line basically defines the number of nodes in our custom layer.</p><p>Third line is where our actual layer is built, weights of the layer are created and initialized here, you might be having some questions like why the weights are not initialized during layer object creation itself?, moreover how is this layer object being used as some python method?, if so then what is this method doing?. Let me answer them one by one, at the time of object creation we might not know the size of the input beforehand (if we were to create weights during object creation then we would need to pass the size explicitly every time as an argument to the class) and without the size of the input we cannot create this weight matrix. Hence we want to create these weights lazily only when the size of inputs is known, which is what happens in our third line, here once we get the information of the input shape we build our layer fully, to prove my point I have fetched the layer weights after creating the layer object and after passing the input shape to this layer object respectively, you can clearly see weights are initialized only when the input shape to the layer is known, elegant right?.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*nrjccgsOe9ZvEt7OuAeBvQ.png" /><figcaption>Calling weight matrix before and after passing input shape (Image by Author)</figcaption></figure><p>now comes the second question how is this object being treated as a python method and if it is a method then what is it doing?, before that let us talk first a bit about these methods that we defined in our custom class.</p><blockquote><strong>__init__ ()</strong> : This is one is pretty straightforward, for those of you who have worked with other programming languages like JAVA this __init__ is equivalent to a constructor this is used to initialize a class object.</blockquote><blockquote><strong>build ()</strong> : As the name suggests, this method is used to actually build the layer i.e it creates the layer weights, this is called once we get the shape of the input that would be fed to the model and it creates the weights accordingly</blockquote><blockquote><strong>call ()</strong> : This is where logic of the layer lives, i.e it takes the input that is being fed to the layer processes it and spits out the output of that layer, which might be used by other layers</blockquote><p>We discussed about what these methods do, but we didn’t talk about one very important thing, how and when are these methods invoked, <em>__init__</em> is pretty straightforward it gets invoked at the time of object creation, as for these <em>build and call methods</em> these are invoked at the time when we are using our layer object as a method, it might get a bit confusing but please be patient, lets break it down, as of now we know the <strong>what part</strong> i.e on being treated as a method what is this object actually doing, now comes the<strong> how part</strong>, how is this object being treated as a method, how are the call and build methods called without any explicit function calls.</p><p>well this is a special kind of object — <strong>the callable object</strong>, this object can be treated as an function with a bit of magic. That is exactly what is required to make this magic happen, a <strong>magic method</strong>, python has these special types of methods whose invocation does not require any explicit function call. They are called internally ( called by some operator overloading or built-in functions), we may not realize it but we have been using some of these magic methods quite extensively already , here is a quick example, in python we know everything is an object when we do something like <em>a = 5 </em>then actually <em>a</em> is an object of a class str, when we do <strong>print(</strong><em>a</em><strong>)</strong> how is the print method able to generate this output here is where another magic function comes into play called <em>__str__</em>, this method returns the output of an object in string form and it is invoked automatically when we put that object inside print method, again here is a small code piece to make you more comfortable around the above statement.</p><pre><strong>class</strong> PrintTest():<br>    <strong>def</strong> __init__(self,obj):<br>        self.obj = obj<br>    <strong>def</strong> __str__(self):<br>        <strong>return</strong> &quot;__str__ method is invoked when print object is put inside print/str method&quot;<br>str_obj = PrintTest(&#39;Hello&#39;)</pre><p>And here are the outputs when we put an object of the PrintTest class inside built in methods like print.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmZ4JEVf1VOsZKwqGaahtQ.png" /><figcaption>Checking __str__ method invocation (Image by Author)</figcaption></figure><p><em>( </em><strong><em>Note</em></strong><em> </em><strong><em>:</em></strong><em> In python there is class called Object which is by default a parent class to every class created in python this __str__ is already defined there, here in our example we had simply overridden the __str__ method. )</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3OVmLk4lci7Dwxt3vab4w.png" /><figcaption>Checking parent class of the custom class (Image by Author)</figcaption></figure><p>Now coming back to our original discussion, there is another magic method called <em>__call__</em> that helps your class object work as regular method, it is invoked automatically once we put brackets round brackets () after of the object name, in simple words <strong>obj()</strong> is equivalent to <strong>obj.__call__()</strong> .</p><p>So this why when we create an object of our original layer, and then do a function call using the same object it works, keen observers would have noticed one thing, that in our custom layer class we did not explicitly define any <em>__call__</em> method, we do have a call method but it is a regular method, it ain’t no magic method, well to answer this I would like to touch upon a concept of OOPs called Inheritance, you must have noticed our custom layer class has inherited a base class called <strong>Layer</strong> from Keras , you might be aware of basic concept of inheritance, once a class inherits another class (parent class) it gets access to all the functionality (methods) of that parent class so this magic method <em>__call__ </em>is written in the Layer class and when we inherit it our custom class gets access to this<em> __call__</em> magic method. These <em>build and call methods</em> are also not some random methods, they also have a significance in layer building. These methods are actually already defined in the Base Layer Class, and they have these special roles to play that we discussed above already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*kcm_HDxmytQB1LNoHv0cFA.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><p>Both of these methods are called via <em>__call__</em> method, so to summarize the whole flow once we pass a tensor/placeholder through layer callable object then <em>__call__</em> method is invoked which in turn calls first the build method to instantiate the layer and later call method to run the logic of the layer. To give the proof of my statement I had added print statements inside the <em>call and build methods</em>, let’s see the output once the input tensor/placeholder is passed to the callable layer object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaQVkYOqHTAwAPP70TW43Q.png" /><figcaption>Checking at build and call mehtods invocation (Image by Author)</figcaption></figure><p>One thing you would have noticed by now that while defining architectures we don’t need the actual data, we just need the shape of tensors that would be needed by the layer, and a placeholder is created for that tensor, the actual data is passed during <em>model.fit()</em> and the data forward propagates through the architecture and later error/loss is calculated which then back propagates hence updating the weights in the process and training the model.</p><h3><strong>CONCLUSION</strong></h3><p>Though these things might look small, but knowing them helps specially when we move into more complex deep learning architectures like LSTM’s, encoder-decoders, etc and having a bit of understanding of these basic concepts helps us later to get a better hang of these complex architectures and eventually modify and create our own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb2cb86b4fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/keras-under-the-hood-afb2cb86b4fa">KERAS : Under the Hood</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[AUC-ROC: Simplified]]></title>
            <link>https://medium.com/data-science/auc-roc-simplified-5914185d24e?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5914185d24e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[classification-metrics]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 08:35:57 GMT</pubDate>
            <atom:updated>2020-11-17T13:49:04.267Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Intuitive Understanding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hxh2lPpuQvUy0hmrUJioDA.png" /><figcaption>Source: <a href="https://pxhere.com/">https://pxhere.com</a></figcaption></figure><h3>INTRODUCTION</h3><p>One important aspect in Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into picture , they give us a sense on how good is your model. If you are familiar with some basics of Machine Learning then you must have across some of these metrics like accuracy, precision, recall, auc-roc, etc.</p><p>Let’s say you are working on a binary classification problem and come up with a model with 95% accuracy, now I ask you what does that actually mean and you would be quick enough to say out of 100 predictions your model makes, 95 of them are correct. Well lets take it up a notch, now the underlying metric is recall and I ask the same question, you might take a moment here but eventually you would come up with an explanation like out of 100 relevant data points (positive class in general) your model is able identify 80 of them. So far so good, now let us assume you evaluated your model using AUC-ROC as a metric and got a value of 0.75 and again I ask the same question to you what does 0.75 or 75% signify, now you might need to give it a thought, some of you might say there is a 75% chance that model identifies a data point correctly but by now you would have already realized that’s not it. Let us try to get an intuitive understanding of one the most popular performance metric for classification problems.</p><h3>HISTORY</h3><p>If you have participated in any online machine learning competition/hackathon then you must have came across Area Under Curve -Receiver Operator Characteristic a.k.a AUC-ROC, many of them have it as their evaluation criteria for their classification problems. Let’s admit it when you had first heard about it, this thought must have cross your mind once, what’s with the long and fancy name? Well the origin of ROC curve goes way back in World War II, it was originally used for analysis of radar signals. The United States Army tried to measure the ability of their radar receiver to correctly identify the Japanese Aircrafts against signal noises [1] . Now that we have a bit origin story lets get down to business</p><h3>GEOMETRIC INTERPRETATION</h3><p>This is the most common definition that you would have encountered when you would google AUC-ROC. Basically ROC curve is a graph that shows the <strong>performance of a classification model at all possible thresholds </strong>( threshold is a particular value beyond which you say a point belongs to particular class). The curve is plotted between two parameters</p><ul><li>True Positive Rate (TPR)</li><li>False Positive Rate (FPR)</li></ul><p>Before understanding TPR and FPR let us quickly look at the confusion matrix first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*lK17g_LKDGcU7UjKlZn1tQ.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><ul><li><strong>True Positive </strong>: Actual Positive and Predicted as Positive</li><li><strong>True Negative </strong>: Actual Negative and Predicted as Negative</li><li><strong>False Positive (Type I Error) </strong>: Actual Negative but predicted as Positive</li><li><strong>False Negative (Type II Error)</strong> : Actual Positive but predicted as Negative</li></ul><p>In simple terms you can call False Positive as <strong>false alarm</strong> and False Negative as a <strong>miss<em>.</em></strong> Now let us look at what TPR and FPR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*b6UGjxJ9bwlOdDZ91iYgWw.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*cVW_c9blXFK7MLsl2dUEUg.png" /><figcaption>Image by Author</figcaption></figure><p>Basically TPR/Recall/Sensitivity is <strong>ratio of positive examples</strong> that are correctly identified and FPR is <strong>ratio of negative examples </strong>that are incorrectly classified and as said earlier ROC is nothing but the plot between TPR and FPR across all possible thresholds and AUC is the entire area beneath this ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*b7VjjLuBouZWfBgFb81F-w.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/3.0/deed.en">Creative Commons</a></figcaption></figure><h3>PROBABILISITC INTERPRETION</h3><p>We looked at the geometric interpretation, but I guess it is still not enough in developing the intuition behind what does 0.75 AUC actually means, now let us have a look at AUC-ROC with a probabilistic point of view.</p><p>Let me first talk about what AUC does and later we will build our understanding on top of this</p><blockquote>AUC measures how well a model is able to distinguish between classes</blockquote><p>An AUC of 0.75 would actually mean that lets say we take two data points belonging to separate classes then there is 75% chance model would be able to segregate them or <strong>rank order them correctly</strong> i.e positive point has a higher prediction probability than the negative class. (assuming a higher prediction probability means the point would ideally belong to the positive class)</p><p>Here is a small example to make things more clear.</p><pre>╔═══════╦═══════╦═════════════╗<br>║ Index ║ Class ║ Probability ║<br>╠═══════╬═══════╬═════════════╣<br>║ P1    ║     1 ║ 0.95        ║<br>║ P2    ║     1 ║ 0.90        ║<br>║ P3    ║     0 ║ 0.85        ║<br>║ P4    ║     0 ║ 0.81        ║<br>║ P5    ║     1 ║ 0.78        ║<br>║ P6    ║     0 ║ 0.70        ║<br>╚═══════╩═══════╩═════════════╝</pre><p>Here we have 6 points where P1, P2, P5 belong to class 1 and P3, P4, P6 belong to class 0 and the corresponding predicted probabilities in the Probability column, as we said if we take two points belonging to separate classes then what is probability that model rank orders them correctly</p><p>We will take all possible pairs such that one point belongs to class 1 and other belongs to class 0, we will have total 9 such pairs below are all of these 9 possible pairs</p><pre>╔═══════╦═════════╦═══════════╗<br>║ Index ║  Pair   ║ IsCorrect ║<br>╠═══════╬═════════╬═══════════╣<br>║     1 ║ (P1,P3) ║ Yes       ║<br>║     2 ║ (P1,P4) ║ Yes       ║<br>║     3 ║ (P1,P6) ║ Yes       ║<br>║     4 ║ (P2,P3) ║ Yes       ║<br>║     5 ║ (P2,P4) ║ Yes       ║<br>║     6 ║ (P2,P6) ║ Yes       ║<br>║     7 ║ (P3,P5) ║ No        ║<br>║     8 ║ (P4,P5) ║ No        ║<br>║     9 ║ (P5,P6) ║ Yes       ║<br>╚═══════╩═════════╩═══════════╝</pre><p>Here colum <strong>isCorrect</strong> tells if the mentioned pair is correct rank ordered based on the predicted probability i.e class 1 point has a higher probability than class 0 point, in 7 out of these 9 possible pairs the class 1 is ranked higher than class 0 or we can say that there is a 77% chance that if you pick a pair of points belonging to separate classes the model would be able to distinguish them correctly. Vola! now I think you might have a bit intuition behind this AUC number, just to clear up any further doubts let us validate it using scikit learn’s AUC-ROC implementation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*JWNXQBolv3ApUF1bWF8G6A.png" /><figcaption>Sample Code for AUC Validation(Image by Author)</figcaption></figure><h3>WHEN TO USE</h3><p>Having said that there certain places where AUC-ROC might not be ideal.</p><ul><li>AUC-ROC does not work well under severe imbalance in dataset, to give some intuition for this lets us look back at the geometric interpretation here. Basically ROC is the plot between TPR and FPR ( assuming the minority class is the positive class), now let us have a close look at the FPR formula again</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*cVW_c9blXFK7MLsl2dUEUg.png" /><figcaption>Image by Author</figcaption></figure><p>Denominator of FPR has a True Negatives as one factor, since Negative Class is in majority the denominator of FPR is dominated by True Negatives which makes FPR less sensitive to any changes in minority class predictions (any change in the False Positives number is not reflected appropriately in FPR due to a high denominator). To overcome this, Precision-Recall Curves are used instead of Receiver Operator Characteristic curve and then the AUC is calculated, try to answer this yourself how does Precision Recall curve handle this problem <em>(Hint: compare PR curve and ROC inputs, Recall and TPR are same, technically only FPR is replaced with Precision, just compare the denominators for both and try to assess how imbalance problem is solved in PR curve)</em></p><ul><li>AUC-ROC tries to measure if the rank ordering of classifications is correct it does not take into account actual predicted probabilities, let me try to make this point clear with a small code snippet</li></ul><pre>import pandas as pd</pre><pre>y_pred_1 = [0.99,0.98,0.97,0.96,0.91,0.90,0.89,0.88]<br>y_pred_2 = [0.99,0.95,0.90,0.85,0.20,0.15,0.10,0.05]<br>y_act = [1,1,1,1,0,0,0,0]<br>test_df = pd.DataFrame (zip(y_act,y_pred_1,y_pred_2),columns=[&#39;Class&#39;,&#39;Model_1&#39;,&#39;Model_2&#39;])<br>test_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*68CuLayPAqABWHt0H8IVNg.png" /><figcaption>Two Sample Models (Image By author)</figcaption></figure><p>We have two models Model_1 and Model_2 as mentioned above, both do a perfect job in segregating the two classes, but if I ask you to choose one among them which one would it be, hold on to your answer for a bit let me first plot these model probabilities.</p><pre>import matplotlib.pyplot as plt</pre><pre>cols = [&#39;Model_1&#39;,&#39;Model_2&#39;]<br>fig,axs = plt.subplots(1,2,figsize=(15,5))<br>for index,col in enumerate(cols): <br>    sns.kdeplot(d2[d2[&#39;Status&#39;]==1][col],label=&quot;Class 1&quot;,shade=True,ax=axs[index])<br>    sns.kdeplot(d2[d2[&#39;Status&#39;]==0][col],label=&quot;Class 0&quot;,shade=True,ax = axs[index])<br>    axs[index].set_xlabel(col)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAkUpaE104I5ukJ32JTdeQ.png" /><figcaption>Predicted Probabilities Distribution (Image by Author)</figcaption></figure><p>If there were any slightest of doubts earlier, I guess now your choice would be quite clear, Model_2 is a clear winner. But the AUC-ROC values would be same for both, this is the drawback it just measures if model is able to rank order the classes correctly it does not look at how well the model separates the two classes, hence if you have a requirement where you want to use the actual predicted probabilities then AUC-ROC might not be the right choice, for those who are curious log loss is one such metric that solves this problem</p><p>So ideally one should use AUC-ROC when the dataset does not have a severe imbalance and when your use case does not require you to deal with actual predicted probabilities.</p><h3><strong>AUC FOR MULTI-CLASS</strong></h3><p>For a multi-class setting we can simply use one vs all methodology and you will have one ROC curve for each class. Lets say you have four classes A, B, C, D then there would ROC curves and corresponding AUC values for all the four classes, i.e. once A would be one class and B , C and D combined would be the others class, similarly B is one class and A , C and D combined as others class, etc.</p><h3>END NOTES</h3><p>AUC-ROC is something you would encounter a lot while working on classification problems, be it an online hackathon or a project that is assigned to you in your organization. I hope I was able to give some basic understanding on what exactly AUC-ROC is and when to use it. In case you want to discuss something or have any suggestions you can reach me at:</p><p>LinkedIn : <a href="https://www.linkedin.com/in/ravindra-sharma-832a04156">https://www.linkedin.com/in/ravindra-sharma-832a04156</a></p><h3>REFERENCES</h3><p>[1]: <a href="http://www.math.utah.edu/~gamez/files/ROC-Curves.pdf">“Using the Receiver Operating Characteristic (ROC) curve to analyze a classification model: A final note of historical interest”</a>(PDF). <em>Department of Mathematics, University of Utah</em>. Department of Mathematics, University of Utah. Retrieved May 25, 2017</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5914185d24e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/auc-roc-simplified-5914185d24e">AUC-ROC: Simplified</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[Central Limit Theorem: An Intuitive Walk-Through]]></title>
            <link>https://medium.com/swlh/central-limit-theorem-an-intuitive-walk-through-36f55bd7668d?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f55bd7668d</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 07:01:16 GMT</pubDate>
            <atom:updated>2020-08-05T12:22:32.915Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Data Driven Understanding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7q-J9tNmyEBzTEqqWgsOrw.jpeg" /><figcaption>Source: <a href="http://matemateca.ime.usp.br/">Matemateca IME-USP</a></figcaption></figure><p>One of the most beautiful concepts in statistics and probability is <em>Central Limit Theorem</em>,people often face difficulties in getting a clear understanding of this and the related concepts, I myself struggled understanding this during my college days (eventually mugged up the definitions and formulas to pass the exam). In its core it is a very simple yet elegant theorem that enables us to estimate the population mean. Here I will try to explain these concepts using this toy <a href="https://www.kaggle.com/carlolepelaars/toy-dataset">dataset</a> on customer demographics available on Kaggle (this is a fictional dataset created for educational purposes). Without wasting much time lets dive in and try to understand what CLT is</p><h3>CENTRAL LIMIT THEOREM</h3><p>Here is what Central Limit Theorem states</p><blockquote>If you take sufficiently large samples from a distribution,then the mean of these samples would follow approximately normal distribution with mean of distribution approximately equal to population mean and standard deviation equal on 1/√n times the population standard deviation (here n is number of elements in a sample)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*RJ5b6ZVZ53MKGiLrX2lzjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DffbJODI-zBWqIu4TVVIGA.png" /><figcaption>Source: <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><p>Now comes the fun part, in order to have a better understanding and appreciation of the above statement, let us take our toy dateset (will take the annual income column for our analysis) and try to check if these approximations actually holds true.</p><p>We will try to estimate the mean income of a population, first let us have a look at the distribution and size the population</p><pre>df = pd.read_csv(r&#39;toy_dataset.csv&#39;)<br>print(&quot;Number of samples in our data: &quot;,df.shape[0])<br>sns.kdeplot(df[&#39;Income&#39;],shade=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*nW_2E4V_rzkLCNq0Y8j1vw.png" /><figcaption>Annual Income Distribution of Population (Image By Author)</figcaption></figure><p>Well, we can fairly say this is isn’t exactly a normal distribution and the original <strong><em>population mean</em></strong> and <strong><em>standard deviation</em></strong> is <strong><em>91252.798</em></strong> and <strong><em>24989.501</em></strong> respectively. Now have a good look on to these numbers and let’s see if we could use Central Limit Theorem to approximate these values</p><h3>GENERATING RANDOM SAMPLES</h3><p>Now let us try to generate random samples from the population and try to plot sample mean distributions</p><pre>def return_mean_of_samples(total_samples,element_in_each_sample):<br>    sample_with_n_elements_m_size = []<br>    for i in range(total_samples):<br>        sample = df.sample(element_in_each_sample).mean()[&#39;Income&#39;]<br>        sample_with_n_elements_m_size.append(sample)<br>    return (sample_with_n_elements_m_size)</pre><p>We will use this function to generate random sample means and later use it to calculate sampling distributions</p><p>Here we are taking 200 samples with 100 elements in each samples and see how the sample mean distribution looks like</p><pre>sample_means = return_mean_of_samples(200,100)<br>sns.kdeplot(sample_means,shade=True)<br>print(&quot;Total Samples: &quot;,200)<br>print(&quot;Total elements in each sample: &quot;,100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QPoSMgzRg533RHYgEQBowA.png" /><figcaption>Sample Mean Distribution (Image By Author)</figcaption></figure><p>Well that looks pretty normal, so now we can assume that with sufficient sample size, sample means do follow normal distribution irrespective ofthe original distributions</p><p>Now comes the second part, let us try to see if we could estimate the population mean from this sampling distribution, below is a piece of code that generates different sampling distributions by varying total sample size and elements in each samples</p><pre>total_samples_list = [100,500]<br>elements_in_each_sample_list = [50,100,500]<br>mean_list = []<br>std_list = []<br>key_list = []<br>estimate_std_list = []<br>key=&#39;&#39;<br>pop_mean = [population_mean]*6<br>pop_std = [population_std]*6<br>for tot in total_samples_list:<br>    for ele in elements_in_each_sample_list:<br>        key = &#39;{}_samples_with_{}_elements_each&#39;.format(tot,ele)<br>        key_list.append(key)<br>        mean_list.append(np.round(np.mean(return_mean_of_samples(tot,ele)),3))<br>        std_list.append(np.round(np.array(return_mean_of_samples(tot,ele)).std(),3))<br>        estimate_std_list.append(np.round(population_std/(np.sqrt(ele)),3))</pre><pre>pd.DataFrame(zip(key_list,pop_mean,mean_list,pop_std,estimate_std_list,std_list),columns=[&#39;Sample_Description&#39;,&#39;Population_Mean&#39;,&#39;Sample_Mean&#39;,&#39;Population_Standard_Deviation&#39;,&quot;Pop_Std_Dev/&quot;+u&quot;\u221A&quot;+&quot;sample_size&quot;,&#39;Sample_Standard_Deviation&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZCWQnMwLi1DFcKEL1fzLg.png" /><figcaption>Summary of sampling distribution generated (Image By Author)</figcaption></figure><ul><li>Look at second and third columns, we can clearly see the mean of sampling distribution is very close to the population mean in all the distributions</li><li>Have a look at the last two columns, initially there is some difference in the deviations but as the sample size increases this difference becomes negligible</li></ul><p>Let us further plot these sampling distributions and population mean and see how the plots look</p><pre>def plot_distribution(sample,population_mean,i,j,color,sampling_dist_type):<br>    sns.kdeplot(np.array(sample),color = color,ax = axs[i,j],shade=True)<br>    axs[i, j].axvline(population_mean, linestyle=&quot;-&quot;, color=&#39;r&#39;, label=&quot;p_mean&quot;)<br>    axs[i, j].axvline(np.array(sample).mean(), linestyle=&quot;-.&quot;, color=&#39;b&#39;, label=&quot;s_mean&quot;)<br>    axs[i, j].set_title(key)<br>    axs[i, j].legend()</pre><pre>colors = [&#39;r&#39;,&#39;g&#39;,&#39;b&#39;,&#39;y&#39;, &#39;c&#39;, &#39;m&#39;, &#39;k&#39;]<br>plt_grid  = [(0,0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]<br>sample_sizes = [(100,50), (100, 100), (100, 500), (500, 50), (500, 100), (500, 500)]</pre><pre>total_samples_list = [100,500]<br>elements_in_each_sample_list = [50,100,500]</pre><pre>fig, axs = plt.subplots(3, 2,  figsize=(10, 9))<br>i = 0<br>for tot in total_samples_list:<br>    for ele in elements_in_each_sample_list:<br>        key = &#39;{}_samples_with_{}_elements_each&#39;.format(tot,ele)<br>        plot_distribution(return_mean_of_samples(tot,ele), population_mean , plt_grid[i][0], plt_grid[i][1] , colors[i], key)<br>        i = i + 1<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*WMBHGkxxUbyWaMAyToBluQ.png" /><figcaption>Plot for sample mean distribution and population mean (Image By Author)</figcaption></figure><p>As you can see the mean of sampling distribution is pretty close to the population mean. (<em>Here is a food for thought, have a look at first and last plots do you notice there is a difference in spread of data, first one is more spread around population mean as compared to last, look at the scale on x axis for better clarity, well once your reach the end of this blog try to answer this question yourself</em>)</p><h3>CONFIDENCE INTERVAL</h3><blockquote>A confidence interval can be defined as an entire interval of plausible values of a population parameter, such as mean based on observations obtained from a random sample of size n.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg0FMd3Vyy2yWHl9Y8IYLA.png" /><figcaption>Source:<a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><p>Let’s summarize our leanings so far and and try to understand Confidence Intervals from it.</p><ul><li>Sampling distribution of mean of samples follow a normal distribution</li><li>Hence using property of normal distribution <em>95% of sample means lie within two standard deviations</em> of population mean</li><li>We can rephrase the sentence and say that <strong><em>95% of these Intervals or rather Confidence Intervals (two standard deviations away from the mean on either side) contains the population mean</em></strong></li></ul><p>Here I would like to give more focus on the last point we talked about. People often get confused and say once we take a random sample and calculate its mean and corresponding 95% CI, there is a 95% chance that the population mean lies within 2 standard deviations of this sample mean, this statement is wrong</p><p>When we talk about a probability estimate w.r.t to a sample then that sample gets fixed here (<em>including the corresponding sample mean and confidence interval</em>), also population mean eventually is a fixed value, hence there is no point in saying there is a 95% probability of a fixed point (population mean) lying in a fixed interval (CI of sample used), it would either exist there or not, instead the more proper definition of 95% CI is</p><p>If random samples are taken and corresponding sample means and CI’s (two standard deviations from the mean on either side) are calculated, then 95% of these CI’s would contain the population mean. For example let’s say we take 100 random samples and calculate their CI’s then 95% of these CI’s would contain the population mean</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qds8usnKaNb-onIlFqnkg.png" /><figcaption>Source:<a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a></figcaption></figure><p>Enough of the talking business, now as always lets take our toy dataset and see if this holds true.</p><pre>def get_CI_percent(size):<br>    counter = 0<br>    for i in range(size):<br>        is_contains = False<br>        sample_mean = df.sample(50)[&#39;Income&#39;].mean()<br>        lower_lim = sample_mean - 2*standard_error<br>        upper_lim = sample_mean + 2*standard_error<br>        if (population_mean&gt;=lower_lim)&amp;(population_mean&lt;=upper_lim):<br>            is_contains = True<br>            counter = counter + 1    <br>    return  np.round(counter/size*100,2) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*CJ0p6dpm948vVyJHH7MNFg.png" /><figcaption>95% Confidence Interval Validation(Image By Author)</figcaption></figure><p>I took 20 random samples with 50 elements in each sample and calculated their sample means and respective two standard deviation intervals (95% CI’s), 18 out of 20 intervals contained these intervals. (actually this interval count varied between 18–20)</p><p>Instead of giving a point estimate (taking a sample and calculating its mean), it is more plausible to give an interval estimate (this helps us include any error that might occur due to sampling) hence we calculate these confidence intervals along with the sample mean.</p><h3>CONCLUSION</h3><p>One question that some of you might be having, why go through so much hard work of taking random samples, calculating its sample mean hence the Confidence Interval later, why not simply do np.mean() like it was done in the very first line of code here.</p><p>Well if you have your data completely available in digital form and you could calculate your population metric just from a single line of code within milliseconds then definitely go for it there is no point in going through the whole process</p><p>However there are many scenarios where data collection itself is a big challenge, suppose we want to estimate mean height of people in Bangalore then it is practically impossible to go to every person and record the data. This is where these concepts of sampling, Confidence Intervals are really useful.</p><p>Here is the <a href="https://github.com/ravi207/central-limit-theorem/blob/master/Central_Limit_theorem-Walkthrough.ipynb">link</a> to the code file and the dataset. For those of you who are new to these topics, I would strongly recommend to try running the code yourself, play around with the dataset (there are other fields like age) to get a better understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f55bd7668d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/central-limit-theorem-an-intuitive-walk-through-36f55bd7668d">Central Limit Theorem: An Intuitive Walk-Through</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[Ensemble Methods: A Beginner’s Guide]]></title>
            <link>https://medium.com/analytics-vidhya/ensemble-methods-a-beginners-guide-d14fe23b1ab9?source=rss-e92edf40ff2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d14fe23b1ab9</guid>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <dc:creator><![CDATA[Ravindra Sharma]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 17:31:12 GMT</pubDate>
            <atom:updated>2020-07-28T13:36:01.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2HjeDyNWW3hBrW5mX_vkQ.png" /></figure><h3><strong>Introduction</strong></h3><p>When I started my Data Science journey,few terms like ensemble,boosting often popped up.Whenever I opened the discussion forum of any Kaggle Competition or looked at any winner’s solution,it was mostly filled with these things.</p><p>At first these discussions sounded totally alien,and these class of ensemble models looked like some fancy stuff not meant for the newbies,but trust me once you have a basic understanding behind the concepts you are going to love them!</p><h3>Ensemble</h3><p>So let’s start with a very simple question,What exactly is ensemble? I googled it up and came across this definition</p><blockquote>“A group of separate things/people that contribute to a coordinated whole”</blockquote><p>In a way this is kind of the core idea behind the entire class of ensemble learning! So let us now put it out in a more technical way,basically ensembles are a class of algorithms where a group of individual models(usually called the base learners) are grouped in certain ways to take an overall decision hence improving the predictive power of the overall model</p><p>Broadly speaking there are four types of ensemble techniques</p><ul><li>Bagging</li><li>Boosting</li><li>Cascading</li><li>Stacking</li></ul><p>(Here I would be discussing about the first two mostly)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*DKDI6EZJHkw2YgjLVDohiQ.png" /><figcaption>Source: <a href="https://www.datacamp.com/community/tutorials/adaboost-classifier-python">Datacamp</a></figcaption></figure><p>At its core the idea behind all four types is same,group of base learners are combined to take a decision,only difference lies in two aspects</p><ul><li>What type of base learners are used</li><li>How are these base learners combined to take an overall decision</li></ul><p>Now,let us try to answer these two questions for the above techniques</p><h3>Bagging</h3><p>Well let’s rewind the clocks a bit and go back to the school days for a while, remember you used to get a report card with an overall grade.Well how exactly was this overall grade calculated,your teachers of respective subjects gave some feedback based on their set of criteria,for example your math teacher would assess you on his own criteria like algebra,trigonometry etc, sports teacher would judge you how you perform on the field,your music teacher would judge on you vocal skills.Point being each of these teachers have their own set of rules of judging the performance of a student and later all of these are combined to give an overall grade on the performance of the student.</p><p>In a very layman terms,bagging does something like this only.Think of each teacher as a base model having their own criteria/features and decision from each base model/teacher is aggregated to calculate the overall prediction/grade.</p><p>So basically bagging is a technique where multiple base learners(for example decision trees) are trained in parallel and during prediction the results of these base learners are aggregated together through various methods like majority vote,mean etc to get a net outcome.Now imagine if you train every base learner(let’s say a decision tree) with the entire dataset there is a high chance these models would give the same results hence aggregating them would not add much value.To solve this each base learner gets to see a slightly different version of the original training dateset so that each model is trained differently and and when aggregated some meaningful results could be obtained. In order for each base learner to see a different version of the original dateset two techniques are used</p><ul><li>Row Sampling</li><li>Column Sampling</li></ul><p>Now instead of giving the entire dateset to each base learner a random subset of row,columns are given to them .One key thing to note here is we do bootstrapping(sampling with replacement) for rows only and not columns i.e each bootstrapped subset can have same rows multiple times but columns are unique(if we do bootstrap sampling for columns also then the base learners could face the problem of collinearity)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*2vD0CEE70DM9YvOwZWDmyQ.jpeg" /><figcaption>Source: <a href="https://www.sciencedirect.com/topics/engineering/random-forest">ScienceDirect</a></figcaption></figure><p>Now each base learner is trained differently and this helps reducing net variance of the overall model(even if the base learners have a high variance but once results are aggregated the net variance of the model reduces).Now as an example Random Forest is one of the most popular bagging techniques which uses all the above principles discussed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*QsU9hzwpaiIpO-yfOkHEhA.gif" /><figcaption>The basic structure of a Random Forest model (<a href="https://www.datascience.com/blog/random-forests-decision-trees-ensemble-methods">Random Forests, Decision Trees, and Ensemble Methods Explained</a>, by Dylan Storey)</figcaption></figure><h3>Boosting</h3><p>Now let’s move to one of the most widely used techniques in all the data science hackathons/competitions.The underlying working principle is similar to bagging,in bagging base learners take decision parallely and later this decision is aggregated whereas in boosting base learners takes decision sequentially(output of one model is used as an input to others) such that next model learns on the errors/mistakes and mistakes of previous models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3iotIOoNo996-JPTE1lDw.png" /></figure><p>Now let us try to understand this by an intuitive example,let’s say a golfer is trying to hit the ball to a hole 500 m away.The first shot he would take would try to cover the maximum gap and come as close to the hole as possible.Let’s say after the first shot he is 80 m away now the golfer would reassess the target and adjust his swing accordingly to cover this residual distance.Let us assume he covers a further distance of 20 m,now in the next shot he would be closer to the hole and tap the ball more softly.</p><p>This is broadly how a boosting algorithm works,here each shot can be considered as a sequential base learner that is trained on the output/residual distance from the previous shot/base learner.</p><p>By the way doesn’t this approach sound familiar,converging to the target gradually and taking smaller and smaller steps as reaching closer to the the optima,if it reminds you of Gradient Descent then you are absolutely correct! In fact there is a very popular boosting algorithm called Gradient Boosted Decision Tree(GBDT),now you are free to derive your conclusions regarding nomenclature of that model.</p><p>AdaBoost or Adaptive Boosting is another example of boosting,the underlying principle is still the same,each model learns from the errors made by the previous models,here the only difference is instead of learning on residual errors,more weights are assigned to the misclassified points by the previous model,XGBoost is nothing extra but a more optimized implementation GBDT.</p><h4>END NOTE</h4><p>These ensemble models are very powerful techniques,that help us to build some strong Machine Learning models,having said that they are not some sort of magic wands that you could wave over to produce desired results every time,there some limitations to them as well having increasing the complexity of model comes at the cost of its interpretability,in order to develop good models one must not always rely blindly on these complex models,you still need to invest time in other important things in a Machine Learning Project like Exploratory Data Analysis,Feature Engineering,etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*a5QjNIJ3fRACDOB6wFr-bw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d14fe23b1ab9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/ensemble-methods-a-beginners-guide-d14fe23b1ab9">Ensemble Methods: A Beginner’s Guide</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>