<?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 Debadri Sengupta on Medium]]></title>
        <description><![CDATA[Stories by Debadri Sengupta on Medium]]></description>
        <link>https://medium.com/@debadri3?source=rss-56ec35fa4a57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Dus_Qpr46v9-mtwvDbo9rQ.png</url>
            <title>Stories by Debadri Sengupta on Medium</title>
            <link>https://medium.com/@debadri3?source=rss-56ec35fa4a57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:08:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debadri3/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[Building a content-based movie recommender system]]></title>
            <link>https://debadri3.medium.com/why-recommend-76385c315a19?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/76385c315a19</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 20:35:34 GMT</pubDate>
            <atom:updated>2022-09-15T08:24:15.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xFgvke7cDUYLkVX_.jpg" /></figure><h3>Why recommend?</h3><p>Ever visited an offline clothing shop? Noticed how when you like a particular dress, the salesperson shows you half a dozen others that you may prefer? On the back of his mind, either by choosing clothes with similar features or the clothes liked by previous users, he is suggesting the products. These, grossly, are content-based and collaborative filtering methods respectively.</p><p>In our case, the ML system is the salesperson. Whether it be an e-commerce company, or a music/book/video streaming one, a highly accurate recommendation system is paramount if one is to achieve high conversion rates (On a personal note, I feel Spotify makes the most ‘personalized’ playlists for you).</p><p><strong>In this project, we are interested to build a content-based movie recommendation system and deploy it on the cloud. We are essentially trying to mimic Netflix.</strong></p><h3>Dataset-</h3><p>The dataset was obtained from <a href="https://www.kaggle.com/datasets/tmdb/tmdb-movie-metadata?select=tmdb_5000_movies.csv">https://www.kaggle.com/datasets/tmdb/tmdb-movie-metadata?select=tmdb_5000_movies.csv</a>.</p><p>The ‘movies’ csv file contains information purely about the movie- its language, genre, budget, plot and stuff.</p><p>The ‘credits’ datafile contains information about the cast and crew involved in the movie.</p><p>As we’ll see, both will be vital in predicting the ratings of the movie.</p><p>The following are the attributes in the movies file explained-</p><blockquote>budget — budget of the movie in USD</blockquote><blockquote>genres — genre(s) in which the movie can be classified into</blockquote><blockquote>homepage — official website of the movie</blockquote><blockquote>id — id of the movie in the TMDB website</blockquote><blockquote>keywords — roughly the most important words in the description of the movie</blockquote><blockquote>original_language — language of the movie</blockquote><blockquote>original_title — title in which the movie was actually released (maybe in some other language)</blockquote><blockquote>overview— description of the movie</blockquote><blockquote>popularity — a score to judge the current popularity of the movie. Read more: <a href="https://developers.themoviedb.org/3/getting-started/popularity">https://developers.themoviedb.org/3/getting-started/popularity</a></blockquote><blockquote>production_companies — movie houses involved in production</blockquote><blockquote>production_countries — country in which the movie was produced</blockquote><blockquote>release_date — date of release of the movie (to be parsed as datetime)</blockquote><blockquote>revenue — total revenue earned in USD</blockquote><blockquote>runtime — duration of the movie in minutes</blockquote><blockquote>spoken_languages — languages spoken inside the movie</blockquote><blockquote>status — current status of the movie, whether released, in post-production or rumored.</blockquote><blockquote>tagline — tagline of the movie</blockquote><blockquote>title — name of the movie</blockquote><blockquote>vote_average — average rating of the movie by users in the TMDB website.</blockquote><blockquote>vote_count — number of users who voted.</blockquote><p>Here are the attributes of the credits file-</p><blockquote>movie_id — foreign key referencing to the id of the movie table</blockquote><blockquote>title — name of the movie</blockquote><blockquote>cast — names of the actors alongwith the character played (and other metadata)</blockquote><blockquote>crew — names of other members involved in production (directors, producers, sound directors etc.)</blockquote><p>Both the dataframes are merged on ‘title’ column.</p><h3>Data pre-processing-</h3><p>Since in the merged dataframe there are 23 columns, we need to do some manual feature removal. The following are the features <strong>we would keep</strong>-</p><blockquote>genres — highly important in predicting if a user will like it</blockquote><blockquote>id — will be later used within the website</blockquote><blockquote>keywords , overview — contains descriptions of the movie which are important content.</blockquote><blockquote>title — is the name of the movie</blockquote><blockquote>cast- actors of the movie</blockquote><blockquote>crew- people involved in production (director etc.) .</blockquote><p>Numerical features (like release_date, revenue, popularity, vote_average etc.) have been removed as they don’t relate with the ‘content’ of the movie. Tags are often weird and don’t provide relevant information of the movie content. Removal of other features is self-explanatory.</p><p>Note — release_date can be a discerning factor in judging the content of the movie.</p><p>After this, simple missing value imputation (on ‘overview’) and duplicates were checked.</p><h4>Problem with genres, keywords, cast, crew columns-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXeME8UKZYqefWT2AE6Bxw.png" /></figure><p>Unfortunately, these columns did not have the names in straightforward fashion but as a list of dictionaries. We need to pre-process these.</p><pre>def helper (lst, if_crew=False, if_top=False):</pre><pre>ans=list()</pre><pre>if (if_crew==True):</pre><pre>for dic in eval(lst):</pre><pre>if (dic[&#39;job&#39;]==&#39;Director&#39; or dict[&#39;job&#39;]==&#39;Writer&#39;): #for crew column only director, writer selected</pre><pre>ans.append(dic[&#39;name&#39;])</pre><pre>return ans</pre><pre>else:</pre><pre>for dic in eval(lst): #eval() evaluates a string to the datatype contained inside it</pre><pre>ans.append(dic[&#39;name&#39;])</pre><pre>if (if_top==False):</pre><pre>return ans</pre><pre>else:</pre><pre>return ans[0:10] #in case, we need to return top 10 actors</pre><p>For the cast, we only return the top 10 actors. For the crew, we only return writer the directors. Code is a bit complicated as it attempts to handle all 4 columns at the same time.</p><p>Also, the overview column was split as a list.</p><h4><strong>Removing space inside words-</strong></h4><p>‘Sam Worthington’ is a very different person from ‘Sam Mendes’. However, if we don’t remove the space inside the strings, both of them will contain the word ‘Sam’ which will cause erroneous recommendations. Thus ‘Sam Worthington’ must be mapped to ‘SamWorthington’.</p><p>The spaces are removed using regex.</p><h4>Creating the ‘tags’ columns-</h4><p>A tags column is created by combining genres, keywords, overview, cast and crew columns. They were combined with 2X weightage given to genre (other ratios were experimented but greater weightage to ‘crew’ resulted in recommendations of movies ONLY directed by the query director).</p><h4>Pre-processing the text in tags-</h4><p>We create a new dataframe with just the id, title and tags columns. The text is pre-processed, i.e converted to lowercase, stopwords are removed, lemmatized, special characters removed etc.</p><h3>Modelling and main-function-</h3><p>The corpus is vectorized using Tf-idf vectorizer with maximum 5000 features. After this, a similarity matrix is created using cosine similarity.</p><p>We also define a function where the query movie name is taken as input, and as output the top 5 most similar movie names are returned. This function will be executed at runtime when the model is deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*jwG5Z02buIfyhao4Or0lbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*rUshdHbaVUsu2CFLAhb0sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*yiGDxvXzZDG1bmSfyQdbjg.png" /></figure><p>Well, it seems our model is giving pretty decent results :).</p><p>As I tread towards joining the Medium Partner Program, a follow from your side would be a leap towards my goal: <a href="https://debadri3.medium.com/">https://debadri3.medium.com/</a></p><p>That’s all from my side. The model was deployed with a beautiful website built with streamlit:</p><p><a href="https://mimicing-netflix.herokuapp.com/">https://mimicing-netflix.herokuapp.com/</a></p><p>Take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76385c315a19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ideal way to learn about data (2022)]]></title>
            <link>https://medium.com/analytics-vidhya/the-ideal-way-to-learn-about-data-2021-776c595a3208?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/776c595a3208</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 06:26:40 GMT</pubDate>
            <atom:updated>2021-11-30T08:41:18.410Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The definitive roadmap for 1st and early 2nd year students!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*7-yoQZPphwRvbcOt.png" /></figure><p>Hi folks! This blog is about how I would have learnt data science and related fields if I had to start over. Please follow this guide if you are in your 1st or 2nd year and want a deep understanding of the end-to-end design of data applications in any tech company so as to have a bright career in this field! I guarantee that if you follow along this path, you’ll possess the knowledge of someone with at least 3 years in this industry.</p><h4><strong>Disclaimer-</strong></h4><ol><li>This is NOT a free guide. To the best of my estimates, following the entire roadmap will cost you close to 60,000 INR (excluding GST). However, trust me, this investment will be a much better one than a so-called certification training from a coaching institute which would cost you as much, if not more.</li><li>This is NOT a guaranteed path to crack a 30–40 LPA job straight out of college. I can only assure in-depth knowledge but not such a salary from this course. If you want that, feel free to tread the competitive programming and open-source path.</li><li>I am in no way affiliated with either of these courses. I am just a student and know neither any of the institutes nor their founders. 🙂</li></ol><p>If you are still interested, please read on and follow the order in which it is the roadmap is laid.</p><h3>Python-</h3><p>I’d like to point out 3 resources. You can use any or all depending on your time constraints-</p><ol><li><a href="https://www.coursera.org/specializations/python"><strong>Python for Everybody- Charles Severance on Coursera- </strong></a>Frankly, the first course for 60–70% of Python developers out there. You’ll be taught by an amazingly cool professor from the University of Michigan.</li><li><a href="https://www.youtube.com/playlist?list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0"><strong>Python playlist by Dhaval Patel-</strong></a><strong> </strong>You’ll be learning from a software engineer who has worked with Nvidia and Bloomberg. Consider following his channel too if you want to get into this field.</li><li><a href="https://www.youtube.com/c/TechWithTim"><strong>Python playlist by Tim-</strong></a><strong> </strong>Young software engineer with whom most of you can resonate. He has 3 playlists- beginner, intermediate and advanced. You can also consider building some cool Python projects from his channel. Worth subscribing!</li></ol><p>P.S- If you have time, consider checking out Flask/Django frameworks from Tim or Prof. Charles Severance (more theory-intensive). But you can skip it for now.</p><h3>SQL-</h3><p>Learn this from <a href="https://www.youtube.com/watch?v=HXV3zeQKqGY">freeCodeCamp</a> or <a href="https://www.youtube.com/watch?v=7S_tz1z_5bA">Mosh</a>. The main key here is to practice. Do that from Leetcode, Hackerrank and SQLZoo.</p><h3><strong>Data Structures and Algorithms-</strong></h3><p>Might sound counter-intuitive but I suggest not doing this in Python. Choose C++ or Java and practice 1–2 Leetcode easy to mediums daily just in case you have to fall back to the traditional software engineering job. Trust me, you’ll get a gazillion of resources on YouTube for this. 😂</p><h3>Data Engineering-</h3><p>Yup, you heard that right! You will have a better foundation for Data Science and ML if you start with Data Engineering. <a href="https://trendytech.in/">TrendyTech</a> is a good course to take in this field. Truth be told, there aren’t a lot of quality, practical courses in this field anyway.</p><p>Note- Data Engineering is a booming field. If you love the course, your journey ends here (well till college at least), and there’s no need to read further. Complete the course, do as many internships as you can. Skilled data engineers are paid as much, if not higher than data scientists and there are very few skilled professionals in this field yet the demand is ever-growing. Besides, this field is more welcoming to freshers with just a Bachelors’ degree than Machine Learning. So the path’s pretty rosy.</p><h3>Data Science and Machine Learning-</h3><p>Now, here’s the juicy part of the post. To spit facts, <a href="https://www.appliedaicourse.com/">AppliedAI Course</a> is hands down the best course out there in this field. The instructor, Srikanth Verma sir (with rich experience of having worked in Amazon and Yahoo in machine learning roles) is the best ML instructor in India I’ve seen and his teaching skills is on par (if not, at times better, XD) with the instructors at Stanford, MIT, etc. He will make you fall in love with machine learning with the perfect blend of theory and practical nature of his lectures.</p><p>Note-</p><ol><li>There are 30 assignments in the course which are quite tough nuts to crack. Good luck with that.</li><li>You’ll get some live sessions along with the course lectures. You can ignore the ones for experienced folks like those of ML system design etc., for now. There’ll be some code-walkthroughs and interview questions like sessions which you should watch.</li><li>You’ll be having a good portfolio of projects by the end of this course. Consider deploying the projects using methods discussed by Srikanth Sir in the live videos (Flask, Streamlit, Sagemaker, KubeFlow, etc). This helped me a lot.</li><li>iNeuron too has a data science course. It is more focused on coding applications rather than theory. That’s another alternative for you.</li><li>This course covers 70 percent of data science in the real world. For the rest, read on.</li></ol><h3><strong>Practical Data Science-</strong></h3><p>Try finishing many courses from <a href="https://www.logikbot.com/">LogikBot</a> to gain experience on what kind of data science is actually done in the real world. Reading e-books by <a href="https://machinelearningmastery.com/products/">Jason Brownlee</a> is another fantastic way of doing the same. Basically understanding the coding aspects.</p><h3>Conclusion-</h3><p>Whoa! That’s a lot of time involvement. I’d estimate at around 2 years for a relatively bright student. If you somehow still have time, consider learning Flask/Django and watch ML system design videos by AppliedAI particularly if you are aiming for Machine Learning Engineer roles.</p><p>If you have completed the roadmap, are on the journey, or planning to get started feel free to connect! Please ask queries in the comments section. And in the end, be generous in your claps, and do follow <a href="https://debadri3.medium.com/">me</a> for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776c595a3208" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-ideal-way-to-learn-about-data-2021-776c595a3208">The ideal way to learn about data (2022)</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>
        <item>
            <title><![CDATA[Redefining Cancer Treatment- The Memorial Sloan Way]]></title>
            <link>https://medium.com/analytics-vidhya/redefining-cancer-treatment-the-memorial-sloan-way-b71ef4eed284?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71ef4eed284</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 05:25:59 GMT</pubDate>
            <atom:updated>2023-01-08T16:33:59.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*2W6deFnCzDuJw33z.jpg" /></figure><p>Whenever a patient has symptoms of cancer, the cancer tumour is taken out and sequenced. Genetic information in the tumor cell is stored in the form of DNA. It is then transcribed to form RNA which is then translated to form proteins/amino acids. In case of a mutation, or a mistake in DNA sequence, the resultant amino acid is affected giving rise to a variation for the particular gene.</p><p>Thousands of genetic mutations may be present in the sequence. We need to distinguish the malignant mutations (drivers leading to tumour growth) from the benign (passenger) ones.</p><p>Our goal will be to classify the given gene-variation pair into one of 9 categories of cancer mutations based on knowledge from text-based clinical literature.</p><p>For reference, each categorical class label corresponds to the following mutation-</p><p>1: Likely Loss-of-function</p><p>2: Likely Gain-of-function</p><p>3: Neutral</p><p>4: Loss-of-function</p><p>5: Likely Neutral</p><p>6: Inconclusive</p><p>7: Gain-of-function</p><p>8: Likely Switch-of-function</p><p>9: Switch-of-function</p><h3>Data information-</h3><p>Data was collected from <a href="https://www.kaggle.com/c/msk-redefining-cancer-treatment#evaluation">https://www.kaggle.com/c/msk-redefining-cancer-treatment#evaluation</a>.</p><p>Two data files are present- one contains the information about the genetic mutations and the other contains the clinical evidence (text) that human experts/pathologists use to classify the genetic mutations.</p><p>· Both these data files are having a common column called ID on which they can be merged.</p><p>Columns for each file-</p><p>File 1: training_variants (ID , Gene, Variations, Class)</p><p>Its fields are</p><ul><li><strong>ID : </strong>the id of the row used to link the mutation to the clinical evidence</li><li><strong>Gene : </strong>the gene where this genetic mutation is located</li><li><strong>Variation : </strong>the aminoacid change for this mutation</li><li><strong>Class :</strong> 1–9 the class this genetic mutation has been classified on</li></ul><p>File 2: training_text (ID, Text)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*3jGSnL0BsihkdnJKb87APg.png" /><figcaption>Sample data points from training_variants dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOhve8gThKdEWualuHFYFQ.png" /><figcaption>A sample data point from the training_text dataset. (Of course, no one except a trained pathologist can understand this!)</figcaption></figure><h3>Business constraints-</h3><ul><li>No low-latency requirement. (need not return results as fast as say, a search engine)</li><li>Interpretability is of concern. (a pathologist needs to verify why the model predicted the particular class)</li><li>Errors can be life-threatening.</li><li>The probability of a data point belonging to each class is required. (to understand the confidence of the model and decide whether human tests are further needed).</li></ul><h3>Type of machine learning problem-</h3><p>As we have 9 classes, it is a multi-class classification problem.</p><h4>Ideal Performance metrics-</h4><p>· Multi-class log-loss</p><p>· Confusion matrix</p><p><strong>Objective-</strong></p><p>To predict the probability of each data point belonging to each of the nine classes.</p><h3>Text preprocessing-</h3><p>As mentioned before, the data consists of 2 CSV files- one for variants and the other for text. They will later be joined on basis of a common ID column using pd. merge() function.</p><p>The text CSV file was not comma-separated but separated by ||. This is taken care of by using separator=’/|/|’ while reading the data. [/=escape character]</p><p>Preprocessing using NLTK library is done on text data-</p><ol><li>Any special character (characters except A-Z (including the newline character) were replaced by a single space character.</li><li>Letters were lowercased.</li><li>Multiple spaces were replaced by a single space.</li><li>Stopword removal.</li></ol><p>We perform left outer join and thus we are bound to find some IDs for whom the text field will be blank. These text fields are replaced by a string containing gene+ ‘ ’ +variation.</p><h3>Data analysis-</h3><p>Train-cross validation-test split is done in the ratio 64:16:20 using stratify=y_labels to preserve class distribution in train,cv,test splits.</p><p>We plot bar plots to show the distribution of classes in each split. They have similar percentages for each class since the split was stratified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*dP5Fgx9X2gJG4zeYsXRjWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*GfSeXP_RMktlBzt71MnKbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*DKyGzXyjRWHZtcy3aVxSDA.png" /></figure><p>From the above bar plots, clearly, the dataset is imbalanced with classes 7,4,1,2 occurring more frequently.</p><h3>Random model-</h3><p>Because our KPI is log-loss which is interpretable and varies till infinity, we need to judge our model with respect to a random model.</p><p>For every data point in the cross-validation dataset and test dataset,we generate an array of size 9 using np.random.rand(1,9) and divide each element by the sum of the array so that total probability reaches 1.</p><p>In our case, random model generated log loss of 2.5 which serves as the baseline.</p><p>The precision, recall and confusion matrices for the random model are plotted. Ideally, diagonal elements should be 1 and off diagonal elements 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDCbQRqyg7GDU5jtSW0T7g.png" /><figcaption>Precision matrix for our random model. Note that column sum=1 here because columns represent predicted class here and precision defines of all those classes predicted as k, how many are actually k.</figcaption></figure><h3>Analysis of gene feature-</h3><p>Univariate analysis of categorical gene feature is done using value_counts() function. There are 238 different genes and their histogram of no of distributions is plotted. It shows a heavily skewed distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*rgvD4s3-LVtUSbTevcxbGQ.png" /></figure><h4>Encoding gene feature-</h4><p>Two types of encoding may be done on a categorical feature- one hot encoding and response coding.</p><p>In one-hot-encoding, each feature is represented by an n-dimensional vector where n is the no. of unique values of the feature. In response coding too, each feature is represented by n-dimensional vector where n is the no. of classes. The vector is filled with probability values (captured from the entire dataset) for the gene feature to belong to the one of the 9 classes.</p><p>The below code is used for building the required response-coding dictionary where keys are the categorical variables and values are the n (here 9) dimensional vectors each corresponding to probability for a class label. [Credits: Stack Overflow]</p><pre>def get_gv_fea_dict(alpha, feature, df):</pre><pre># value_count: it contains a dict like</pre><pre># print(train_df[‘Gene’].value_counts())</pre><pre># output:</pre><pre># {BRCA1 174</pre><pre># TP53 106</pre><pre># EGFR 86</pre><pre># BRCA2 75</pre><pre># PTEN 69</pre><pre># KIT 61</pre><pre># BRAF 60</pre><pre># ERBB2 47</pre><pre># PDGFRA 46</pre><pre># …}</pre><pre># print(train_df[‘Variation’].value_counts())</pre><pre># output:</pre><pre># {</pre><pre># Truncating_Mutations 63</pre><pre># Deletion 43</pre><pre># Amplification 43</pre><pre># Fusions 22</pre><pre># Overexpression 3</pre><pre># E17K 3</pre><pre># Q61L 3</pre><pre># S222D 2</pre><pre># P130S 2</pre><pre># …</pre><pre># }</pre><pre>value_count = train_df[feature].value_counts()</pre><pre># gv_dict : Gene Variation Dict, which contains the probability array for each gene/variation</pre><pre>gv_dict = dict()</pre><pre># denominator will contain the number of time that particular feature occured in whole data</pre><pre>for i, denominator in value_count.items():</pre><pre># vec will contain (p(yi==1/Gi) probability of gene/variation belongs to perticular class</pre><pre># vec is 9 diamensional vector</pre><pre>vec = []</pre><pre>for k in range(1,10):</pre><pre># print(train_df.loc[(train_df[‘Class’]==1) &amp; (train_df[‘Gene’]==’BRCA1&#39;)])</pre><pre># ID Gene Variation Class</pre><pre># 2470 2470 BRCA1 S1715C 1</pre><pre># 2486 2486 BRCA1 S1841R 1</pre><pre># 2614 2614 BRCA1 M1R 1</pre><pre># 2432 2432 BRCA1 L1657P 1</pre><pre># 2567 2567 BRCA1 T1685A 1</pre><pre># 2583 2583 BRCA1 E1660G 1</pre><pre># 2634 2634 BRCA1 W1718L 1</pre><pre># cls_cnt.shape[0] will return the number of rows</pre><pre>cls_cnt = train_df.loc[(train_df[‘Class’]==k) &amp; (train_df[feature]==i)]</pre><pre># cls_cnt.shape[0](numerator) will contain the number of time that particular feature occured in whole data</pre><pre>vec.append((cls_cnt.shape[0] + alpha*10)/ (denominator + 90*alpha))</pre><pre># we are adding the gene/variation to the dict as key and vec as value</pre><pre>gv_dict[i]=vec</pre><pre>return gv_dict</pre><p>Notice how Laplace (additive) smoothing is also performed. It is done to ensure very small values are handled well and the model does not overfit.</p><blockquote>Consider a value ‘x’ for the feature ‘gene’:</blockquote><blockquote>1st element of the vector corresponding to ‘x’= (number of times ‘x’ occured such that data point belongs to class1 + 10*alpha / number of time ‘x’ occurred in total data+n*alpha) [where n is the number of class labels and alpha is a hyperparameter]</blockquote><p>Code to get the response-coded matrix for our dataset-</p><pre># Get Gene variation feature</pre><pre>def get_gv_feature(alpha, feature, df):</pre><pre># print(gv_dict)</pre><pre>#     {&#39;BRCA1&#39;: [0.20075757575757575, 0.03787878787878788, 0.068181818181818177, 0.13636363636363635, 0.25, 0.19318181818181818, 0.03787878787878788, 0.03787878787878788, 0.03787878787878788],</pre><pre>#      &#39;TP53&#39;: [0.32142857142857145, 0.061224489795918366, 0.061224489795918366, 0.27040816326530615, 0.061224489795918366, 0.066326530612244902, 0.051020408163265307, 0.051020408163265307, 0.056122448979591837],</pre><pre>#      &#39;EGFR&#39;: [0.056818181818181816, 0.21590909090909091, 0.0625, 0.068181818181818177, 0.068181818181818177, 0.0625, 0.34659090909090912, 0.0625, 0.056818181818181816],</pre><pre>#      &#39;BRCA2&#39;: [0.13333333333333333, 0.060606060606060608, 0.060606060606060608, 0.078787878787878782, 0.1393939393939394, 0.34545454545454546, 0.060606060606060608, 0.060606060606060608, 0.060606060606060608],</pre><pre>#      &#39;PTEN&#39;: [0.069182389937106917, 0.062893081761006289, 0.069182389937106917, 0.46540880503144655, 0.075471698113207544, 0.062893081761006289, 0.069182389937106917, 0.062893081761006289, 0.062893081761006289],</pre><pre>#      &#39;KIT&#39;: [0.066225165562913912, 0.25165562913907286, 0.072847682119205295, 0.072847682119205295, 0.066225165562913912, 0.066225165562913912, 0.27152317880794702, 0.066225165562913912, 0.066225165562913912],</pre><pre>#      &#39;BRAF&#39;: [0.066666666666666666, 0.17999999999999999, 0.073333333333333334, 0.073333333333333334, 0.093333333333333338, 0.080000000000000002, 0.29999999999999999, 0.066666666666666666, 0.066666666666666666],</pre><pre>#      ...</pre><pre>#     }</pre><pre>gv_dict = get_gv_fea_dict(alpha, feature, df)</pre><pre># value_count is similar in get_gv_fea_dict</pre><pre>value_count = train_df[feature].value_counts()</pre><pre># gv_fea: Gene_variation feature, it will contain the feature for each feature prob dist value in the data</pre><pre>gv_fea = []</pre><pre># for every feature values in the given data frame we will check if it is there in the train data then we will add the feature to gv_fea</pre><pre># if not we will add [1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9] to gv_fea</pre><pre>for index, row in df.iterrows():</pre><pre>if row[feature] in dict(value_count).keys():</pre><pre>gv_fea.append(gv_dict[row[feature]])</pre><pre>else:</pre><pre>gv_fea.append([1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9])</pre><pre>#             gv_fea.append([-1,-1,-1,-1,-1,-1,-1,-1,-1])</pre><pre>return gv_fea</pre><pre># Get Gene variation feature</pre><pre>def get_gv_feature(alpha, feature, df):</pre><pre># print(gv_dict)</pre><pre>#     {&#39;BRCA1&#39;: [0.20075757575757575, 0.03787878787878788, 0.068181818181818177, 0.13636363636363635, 0.25, 0.19318181818181818, 0.03787878787878788, 0.03787878787878788, 0.03787878787878788],</pre><pre>#      &#39;TP53&#39;: [0.32142857142857145, 0.061224489795918366, 0.061224489795918366, 0.27040816326530615, 0.061224489795918366, 0.066326530612244902, 0.051020408163265307, 0.051020408163265307, 0.056122448979591837],</pre><pre>#      &#39;EGFR&#39;: [0.056818181818181816, 0.21590909090909091, 0.0625, 0.068181818181818177, 0.068181818181818177, 0.0625, 0.34659090909090912, 0.0625, 0.056818181818181816],</pre><pre>#      &#39;BRCA2&#39;: [0.13333333333333333, 0.060606060606060608, 0.060606060606060608, 0.078787878787878782, 0.1393939393939394, 0.34545454545454546, 0.060606060606060608, 0.060606060606060608, 0.060606060606060608],</pre><pre>#      &#39;PTEN&#39;: [0.069182389937106917, 0.062893081761006289, 0.069182389937106917, 0.46540880503144655, 0.075471698113207544, 0.062893081761006289, 0.069182389937106917, 0.062893081761006289, 0.062893081761006289],</pre><pre>#      &#39;KIT&#39;: [0.066225165562913912, 0.25165562913907286, 0.072847682119205295, 0.072847682119205295, 0.066225165562913912, 0.066225165562913912, 0.27152317880794702, 0.066225165562913912, 0.066225165562913912],</pre><pre>#      &#39;BRAF&#39;: [0.066666666666666666, 0.17999999999999999, 0.073333333333333334, 0.073333333333333334, 0.093333333333333338, 0.080000000000000002, 0.29999999999999999, 0.066666666666666666, 0.066666666666666666],</pre><pre>#      ...</pre><pre>#     }</pre><pre>gv_dict = get_gv_fea_dict(alpha, feature, df)</pre><pre># value_count is similar in get_gv_fea_dict</pre><pre>value_count = train_df[feature].value_counts()</pre><pre># gv_fea: Gene_variation feature, it will contain the feature for each feature prob dist value in the data</pre><pre>gv_fea = []</pre><pre># for every feature values in the given data frame we will check if it is there in the train data then we will add the feature to gv_fea</pre><pre># if not we will add [1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9] to gv_fea</pre><pre>for index, row in df.iterrows():</pre><pre>if row[feature] in dict(value_count).keys():</pre><pre>gv_fea.append(gv_dict[row[feature]])</pre><pre>else:</pre><pre>gv_fea.append([1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9])</pre><pre>#             gv_fea.append([-1,-1,-1,-1,-1,-1,-1,-1,-1])</pre><pre>return gv_fea</pre><p>Simple one-hot-encoding works well for Logistic Regression, Linear SVM while response coding works better for Naïve Bayes, Random Forest etc. This is because linear models can handle large dimensionality better than ensemble/forest models.</p><p>We need to infer how useful the gene feature is. For this, a model is built using only gene feature as the attribute and it is checked whether the log loss is less than 2.5.</p><p>First, an SGDClassifier (with ‘log’ loss and l2 regularization and h-param tuning) is used on one-hot encoded gene features. On top of it, a Calibrated Classifier is used. This essentially implements Logistic Regression</p><p>Hyperparameter tuning using grid search is done and corresponding train,cv,test log loss is measured. It is better than a random model and is not overfitting. Thus, our gene feature is pretty useful.</p><p>Now, we have to check if the gene feature is stable. A stable feature is one whose values have significant overlapping between train, CV and test sets. If such is not the case, ML models are impossible to build.</p><p>The train , cv, and test log loss were calculated. The lack of overfitting implies feature stability. Also, we observe most (above 90%) gene features in cv and test data were present in train data too. Thus the gene feature is stable.</p><h3>Analysis of variation feature-</h3><p>Next, the categorical feature variation is analysed.</p><p>Histogram plotted for variation.value_counts() shows extremely skewed data. Most values only have a single occurrence!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*O0SrJVwghMKbJIIEzQfaxw.png" /></figure><p>CDF shows a linear plot. This infers that most value counts for features are 1.</p><p>Now, one -hot-encoding followed by Logistic Regression+Calibrated CV is done. Hyperparameter tuning for alpha is performed. However, it is seen the model does overfit which arises from feature instability.</p><p>Only around 10% of variation points in test and cv df contained in set(train df[variation]). Thus, the variation feature, though useful, is not stable.</p><h3>Analysis of text feature-</h3><p>Now, the text feature is analyzed. The same questions are asked namely,</p><p>How many unique words are present in train data?</p><p>How are word frequencies distributed?</p><p>How to featurize text field?</p><p>Is the text feature useful in predicitng y_i?</p><p>Is the text feature stable across train, test and CV datasets?</p><p>On training Logistic Regression+CalibratedCV, the training log-loss with optimal hyperparameters is good. The model does not really overfit which shows that text feature is stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*Mj4a3GGPQDz4FgTUpX7Y1w.png" /><figcaption>Metric comparison for all our features</figcaption></figure><p>Thus our feature importance is text&gt;gene&gt;variation. This is deduced from the cv and test data log loss values.</p><p>Above 95 percent of words present in test data was also present in set(train data). Thus text feature is stable too.</p><h3>Modelling-</h3><p>Next, we go for proper ML modelling.</p><p>The one-hot gene, variation, text features are horizontally stacked and converted to csr matrix. The response-coded gene, text, features are done same too.</p><h4>One-hot-encoded features are 55517-dimensional while response-coded are just 27-dimensional. Thus one-hot features are good for Logistic Regression, LinearSVM models while response-coded are better for KNN, Boosting, Random Forest, Decision Trees etc.</h4><h4>Multinomial Naive Bayes with one-hot-encoded features-</h4><p>The horizontally-stacked features are fed into a Multinomial Naïve Bayes Classifier +Calibrated Classifier with hyperparameter tuning with Grid Search.</p><p>Test log loss was inferior to the LR model just using text features. Moreover from precision and recall matrix, the model gets confused between 2–7 and 1–4 classes which form the majority of data points.</p><p>As per biz-requirements, for a particular query point from test data, both the predicted label as well as probability of classes was predicted using predict_proba().</p><p>Note that it is always recommended to use Calibrated Classifier on top of the base learner whenever output probabilities is required because it calibrates the probability values to match the expected distribution of probabilities for each class. The output probabilities vary greatly from expected class probabilities especially in case of complex non-linear models.</p><h3>KNN Classifier with response-coded features</h3><p>Next, KNN with response coded features is tried. The model performs better than previous Naive Bayes Classifier. However, confusion still occurs in the majority classes 2–7, 1–4. But performance (log-loss) on minority classes is better.</p><p>For interpretability of KNN, model.kneighbours() function is used to get the classes of nearest n neighbours.</p><h3>Logistic Regression with class balancing and one-hot-features-</h3><p>Next, an SGDClassifier (loss=’log’ and class=’balanced’) is used with one-hot encoded features. This model gives us the lowest log-loss value as of now. From the confusion matrices, we observe good results for low density classes 8,9 too. The classes were oversampled by using class balancing feature. Thus balancing helps in better precision and recall for minority classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GR5hxC9lzKogsWOzeeJ__A.png" /><figcaption>Recall matrix for class-balanced logistic regression</figcaption></figure><h3>LinearSVM Classifier with class balancing and one-hot-features-</h3><p>Next, an SGDClassifier(loss=’hinge’, class=’balanced’) is implemented. The accuracy is lower than Logistic Regression model but other metrics are comparable for LinearSVM with LR.</p><h3>Random Forest Classifier with both one-hot and response coded features-</h3><p>Random Forests with both one-hot-encoding and response-coding are trained with hyperparameters as no. of estimators and max depth of the tree. For this model, precision and recall for minority classes is 1 or near to 1. However, the majority classes are not that well classified.</p><p>Random Forest with response coding overfits and has the highest log-loss.</p><h3>Stacking Classifier-</h3><p>Using MLXtend library, a Stacking Classifier was now tried. Base learners Logistic Regression, LinearSVM, and Naïve Bayes classifiers’ probability outputs were passed to the final meta classifier Logistic Regression Model.</p><p>However, stacking models faces issues of interpretability, and the training data is split among the base models. Thus, errors for individual models are increased.</p><p>Thus, stacking is not optimal in case we have fewer data points.</p><p>Next, a Majority Voting Classifier with voting=’soft’ (i.e taking the probability outputs of base models), was also used.</p><h3><strong>Deployment-</strong></h3><p>A webpage using Flask was developed and deployed on Heroku for real-time predictions. Unfortunately, Heroku has stopped free-tier all of a sudden.</p><p>A video of the working of the webpage can be found on the project GitHub link:</p><p><a href="https://github.com/Debadri3/Personalized-Cancer-Diagnosis">https://github.com/Debadri3/Personalized-Cancer-Diagnosis</a></p><p>If you found the project useful, please be generous in your claps and follow me on Medium: <a href="https://medium.com/@debadri3">https://medium.com/@debadri3</a>. Would really help a budding author like me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71ef4eed284" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/redefining-cancer-treatment-the-memorial-sloan-way-b71ef4eed284">Redefining Cancer Treatment- The Memorial Sloan Way</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>
        <item>
            <title><![CDATA[Estimating pickup density of Yellow Cabs]]></title>
            <link>https://medium.com/analytics-vidhya/estimating-pickup-density-of-yellow-cabs-c6b45bb69331?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b45bb69331</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 15:19:55 GMT</pubDate>
            <atom:updated>2021-08-01T15:19:55.196Z</atom:updated>
            <content:encoded><![CDATA[<p>Given the ever-rising demand for luxury-based public transportation across the world, it is of prime importance to these businesses as well as the drivers themselves to accurately be able to predict the expected number of cab pickups given a time-frame and a location cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*yXgSA_i3NWAXxEAW" /><figcaption>Yellow cabs in New York City</figcaption></figure><h3>Information on taxis in New York-</h3><p>Yellow Taxis or the Yellow Medallion Taxicabs are the famous NYC yellow taxis that provide transportation exclusively through street-hails. The number of taxicabs is limited by a finite number of medallions issued by the TLC. You access this mode of transportation by standing in the street and hailing an available taxi with your hand. The pickups are not pre-arranged.</p><p>Other types of taxis include For Hire Vehicles (FHVs) and Green Taxis.</p><h3><strong>Information on the data-</strong></h3><p>The data is taken from-</p><p><a href="https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page">https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page</a></p><p>Credits for collecting and providing the dataset goes to NYC Taxi and Limousine Commission.</p><p>In our analysis, we’ll be using data of January, February and March of years 2015 and 2016. (named as yellow_tripdata_2016–02.csv , yellow_tripdata_2015–03 and so forth).</p><p>Each such dataset is of nearly 2 GB in size and occupies more than 10 million data points.</p><p>Each data point has 19 dimensions (attributes). Let’s explore them-</p><blockquote><strong>VendorID</strong></blockquote><blockquote>A code indicating the TPEP provider that provided the record.</blockquote><blockquote>1. Creative Mobile Technologies</blockquote><blockquote>2. VeriFone Inc.</blockquote><blockquote><strong>tpep_pickup_datetime</strong></blockquote><blockquote>The date and time when the meter was engaged.</blockquote><blockquote><strong>tpep_dropoff_datetime</strong></blockquote><blockquote>The date and time when the meter was disengaged.</blockquote><blockquote><strong>Passenger_count</strong></blockquote><blockquote>The number of passengers in the vehicle. This is a driver-entered value. (can be erroneous)</blockquote><blockquote><strong>Trip_distance</strong></blockquote><blockquote>The elapsed trip distance in miles reported by the taximeter.</blockquote><blockquote><strong>Pickup_longitude</strong></blockquote><blockquote>Longitude where the meter was engaged.</blockquote><blockquote><strong>Pickup_latitude</strong></blockquote><blockquote>Latitude where the meter was engaged.</blockquote><blockquote><strong>RateCodeID</strong></blockquote><blockquote>The rate code in effect for the trip.</blockquote><blockquote>1. Standard rate</blockquote><blockquote>2. JFK</blockquote><blockquote>3. Newark</blockquote><blockquote>4. Nassau or Westchester</blockquote><blockquote>5. Negotiated fare</blockquote><blockquote>6. Group ride</blockquote><blockquote><strong>Store_and_fwd_flag</strong></blockquote><blockquote>This flag indicates whether the trip record was held in vehicle memory before sending to the vendor, aka “store and forward,” because the vehicle did not have a connection to the server at the point.<br> Y= store and forward trip<br> N= not a store and forward trip</blockquote><blockquote><strong>Dropoff_longitude</strong></blockquote><blockquote>Longitude where the meter was disengaged.</blockquote><blockquote><strong>Dropoff_ latitude</strong></blockquote><blockquote>Latitude where the meter was disengaged.</blockquote><blockquote><strong>Payment_type</strong></blockquote><blockquote>A categorical variable signifying how the passenger paid for the trip.</blockquote><blockquote>1. Credit card</blockquote><blockquote>2. Cash</blockquote><blockquote>3. No charge</blockquote><blockquote>4. Dispute</blockquote><blockquote>5. Unknown</blockquote><blockquote>6. Voided trip</blockquote><blockquote><strong>Fare_amount</strong></blockquote><blockquote>The time-and-distance fare calculated by the meter.</blockquote><blockquote><strong>Extra</strong></blockquote><blockquote>Miscellaneous extras and surcharges. Currently, this only includes the $0.50 and $1 rush hour and overnight charges.</blockquote><blockquote><strong>MTA_tax</strong></blockquote><blockquote>0.50 MTA tax that is automatically triggered based on the metered rate in use.</blockquote><blockquote><strong>Improvement_surcharge</strong></blockquote><blockquote>0.30 improvement surcharge assessed trips at the flag drop. the improvement surcharge began being levied in 2015.</blockquote><blockquote><strong>Tip_amount</strong></blockquote><blockquote>Tip amount — This field is automatically populated for credit card tips. Cash tips are not included.</blockquote><blockquote><strong>Tolls_amount</strong></blockquote><blockquote>Total amount of all tolls paid in trip.</blockquote><blockquote><strong>Total_amount</strong></blockquote><blockquote>The total amount charged to passengers. Does not include cash tips.</blockquote><h4><strong>Reading the dataframe using Dask-</strong></h4><p>To handle such a large dataframe, some library other than Pandas needs to be used. This is because Pandas loads the entire dataframe into the RAM at once. Dask, an alternative, progressively loads rows from the dataframe into the RAM, processes them as per our code instruction, and then deletes them from the RAM making space for the next set of rows. This enables us to process dataframes of size greater than our local machine’s RAM. The concept is quite similar to how an OS stores large files in blocks of memory inside the hard disk. The files are accessed and processed sequentially as per the RAM capacity and then deleted.</p><p>Unlike Pandas, for functions like, say, summing up a column, Dask does not trigger immediate computation. Instead it partitons the dataframe, assigns key-value pairs to them and then parallelizes the computation.</p><p>Use the below snippet to get a visualization of the underlying Dask graph.</p><pre>df.visualize() #visualize() is used to visualize the graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcFqd_-AlGg1W0AAhX630w.png" /><figcaption>You need to have Graphviz installed. The circles represent operations while the rectangles are the results.</figcaption></figure><p>To visualize the computation of sum of fare amount column-</p><pre>month.fare_amount.sum().visualize()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbJkMly7vTipfwEJJ3FWlg.png" /></figure><p>To actually calculate the sum.</p><pre>month.fare_amount.sum.compute()</pre><p>Trivia: Up until the compute() function, the entire command looks like Pandas. Hence without the compute() function, lazy loading of entire dataset will be performed. Only on using the compute() function will delayed computation occur.</p><h3><strong>ML Problem formulation-</strong></h3><p>Revisiting our problem, the case study we are trying to solve is essentially a time-series forecasting and regression problem to find number of pickups, given location coordinates (latitude and longitude) and a 10-min time interval, in the query region and surrounding regions (clustered together).</p><p><em>A cluster region and a 10-minute time interval is given, we need to predict number of pickups during that time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fOSDXbtVyaJfkq0L.gif" /><figcaption>Sample time series data. In our case, the x-axis will be the ith 10-minute interval and the y-axis will be the number of pickups.</figcaption></figure><p>The above image is a generic image of a time-series data. In our case, we will have such representation for each region cluster.</p><h3>Performance metrics-</h3><p>Most important- Mean absolute percentage error (MAPE)</p><p>Relative error from actual number of pickups is what concerns the drivers more.</p><p>Secondary- Mean squared error.</p><h3>Data Analysis, cleaning with some engineered features-</h3><p>New York is bounded between coordinates(lat,long) — (40.5774, -74.15) &amp; (40.9176,-73.7004). Points beyond these coordinates were removed as outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8NxlBJR0BfWYBrbOvWAEw.png" /><figcaption>100 outlier locations plotted using Folium</figcaption></figure><p>The same was done for drop-off latitudes and longitudes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Z61wq5L0kc-7Ap06E4IGg.png" /><figcaption>There were some drop-offs even in the sea!</figcaption></figure><p>Attributes ‘tpep_pickup_datetime’ and ‘tpep_dropoff_datetime’ were of datatype string. These were converted to unix time-stamp format.</p><p>Then the corresponding duration in minutes were computed by subtracting unix dropoff time from pickup time/60.</p><p>In the end we have a modified dataframe with attributes-</p><blockquote># 1.’passenger_count’ : self explanatory</blockquote><blockquote># 2.’trip_distance’ : self explanatory (in miles)</blockquote><blockquote># 3.’pickup_longitude’ : self explanatory</blockquote><blockquote># 4.’pickup_latitude’ : self explanatory</blockquote><blockquote># 5.’dropoff_longitude’ : self explanatory</blockquote><blockquote># 6.’dropoff_latitude’ : self explanatory</blockquote><blockquote># 7.’total_amount’ : total fair that was paid</blockquote><blockquote># 8.’trip_times’ : duration of each trip</blockquote><blockquote># 9.’pickup_times : pickup time converted into unix time</blockquote><blockquote># 10.’Speed’ : velocity of each trip</blockquote><p>The engineered features added thus are trip_times, pickup_times and speed (in km/h) (calculated by dividing 60* trip_distance by trip_time).</p><p>Modified dataframe-</p><p>As of now, only the attributes of latitude and longitude (4 of them) and pickup time have been scrapped of outliers. We need to remove outliers from other columns too!</p><h4><strong>Outliers from trip_times-</strong></h4><p>Boxplot for trip_time values was plotted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*WxCUnri4mqku8tvvIyP1bw.png" /></figure><p>It is highly skewed and is not interpretable to detect outliers. (Remember in seaborn, points above Q3+1.5*IQR and those below Q1–1.5*IQR are considered outliers).</p><p>Thus, we adopt the percentile method. In this method, we find 0–100th percentile values to detect beyond what point the outliers occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*4H2CDSH84G77Zng2Q-9UWA.png" /></figure><p>Clearly outliers are present. Lets make our range smaller (90–100).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*gfrgFk4abJdIhF-XFw-JeQ.png" /></figure><p>Okay! We are clearly not getting the exact percentile above which we can remove the outliers. 😅</p><p>According to NYC Taxi and Limousine Commission Regulations , trip duration cannot exceed 12 hours within a 24 hour duration. Thus, those data points with trip duration &lt;1 min and &gt;720 mins were removed.</p><p>Now, we plot PDF for trip_times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*GwK-9Rn4oR5uBOGNO5xjDw.png" /></figure><p>The PDF shows a log-normal distribution. Thus, they were converted to logarithmic values to make the PDF a normal distribution. This will later assist in applying Gaussian Naive Bayes (Logistic Regression).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*KT-uuUcHzn8db7FXwLnzDw.png" /></figure><p>The log_times now look like a Gaussian distribution.</p><p>Also, Q-Q plot showed Gaussianity over +-3 std-deviations.</p><h4>Outliers from speed-</h4><p>Percentile method showed 99.9 percentile value as 45.31 miles/h. Speed values less than 0 and above 45.31 were removed.</p><p>It was also noted that average speed (sum(col)/len(df)) of all cabs is 12.45 miles/h. Thus, in 10 minutes, a cab driver, on an average can drive 2 miles. This is a reasonable size of a cluster as cab driver can easily drive 2 miles to move to another cluster in hopes of more pickups.</p><h4>Outliers from trip distance-</h4><p>Percentile method showed 99.9 percentile value as 23 miles. Trip distances less than 0 and above 23 were removed.</p><h4>Outliers from fare amount-</h4><p>The 99.9th percentile seemed a reasonable value. Thus, the elbow method was employed.</p><p>Here, we plot the last few fare amount points using matplotlib and try to estimate the outlier amount from there. Say, we sort the values in ascending order and choose the top 50 values. (var[-50:])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*krGEWPNE62gk5b6vz2j80w.png" /></figure><p>The y-axis range is too high to get the exact inflection point. Let us ignore the top 35 values and again plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*z2GztVxwG0vDU9zTePw7Ag.png" /><figcaption>var [-50:-35]</figcaption></figure><p>Much better! $800 seems a good inflection point above which points can be removed.</p><p>It is observed that a good percent of data (97 percent) is retained after outlier removal.</p><h3>Clustering regions-</h3><p>Now, the entire NYC area needs to be clustered/segmented using latitude and longitude values. K-Means has been used for this purpose.</p><p>Note that the pickup points and not the dropoff have been clustered.</p><p>K-Means generally clusters points such that the number of points in each cluster is similar. Thus, smaller clusters are seen for places with dense number of pickups and larger ones for those with sparse number of pickups.</p><p>Another constraint will be we need the inter-cluster distance to be &lt;=2 miles. [which is the average distance traversed by yellow cab in 10-min interval]. And minimum inter-cluster distance should be 0.5 miles. Else, cluster regions would be too near one another .</p><p>Cluster analysis with K-Means for various k values (no of clusters) was performed (10,20,30,40,50). Kind of a grid search with k as hyperparameter. For each k, the average number of clusters with centres within 2 miles and beyond 2 miles is calculated and their percentages evaluated. Minimum inter-cluster distance for each k was calculated too.</p><p>It was found that the best k having min distance&gt;0.5 miles (constraint) and percentage of good clusters=25 was 40.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TawD8KARGQM0jOFDegAClw.png" /></figure><p>The K-means clusters with k=40 is shown-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*VvCuYrOjYTqF1yhjflZKyw.png" /><figcaption>Plotted using matplotlib (ax.scatter).</figcaption></figure><p>Note from above how Manhattan city has small well defined clusters corresponding to more number of pickups while outlying regions have sparser clusters.</p><p>The Cluster IDs (from 1 to 40) are added to the df using kmeans.predict(). Note that I am working with the 2015 Jan data only as of now.</p><h3>Time binning-</h3><p>The UNIX time stamp for the starting of January, February and March (2015–2016) is noted.</p><p>And each pickup-time in the month is allotted a particular bin depending on the difference between UNIX pickup time and time stamp of beginning of month.</p><pre>tenminutewise_binned_unix_pickup_times=[(int((i-start_pickup_unix)/600)+33) for i in unix_pickup_times] #Here 33 is more converting GMT to EST</pre><h3>Applying Group-by</h3><p>Next, the dataframe is grouped by pick-up cluster as the primary index and pick-up bin as the secondary index. Recollect that we have chosen 40 as number of clusters (k) and 4464 (24*31*60/10) bins per cluster.</p><p>We apply count() function after group-by to count the total number of pickups for that cluster in that time bin. (This is our prediction problem).</p><pre>jan_2015_groupby = jan_2015_frame[[‘pickup_cluster’,’pickup_bins’,’trip_distance’]].groupby([‘pickup_cluster’,’pickup_bins’]).count()</pre><p>Groupby dataframe looks like this-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*5MCgDF1AdUX_Nh2KeR2GtQ.png" /></figure><p>In the next step, we observe for each cluster how many missing time bins (out of 4464) are present.</p><p>These missing time-bin values can be zero-filled or smoothed. Zero-filling will later cause division by zero errors so we smooth them.</p><p>For smoothing, we distribute pick-up values from the adjacent clusters evenly. Say we have ‘x’ pickup bin missing, we can sum no. of pickups in x-1th bin and x+1th bin and divide it by 3 and fill all of them by the result.</p><p>Note that smoothing is performed only for train data. For test data, filling with 0s is used to avoid data leakage.</p><h3>Modelling-</h3><p>This is where the interesting part arrives! There will be two types of modelling.</p><ol><li>Using pickup density values from the 2015 data (training) to calculate that of the 2016 data i.e Rt=P2016t/P2015t (called ratio features)</li><li>Using previous known pickup density values of the 2016 data itself to predict the future values.</li></ol><p>For coming calculations, we use window size=3.</p><h4>Simple moving average</h4><p>For every cluster and every 10-minute bin in 2016 (test) data, the corresponding ratios (i.e the ratio between 2016 to the 2015 values) for the last n 10-minute bins is summed and divided by n. This value is used as a current ratio and the current 2015 value is multiplied by it to get the predicted 2016 value. The corresponding error is calculated.</p><blockquote>R’t=(Rt−1+Rt−2+Rt−3….Rt−n)/n (here, n=3 chosen)</blockquote><p>Alternatively, we can use the past n 10-min bins (for a particular cluster) 2016 values themselves to find the current pickup density value.</p><blockquote>P’t=(Pt−1+Pt−2+Pt−3….Pt−n)/n (here, n=1 chosen)</blockquote><h4>Weighted moving average-</h4><p>The simple moving averages model gave equal importance to all the previous n values. However, we know intuitively that the future is more likely to be similar to the latest values and less similar to the older values. Weighted Averages converts this analogy into a mathematical relationship giving the highest weight to the latest previous value and decreasing weights to the subsequent older ones.</p><blockquote>R’t=(N∗Rt−1+(N−1)∗Rt−2+(N−2)∗Rt−3….1∗Rt−n)/(N∗(N+1)/2), here n=5. Note that weight is kept equal to the window size.</blockquote><blockquote>P’t=(N∗Pt−1+(N−1)∗Pt−2+(N−2)∗Pt−3….1∗Pt−n)/(N∗(N+1)/2), here n=2</blockquote><h4>Exponentially weighted average-</h4><p>Through weighted-average we have satisfied the analogy of giving higher weights to the latest value and decreasing weights to the subsequent ones but we still do not know which is the correct weighting scheme as there are infinitely many possibilities in which we can assign weights in a non-increasing order and tune the hyperparameter window-size. To simplify this process, we use Exponential Moving Averages which is a more logical way towards assigning weights and at the same time also using an optimal window-size.</p><p>In exponential moving averages we use a single hyperparameter alpha (α) which is a value between 0 &amp; 1 and based on the value of the hyperparameter alpha the weights and the window sizes are configured.<br> For eg, if α=0.9 then the number of days on which the value of the current iteration is based is~1/(1−α)=10 i.e. we consider values 10 days prior before we predict the value for the current iteration.</p><blockquote>R′t=α∗Rt−1+(1−α)∗R′t−1. Note that if α=0, R’t=R’t-1. If α=1, R’t=Rt-1.</blockquote><blockquote>P′t=α∗Pt−1+(1−α)∗P′t−1</blockquote><p>All the baseline models (SMA, WMA, EWMA) using both predicted and ratio features were evaluated. EWMA using previous value feature gave the best MAPE of 13.5%.</p><h3><strong>Fitting regression models-</strong></h3><p>The pick-up density values from last 5 10 minute time-bins and cluster region are added as features to our original test and train dataframe. The exponential weighted average till the time bin is also added. Additionally, we have latitude longitude values and day of the week as features.</p><p>Linear regression, RF regressor and XGBoost regressor were used. RF regressor and XGB Regressor also gives feature importance and as expected exponentiall weighted average has the highest weightage.</p><p>We noted a best performance of 12.5–13% MAPE from these models which is quite similar to our EWMA baseline model.</p><h3>Deployment-</h3><p>The model has been deployed on Heroku platform.</p><p><a href="https://nyc-cab-pickup-predictor-api.herokuapp.com/">https://nyc-cab-pickup-predictor-api.herokuapp.com/</a></p><p>Please use (latitude,longitude) values between (40.5774, -74.15) &amp; (40.9176,-73.7004) as that bounds NYC. Use reasonable numerical values for sanity :-).</p><h4>Conclusion-</h4><p>If you liked the blog please give it a generous amount of claps and follow me as I’ll be posting a few more of my projects here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b45bb69331" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/estimating-pickup-density-of-yellow-cabs-c6b45bb69331">Estimating pickup density of Yellow Cabs</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>
        <item>
            <title><![CDATA[Stack Overflow Question Tagger]]></title>
            <link>https://medium.com/analytics-vidhya/stack-overflow-question-tagger-96a045c1ca4c?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a045c1ca4c</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Thu, 03 Dec 2020 05:58:35 GMT</pubDate>
            <atom:updated>2023-01-11T23:00:08.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*dZR-6mVLWHoQr7vBIU2-kw.png" /></figure><h4>Background</h4><p>I won’t be lying if I assert that every developer/engineer/student has used the website Stack Overflow more than once in their journey. Widely considered as one of the largest and most trusted websites for developers to learn and share their knowledge, the website presently hosts in excess of 10,000,000 questions. In this post, we try to predict the question tag based on the question text asked on the website. The most common tags on the website include Java, JavaScript, C#, PHP, Android amongst others.</p><p>Proper prediction of the tags is important to ensure that the questions are suggested to users having substantial experience in answers related to the topic suggested.</p><h4><strong>Data</strong></h4><p>The data was collected from the Keyword Extraction competition by Facebook on Kaggle (<a href="https://www.kaggle.com/c/facebook-recruiting-iii-keyword-extraction/data">https://www.kaggle.com/c/facebook-recruiting-iii-keyword-extraction/data</a>).</p><p>On unzipping the dataset, we obtain the train.csv and text.csv files.</p><p><strong>Train.csv</strong> contains 4 columns: Id,Title,Body,Tags. The body consists of a lot of computer code- an issue to be addressed early.<br><strong>Test.csv</strong> contains the same columns but without the Tags.<br><strong>Size of Train.csv</strong> — 6.75GB<br><strong>Size of Test.csv</strong> — 2GB</p><p><strong>Number of rows in Train.csv</strong> = 6034195<br>The questions are randomized and contains a mix of verbose text sites as well as sites related to math and programming. The number of questions from each site may vary, and no filtering has been performed on the questions (such as closed questions).</p><p><strong>Attribute explanation-</strong></p><blockquote><strong>Id</strong> - Unique identifier for each question<br><br><strong>Title</strong> - The question&#39;s title<br><br><strong>Body</strong> - The body of the question<br><br><strong>Tags</strong> - The tags associated with the question in a space-seperated format (all lowercase, should not contain tabs &#39;\t&#39; or ampersands &#39;&amp;&#39;)</blockquote><h4><strong>Constraints-</strong></h4><p>As with every information retrieval model, high precision and high recall is a must. An incorrect label affects precision while a missed label affects recall. Both hamper user experience on the site. Latency requirements are not stringent.</p><h4>The prediction problem-</h4><p>Our problem is essentially a multi-label classification problem where each of the tags is a label and their prediction essentially is not mutually exclusive.</p><p>The evaluation metric to be used is the micro-averaged F1-score which beautifully inculcates both precision and recall simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRW4ti4a4YV1NkjNey1n7Q.png" /><figcaption>Performance metrics from the competition website</figcaption></figure><p>Because the micro F1-score includes the number of true positives, false positives and false negatives of a particular class, it also inherently weighs each class by the frequency of data points for it. However, the macro F1-score is free from such bias. It is a simple average function.</p><p>We use the micro F1-score to account for inequal size of our classes.</p><h4><strong>Exploratory Data Analysis</strong></h4><p>The data is loaded from the csv files to an SQLite database. Duplicate questions removal is done through SQL queries. The original number of rows in the database was 6034196. The new database, post deduplication, consists of 4206314 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxTlSIpiE1L9aL7e8788_g.png" /></figure><pre>#Code to get the bag of words vocabulary for the tags<br>tags = vectorizer.get_feature_names()</pre><p>Let us take a look at some alphabetically sorted tags and their counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*g1grMG1j9s7c5sxapnyRAw.png" /></figure><p>Now, we sort the tags in decreasing order of number of occurences and then plot the distribution.</p><pre>plt.plot(tag_counts)</pre><pre>plt.title(“Distribution of number of times tag appeared questions”)</pre><pre>plt.grid()</pre><pre>plt.xlabel(“Tag number”)</pre><pre>plt.ylabel(“Number of times tag appeared”)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*rW6DFwiTgPmmrowZ8T-Rww.png" /></figure><p>Noticeably, the distribution is highly skewed with the most frequent tag occurring more than 3 million times and the rarer ones occurring around once.</p><p>We need to zoom into the data to get a better understanding of the distribution. We consider the top 100 tags now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*DJN6X32Y8k1eLRqKx3cLtw.png" /><figcaption>Note that 0 → 100th percentile, 25 → 75th percentile because this is sorted in descending order.</figcaption></figure><p>The drops in the quantiles are still significant. The 75th percentile consists of barely 15 percent of the 100 percentile values. The numbers get lower with drop in quantiles.</p><p>In fact, just the top 14 tags have been used more than 1 million times. The most frequent tag (C#) is used 331505 times.</p><p>The enormous variation in the frequency of tags justifies micro-averaged F1-score as the appropriate metric.</p><p>We now plot the number of tags per question.</p><pre>sns.countplot(tag_quest_count, palette=&#39;gist_rainbow&#39;)</pre><pre>plt.title(&quot;Number of tags in the questions &quot;)</pre><pre>plt.xlabel(&quot;Number of Tags&quot;)</pre><pre>plt.ylabel(&quot;Number of questions&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*dBSXyOhtgQxfTrAthIZcbQ.png" /></figure><p>Most questions have 2–3 tags the average being around 2.9. The range of tags per question is from 1 to 5.</p><p>We now plot the Word Cloud for the tags. The font size of each word is proportional to its frequency of occurence.</p><pre>tup = dict(result.items())</pre><pre>#Initializing WordCloud using frequencies of tags.</pre><pre>wordcloud = WordCloud( background_color=’black’,</pre><pre>width=1600,</pre><pre>height=800,</pre><pre>).generate_from_frequencies(tup)</pre><pre>fig = plt.figure(figsize=(30,20))</pre><pre>plt.imshow(wordcloud)</pre><pre>plt.axis(‘off’)</pre><pre>plt.tight_layout(pad=0)</pre><pre>fig.savefig(“tag.png”)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*kc7uMaCaPhTUEurPhT1tpg.png" /></figure><p>Let’s take a look at the top 20 tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*66tx9qKUITGPTDiez0glPg.png" /></figure><p>Most of the top tags are associated with programming languages and platforms.</p><h4><strong>Text preprocessing</strong></h4><p>Due to computational limitations, 1 million data points have been sampled out of the 4 million.</p><p>Let’s take a look at an example data point.</p><pre><strong>Title</strong>:  Implementing Boundary Value Analysis of Software Testing in a C++ program?<br><strong>Body </strong>:</pre><pre>#include&lt;<br>        iostream&gt;\n<br>        #include&lt;<br>        stdlib.h&gt;\n\n<br>        using namespace std;\n\n<br>        int main()\n<br>        {\n<br>                 int n,a[n],x,c,u[n],m[n],e[n][4];\n         <br>                 cout&lt;&lt;&quot;Enter the number of variables&quot;;\n         cin&gt;&gt;n;\n\n         <br>                 cout&lt;&lt;&quot;Enter the Lower, and Upper Limits of the variables&quot;;\n         <br>                 for(int y=1; y&lt;n+1; y++)\n         <br>                 {\n                 <br>                    cin&gt;&gt;m[y];\n                 <br>                    cin&gt;&gt;u[y];\n         <br>                 }\n         <br>                 for(x=1; x&lt;n+1; x++)\n         <br>                 {\n                 <br>                    a[x] = (m[x] + u[x])/2;\n         <br>                 }\n         <br>                 c=(n*4)-4;\n         <br>                 for(int a1=1; a1&lt;n+1; a1++)\n         <br>                 {\n\n             <br>                    e[a1][0] = m[a1];\n             <br>                    e[a1][1] = m[a1]+1;\n             <br>                    e[a1][2] = u[a1]-1;\n             <br>                    e[a1][3] = u[a1];\n         <br>                 }\n         <br>                 for(int i=1; i&lt;n+1; i++)\n         <br>                 {\n            <br>                    for(int l=1; l&lt;=i; l++)\n            <br>                    {\n                 <br>                        if(l!=1)\n                 <br>                        {\n                    <br>                            cout&lt;&lt;a[l]&lt;&lt;&quot;\\t&quot;;\n                 <br>                        }\n            <br>                    }\n            <br>                    for(int j=0; j&lt;4; j++)\n            <br>                    {\n                <br>                        cout&lt;&lt;e[i][j];\n                <br>                        for(int k=0; k&lt;n-(i+1); k++)\n                <br>                        {\n                    <br>                            cout&lt;&lt;a[k]&lt;&lt;&quot;\\t&quot;;\n               <br>                        }\n                <br>                        cout&lt;&lt;&quot;\\n&quot;;\n            <br>                    }\n        <br>                 }    \n\n        <br>                 system(&quot;PAUSE&quot;);\n        <br>                 return 0;    \n<br>        }\n</pre><pre>\n\n</pre><pre>&lt;p&gt;The answer should come in the form of a table like&lt;/p&gt;\n\n<br>    &lt;pre&gt;&lt;code&gt;       <br>    1            50              50\n       <br>    2            50              50\n       <br>    99           50              50\n       <br>    100          50              50\n       <br>    50           1               50\n       <br>    50           2               50\n       <br>    50           99              50\n       <br>    50           100             50\n       <br>    50           50              1\n       <br>    50           50              2\n       <br>    50           50              99\n       <br>    50           50              100\n<br>    &lt;/code&gt;&lt;/pre&gt;\n\n<br>    &lt;p&gt;if the no of inputs is 3 and their ranges are\n<br>    1,100\n<br>    1,100\n<br>    1,100\n<br>    (could be varied too)&lt;/p&gt;\n\n<br>    &lt;p&gt;The output is not coming,can anyone correct the code or tell me what\&#39;s wrong?&lt;/p&gt;\n&#39;</pre><pre><strong>Tags </strong>: &#39;c++ c&#39;</pre><p>The following steps were taken for the preprocessing-</p><ol><li>Special characters were removed from the title and the body (excluding the code) using regular expressions.</li><li>Stop-words were removed. (except ‘C’).</li><li>HTML tags (‘&lt;something&gt;’) were removed. (These are used to make particular word of the question/answer bold, eg. &lt;b&gt;Python&lt;/b&gt; )</li><li>Conversion of words to lowercase followed by stemming by Snowball Stemmer.</li><li>Each question was made as title+question thus eliminating the ‘title’ column</li></ol><p>This is how some question bodies look after processing.</p><pre>(&#39;ef code first defin one mani relationship differ key troubl defin one zero mani relationship entiti ef object model look like use fluent api object composit pk defin batch id batch detail id use fluent api object composit pk defin batch detail id compani id map exist databas tpt basic idea submittedtransact zero mani submittedsplittransact associ navig realli need one way submittedtransact submittedsplittransact need dbcontext class onmodelcr overrid map class lazi load occur submittedtransact submittedsplittransact help would much appreci edit taken advic made follow chang dbcontext class ad follow onmodelcr overrid must miss someth get follow except thrown submittedtransact key batch id batch detail id zero one mani submittedsplittransact key batch detail id compani id rather assum convent creat relationship two object configur requir sinc obvious wrong&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;explan new statement review section c code came accross statement block come accross new oper use way someon explain new call way&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;error function notat function solv logic riddl iloczyni list structur list possibl candid solut list possibl coordin matrix wan na choos one candid compar possibl candid element equal wan na delet coordin call function skasuj look like ni knowledg haskel cant see what wrong&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;step plan move one isp anoth one work busi plan switch isp realli soon need chang lot inform dns wan wan wifi question guy help mayb peopl plan correct chang current isp new one first dns know receiv new ip isp major chang need take consider exchang server owa vpn two site link wireless connect km away citrix server vmware exchang domain control link place import server crucial step inform need know avoid downtim busi regard ndavid&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;use ef migrat creat databas googl migrat tutori af first run applic creat databas ef enabl migrat way creat databas migrat rune applic tri&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;magento unit test problem magento site recent look way check integr magento site given point unit test jump one method would assum would big job write whole lot test check everyth site work anyon involv unit test magento advis follow possibl test whole site custom modul nis exampl test would amaz given site heavili link databas would nbe possibl fulli test site without disturb databas better way automaticlli check integr magento site say integr realli mean fault site ship payment etc work correct&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;find network devic without bonjour write mac applic need discov mac pcs iphon ipad connect wifi network bonjour seem reason choic turn problem mani type router mine exampl work block bonjour servic need find ip devic tri connect applic specif port determin process run best approach accomplish task without violat app store sandbox&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;send multipl row mysql databas want send user mysql databas column user skill time nnow want abl add one row user differ time etc would code send databas nthen use help schema&#39;,) ---------------------------------------------------------------------------------------------------- (&#39;insert data mysql php powerpoint event powerpoint present run continu way updat slide present automat data mysql databas websit&#39;,) --------------------------------------------------------------------------------------------------<strong>--</strong></pre><h4><strong>Modelling-</strong></h4><p>It is crucial to propose this multi-label classification problem as a binary classification for us to apply various ML models. One vs Rest Classification will be too slow on 42000 labels. Classifier chains’ use is pertinent as the tags themselves may be correlated. For example, the presence of ‘C++’ may also trigger the presence of ‘pointers’. Label power sets may lead to a creation of a massive number of classes. Adoption of existing algorithms for multi-label classification is another approach. More information on this topic can be found on <a href="https://www.analyticsvidhya.com/blog/2017/08/introduction-to-multi-label-classification/">this link</a>.</p><p>Due to computation limitations, we cannot use all the tag labels as classes. We need to choose the top tags as per occurrence frequency for a ‘partial coverage’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*xnINhbSHPH1mCuAIKtmlOg.png" /><figcaption>Percentage of questions covered vs no of tags</figcaption></figure><p>Only using the top 5500 tags makes us cover more than 99 percent of questions <strong>partially</strong>.</p><p>Train-test-split of 80–20 ratio is performed randomly.</p><pre>total_size=preprocessed_data.shape[0]</pre><pre>train_size=int(0.80*total_size)</pre><pre>x_train=preprocessed_data.head(train_size)</pre><pre>x_test=preprocessed_data.tail(total_size — train_size)</pre><pre>y_train = multilabel_yx[0:train_size,:]</pre><pre>y_test = multilabel_yx[train_size:total_size,:]</pre><p>We now convert our pre-processed text data of the question into its Tf-Idf form.</p><pre>vectorizer = TfidfVectorizer(min_df=0.00009, max_features=200000, smooth_idf=True, norm=&quot;l2&quot;, \</pre><pre>tokenizer = lambda x: x.split(), sublinear_tf=False, ngram_range=(1,3))</pre><pre>x_train_multilabel = vectorizer.fit_transform(x_train[&#39;question&#39;])</pre><pre>x_test_multilabel = vectorizer.transform(x_test[&#39;question&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*Ojam0NnQhw9LwWzTu0aoPA.png" /></figure><p>Our feature vector is 88244 dimensional while the label vector is 5500 dimensional. We run into a problem here.</p><p>Tf-idf vectorizer stores these huge-dimensional vectors as sparse vectors. ‘scikit-multilearn’ library tries to convert such sparse vector representations to normal dense data matrices for its own use which raises us a memory error. Hence we fail to use MLKNN (a multi-label algorithm for KNN) in this case.</p><p>We instead use One vs Rest Classifier. The algorithm trains 5500 classifiers separately and uses their results.</p><pre>classifier = OneVsRestClassifier(SGDClassifier(loss=&#39;log&#39;, alpha=0.00001, penalty=&#39;l1&#39;), n_jobs=-1)</pre><pre>classifier.fit(x_train_multilabel, y_train)</pre><pre>predictions = classifier.predict(x_test_multilabel)</pre><pre>print(&quot;accuracy :&quot;,metrics.accuracy_score(y_test,predictions))</pre><pre>print(&quot;macro f1 score :&quot;,metrics.f1_score(y_test, predictions, average = &#39;macro&#39;))</pre><pre>print(&quot;micro f1 scoore :&quot;,metrics.f1_score(y_test, predictions, average = &#39;micro&#39;))</pre><pre>print(&quot;hamming loss :&quot;,metrics.hamming_loss(y_test,predictions))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*A3UB_VsSfOGrOhub4GR6Ug.png" /></figure><p>Here’s the precision-recall report for the first 10 labels-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*r-KKL7j0f_4F6aISmsAzCQ.png" /></figure><p>As we observe, the metrics are relatively low. Hyperparameter tuning is restricted due to the large size of the dataset. The training takes around 9 hours on a mid-level laptop (i5 processor). Hence, we repeat the same procedure but now for 0.5 million data points and take the top 500 labels (accounting for 90 percent partial coverage of questions).</p><p>Another step of feature engineering was also performed. Extra weight on the title of the question rather than the body. This was done by making question= title*3+ question (rather than title+question) and stored in the table of another database from where it is queried.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*HI-sm40nOvpn4GgmNFMynQ.png" /></figure><p>As seen, the metrics have improved from the previous training. The recall remains low which increases our model’s chances of missing labels. Further tuning may be used to correct this issue.</p><p>Special mention: <a href="https://youtu.be/nNDqbUhtIRg">https://youtu.be/nNDqbUhtIRg</a></p><h3>Using the MLFlow Pipeline:</h3><p>While the above method is okay for small personal projects, a larger project requires collaboration between teams and that is where tracking of the ML lifecycle becomes necessary.</p><p>From the Github repository of the open-sourced MLFlow project,</p><blockquote>MLflow is a platform to streamline machine learning development, including tracking experiments, packaging code into reproducible runs, and sharing and deploying models. MLflow offers a set of lightweight APIs that can be used with any existing machine learning application or library (TensorFlow, PyTorch, XGBoost, etc), wherever you currently run ML code (e.g. in notebooks, standalone applications or the cloud).</blockquote><p>Even to date, 49% of enterprises are just exploring the vast use cases of machine learning with no concrete plans for them. This is partly because they adopt simple traditional software engineering toolkits to solve the challenging problems associated with ML workflows like dealing with scale, logging various aspects of the pipeline like data engineering, analysis, modeling, deployment, a collaboration between these teams, tracking and monitoring past experiments and so forth.</p><p>This is where MLFlow comes into the picture. In general, MLFlow is used for-</p><ol><li>Data analysis and statistical inference to select a family of models for the business problem</li><li>Designing the MLFlow experiments to identify the best hyperparameters for the model.</li><li>Training and deploying a large-scale ML model using Apache Spark.</li></ol><p>Each of these is done using a different component of MLFlow which we’ll discuss below.</p><h4>MLFlow Tracking: Monitoring and logging experiments</h4><p>[A Databricks Community Edition workspace would be ideal as they are the providers of MLFlow. However, they do not permit more than 1 GB of storage so I had to use Colab for MLFlow]</p><p>Ngrok was used to deploy a local host server from Google Colab. MLFlow training then was started and the parameter (alpha), metrics scores, and the model pickle files were logged.</p><p>Download the MLFlow files as a zip folder on your local machine. They contain individual runs for a set of alphas as hyperparameters.</p><h4>MLFlow Project:</h4><p>Inside, the artifacts folder will be the model.pkl file. The entry point of the project along with the model flavours are mentioned in the MLmodel file.</p><p>To deploy the model at an endpoint clone the Github repository and use:</p><blockquote>mlflow models serve -m 4ce61665c3e443a4b21fb605969a1b44/artifacts/model/ -h 127.0.0.1 -p 5000</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a045c1ca4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/stack-overflow-question-tagger-96a045c1ca4c">Stack Overflow Question Tagger</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>
        <item>
            <title><![CDATA[Electric guitar classification using CNNs (Deep Learning)]]></title>
            <link>https://debadri3.medium.com/electric-guitar-classification-using-cnns-deep-learning-1f6068e6c110?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f6068e6c110</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[deeplearing]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 17:07:29 GMT</pubDate>
            <atom:updated>2020-06-13T17:40:47.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Electric guitar classification using CNNs</h3><h3><strong>Introduction</strong>-</h3><p><strong>GitHub link to project code: </strong><a href="https://github.com/Debadri3/cnn-electric-guitar-classification">https://github.com/Debadri3/cnn-electric-guitar-classification</a></p><p>The electric guitar has been one of the most adore instruments since it was widely popularized by the likes of Hendrix, Van Halen and so forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*q8tWTaufCU42OD54Lz9JvQ.jpeg" /><figcaption>Hendrix was one of the pioneers in popularizing the electric guitar</figcaption></figure><p>Likewise, two guitar manufacturing mammoths, namely, Fender and Gibson have produced several variants of the electric guitar with modifications over the years. This project is a multi-class classification problem using pre-trained Convolutional Neural Network Model from TensorFlow Hub where I attempt to classify 7 different solid-body models of the electric guitar.</p><p>The electric guitar models used as classes typically differ in body shape, pick-up positions, knob positioning and so on. We’ll see how much our model can figure these out.</p><p>For information about the types of electric guitars, check this link: <a href="https://ledgernote.com/columns/guitar-guru/types-of-electric-guitars/">https://ledgernote.com/columns/guitar-guru/types-of-electric-guitars/</a></p><h3>Creating the dataset-</h3><p>‘Bulk Image Downloader’ software was used to download dataset images. Only .jpg extension images were used while .png, .webp images were ignored.</p><p>This linked was referred to for creation of .csv labels file: <a href="https://www.datacamp.com/community/tutorials/datasets-for-images">https://www.datacamp.com/community/tutorials/datasets-for-images</a></p><p>However, the folder location need not be added before the image name as the images were uploaded and imported from my drive for the project. A separate ‘label’ column was also added to the .csv file.</p><p>Strings specifying the storage location of the images were used while pre-processing because it is easier to work with them rather than the images itself.</p><h3><strong>Processing the labels-</strong></h3><p>The ‘label’ column of the csv file was converted to a numpy array for processing.</p><p>An array containing only the unique labels was created. Then, we compare each data label with the unique label and store the corresponding Boolean array.</p><p>‘Train test split’ was applied to convert the dataset into training and valid datasets.</p><h3><strong>Pre-processing images-</strong></h3><p>The images presently were in the form of file-paths. And labels in the form of numpy arrays. We convert them to tensor, which is similar to an n-dimensional array, but can be easily computed by GPUs.</p><p>For this a function is built which reads the image in the file-path, converts it into a Tensor with 3 colour channels (RGB), normalizes the gray-scale value (0–255 to 0–1), and then converts it into our desired size (224*224 in our case, as it is the input shape expected by our future model) and returns it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*19PF5Tq09ud6ASr4TcF7hQ.png" /><figcaption>A portion of the training dataset images</figcaption></figure><h3>Creating batch data-sets-</h3><p>The function built for this can handle either of test, validation or training data. If it is training data, the batch is shuffled every time we call the function and then turns them into batches of 32 at a time for processing. According to Yann LeCun, a French pioneer of machine learning, that number is ideal as a batch size. [<a href="https://twitter.com/ylecun/status/989610208497360896?s=20">https://twitter.com/ylecun/status/989610208497360896?s=20</a>]</p><h3>Building the model-</h3><p>Transfer learning iwas used by compiling a pre-trained model from TensorFlow Hub. The model falls under ImageNet/MobileNet V2 architecture and uses a depth multiplier of 1.40 for image classification. It requires an input shape of 224*224 which our images have already been converted to. The high depth multiplier implied a chance of overfitting; hence a Dropout layer was necessary.</p><p>The activation function used is ‘softmax’ which assigns a probability of the data point of belonging to each class. It is a multi-class version of ‘sigmoid’. The loss function I used is ‘categorical cross-entropy’. Without delving into the mathematics, lower the cross-entropy better the model. Metric used for evaluation is validation accuracy.</p><h3>Creating callbacks-</h3><p>Two callbacks- TensorBoard and Early Stopping were used. The TensorBoard is essentially able to save our model’s performance logs to a directory so that we can visualize them later.</p><p>The Early Stopping callback prevents overfitting of the model when the desired parameter stops improving or starts decreasing for the specified (‘patience’) number of rounds. In our case, it was 3.</p><h3><strong>Training the model-</strong></h3><p>Model was trained for maximum 100 epochs. Early stopping would stop training much before that.</p><h3>Scoring the model-</h3><p>A mean accuracy score of around 70-75 percent was attained, depending on each ‘restart and run’ on the validation set. It may differ slightly depending on the GPU etc.</p><h3>Checking our predictions-</h3><p>First we check our TensorBoard log. The loss decreases and then reaches a constant, while the accuracy increases and reaches a constant. The ‘predictions’ array consist of the probability of each data point belonging to each of the labels. A function is built to return the label having the maximum probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*CJmY6kxDQjRfixGQveyAew.png" /><figcaption>TensorBoard log for epoch accuracy of our model</figcaption></figure><h3>Picturing our predictions-</h3><p>We first unbatchify our data. And then plot few of the images against a probability distribution of the model’s predicted labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJMRqfdbYcU0U-Cfnl7NvA.png" /><figcaption>Probability distribution prediction</figcaption></figure><h3>Conclusion:</h3><p>Our model does a better than expected job in classifying the guitars. After inspecting few images, I see that, much like other guitar players, it got confused mainly between Super Strat and the Strat. Most other predictions were accurate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f6068e6c110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluation metrics of classification models- A beginner-friendly guide]]></title>
            <link>https://debadri3.medium.com/evaluation-metrics-of-classification-models-a-beginner-friendly-guide-77c4f95b3b3d?source=rss-56ec35fa4a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c4f95b3b3d</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[evaluation]]></category>
            <dc:creator><![CDATA[Debadri Sengupta]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 08:15:05 GMT</pubDate>
            <atom:updated>2020-06-06T11:39:49.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*d8K65QYYJ_3sBOTL.png" /></figure><p>A hearty welcome to all my readers! In my first story, I discuss various methods used while evaluating a supervised learning model for classification.</p><h3>Confusion matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*kWxZ3EDUY0Xj2ytMtQQqUA.png" /><figcaption>Source: <a href="https://glassboxmedicine.com/2019/02/17/measuring-performance-the-confusion-matrix/">https://glassboxmedicine.com/2019/02/17/measuring-performance-the-confusion-matrix/</a></figcaption></figure><p>Confusion matrix is a matrix showing where the model got confused.</p><p>To better understand these terms, let’s use a medical model.</p><p>· <strong>True positive is when the patient is sick and the model predicts him to be sick</strong></p><p><strong>· False positive is when patient is healthy but model predicts him to be sick</strong></p><p><strong>· False negative is when patient is sick but model predicts him to be healthy</strong></p><p><strong>· True negative is when patient is healthy and model predicts him to be healthy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*_jiWxAjVPlzGtEM0L9Q3aA.png" /><figcaption>Confusion matrix example</figcaption></figure><p>This is a confusion matrix of a spam classifying model. Essentially the principal diagonal is the area where the model is not confused and returns accurate results. All other squares are where model returned inaccurate results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*kJTRQTMCuUp7hMX1HepcpA.png" /></figure><p>This is a confusion matrix for three possible illnesses A, B and C. Instead of the number of each type of classification, it indicates the probability of being classified into each type. Each row adds up to 1. Again, squares other than those in the principal diagonal indicate where the model was confused.</p><p>We’ll try to understand the next metrics in terms of the confusion matrix.</p><h3>Accuracy</h3><p><strong>It is essentially (number of data points properly classified) over the (total number of data points)</strong>. It is also the number of points in the principal diagonal of the confusion matrix over the total number of points.</p><p>Accuracy fails when number of data points in question is very high. For example, in a tax evasion prediction model, suppose there are 300 tax evaders out of 30,000 candidates. And our model predicts all of them clean. Even then the model has an accuracy of ((30000–300)/(30000))*100= 99%! But our model is terrible right? As even a single evader may cause the government a loss of millions!</p><h3>Precision and Recall</h3><p>Precision answers the question, out of all people diagnosed sick, how many were actually sick.</p><p>Recall (or sensitivity) answers the question, out of all people actually sick, how many did we diagnose as sick.</p><p>This is the simplest way to put it in terms of a medical model. Let’s now look at the formulae.</p><p>[Note: Before proceeding, please revise the abbreviations like FN, TP etc. from the first image]</p><p><strong>Precision= TP/TP+FP</strong></p><p><strong>Recall=TP/TP+FN</strong></p><p>If we want a smaller number of false negatives, we focus on recall. This is essential for medical models where we do not want to classify a sick patient as healthy!</p><p>On the other hand, a smaller number of false positives is guaranteed by precision. This is important for let’s say a spam classifier, where we do not want important messages to be classified as spam!</p><p>It is interesting to note that precision and recall have an antagonizing effect on one another. Let’s say we want to predict whether a passenger in an airplane is a terrorist or not. If we classify all passengers as terrorists, we would have a recall of 1 (no false negatives) but we have to put a bar on literally all the passengers! Conversely, if we classify all of them as non-terrorists, we have a precision of 1, but risk lives of many others. A proper balance is essential.</p><p>This is where F-beta score comes in.</p><h3>F-beta score-</h3><p>A larger beta places greater emphasis on recall. This is because with an increased beta, weightage of precision in the denominator increases which decreases its overall effect. Conversely, a smaller beta places greater emphasis on precision.</p><p>As an example, we may want a larger beta value in a video recommendation system as we don’t want to miss out suggesting a video to a user. A smaller beta value may be crucial for a company implementing a model to send sample products to prospective users. A large number of false positives may lead to spending on the wrong person!</p><p>Its most famous form is the <strong>F-1 score</strong> which is the harmonic mean between the precision and recall laying equal weightage on both.</p><p><strong>F-1 score= (2*precision*recall)/(precision+recall)</strong></p><h3><strong>Sensitivity and Specificity</strong></h3><p><strong>Sensitivity is the exact same thing as recall</strong>.</p><p>Specificity answers the question, out of all people we diagnosed healthy, how many were actually healthy.</p><p><strong>Specificity= TN/TN+FP</strong></p><p>If we want lesser number of false positives we focus on specificity.</p><p>We plot all the above metrics in confusion matrix terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*2LW4vQbu4ZrHVsXPg9nPrw.png" /><figcaption>Sensitivity and specificity in a confusion matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Y9ypfZ9qCJ_gRoiC_7lziQ.png" /><figcaption>Precision and Recall in a confusion matrix</figcaption></figure><p>Each row and column of the confusion matrix implies some metric. This is why the confusion matrix is so important!</p><h3>ROC Curve-</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*ENIhT7HSpoSuv94Y.png" /><figcaption>ROC Curves for three models. Note that the straight line implies a random model</figcaption></figure><p><strong>ROC (Receiver Operator Characteristics) is a curve plotting True Positive Rate against False Positive Rate.</strong></p><p>True positive rate is surprisingly same as recall.</p><p><strong>TPR= no. of points correctly classified as positive/total no. of points actually positive= TP/TP+FN</strong></p><p>Similarly,</p><p><strong>False positive rate (FPR)= no. of points incorrectly classified as positive/total no. of points actually negative= FP/FP+TN</strong></p><p>Instinctively, we can imagine we want a model which gives a high TPR but low FPR. Hence, our curve should be as much close to covering the entire graph as possible. In more technical terms, the Area Under Curve (AUC) should be as high as possible.</p><p>Now, how do we know the points to plot this curve?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Ug8n1CV82197KPJXUVxNvw.png" /></figure><p>Imagine our model has classified points like this. Points to the left of the split are classified negative while those right are positive. Its FPR is 2/2+5= 0.286. There are 2 red points(negative) classified as positive out of 7 total red point. Its TPR is 5/5+2=0.857. 5 actually positive points have been classified as positive out of 7 total positive points. Hence the point is plotted as (0.286,0.857) on the curve. Similarly, we plot the points at various splits resulting in the ultimate ROC curve.</p><p>A split at the absolute left classifies everything as positive hence FPR=TPR=1 and split at the extreme right has FPR=TPR=0 as nothing is classified as positive.</p><p>Now, let’s take a look at a perfect split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*FHvLkDEdnfw_PRwTkmuwgw.png" /></figure><p>All splits at the left of mid-mark classify all positive points correctly as true positive resulting in TPR=1 but false positives occur too. All splits at the right of mid-mark have no false positives resulting in FPR=0 but false negatives occur. What we get if we plot all the points is a perfect square with unit area as the ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*cMtamsJ5wljVesByyV0SpQ.png" /><figcaption>Curve ‘A’ is the perfect model (unit square), curve B is the good model, while curve ‘C’ is a random model</figcaption></figure><p>Since this is an unattainable model, our model should aim at maximizing AUC towards 1.</p><p>The above diagram shows sensitivity and (1-specificity) instead of TPR and FPR on the axes. Recall that TPR is the same as sensitivity. FPR= FP/FP+TN while specificity=TN/TN+FP. Hence, 1-specificity is same as FPR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*WEB2JPvr3tgYhvuCO5K97g.png" /></figure><p>This is another form of ROC curve with specificity and sensitivity on the axes. Rotate the axes anti-clockwise by one quadrant to transform it into our standard ROC curve.</p><p>Hope you liked my article and it helped you!</p><p><strong>The above content is created using what I learned from Udacity and various other platforms. Some images’ rights lie solely under Udacity License and are not permitted to be used in return of money.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c4f95b3b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>