<?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 Vishnu vardhan Varapalli on Medium]]></title>
        <description><![CDATA[Stories by Vishnu vardhan Varapalli on Medium]]></description>
        <link>https://medium.com/@iamvishnu-varapally?source=rss-e3f6e359f240------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9C_VnBrIRW49Ri9UR-rzbg.jpeg</url>
            <title>Stories by Vishnu vardhan Varapalli on Medium</title>
            <link>https://medium.com/@iamvishnu-varapally?source=rss-e3f6e359f240------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:09:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamvishnu-varapally/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[How We Built a High-Availability, Zero-Cost AI Workspace: The Strategy]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iamvishnu-varapally.medium.com/how-we-built-a-high-availability-zero-cost-ai-workspace-the-strategy-631bb363b057?source=rss-e3f6e359f240------2"><img src="https://cdn-images-1.medium.com/max/1020/1*ZrxtSJn0Y0nE7-OnoCZghw.png" width="1020"></a></p><p class="medium-feed-snippet">In the world of Generative AI, developers and power users face a constant trade-off: pay premium prices for reliable closed models, or&#x2026;</p><p class="medium-feed-link"><a href="https://iamvishnu-varapally.medium.com/how-we-built-a-high-availability-zero-cost-ai-workspace-the-strategy-631bb363b057?source=rss-e3f6e359f240------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iamvishnu-varapally.medium.com/how-we-built-a-high-availability-zero-cost-ai-workspace-the-strategy-631bb363b057?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/631bb363b057</guid>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 18:42:43 GMT</pubDate>
            <atom:updated>2026-06-22T18:42:43.778Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Russian Doll of Tech: Unpacking AI, Machine Learning, and Deep Learning]]></title>
            <link>https://iamvishnu-varapally.medium.com/the-russian-doll-of-tech-unpacking-ai-machine-learning-and-deep-learning-da1600596f16?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/da1600596f16</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[macine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 16:17:40 GMT</pubDate>
            <atom:updated>2025-12-06T16:17:40.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*9rwXhgU2w1iyOE4H.jpg" /><figcaption>Russion doll perspective of evolution of AI</figcaption></figure><p><strong>Finally, understanding the buzzwords that are reshaping our reality.</strong></p><p>We live in an era where your phone knows what you want to type before you do, your car can spot pedestrians in the dark, and a website can generate a Renaissance-style painting of your cat in seconds.</p><p>Yet, if you ask three different people to explain how this works, you’ll get three different answers. One will say it’s “Artificial Intelligence.” Another will correct them and say, “No, that’s actually Machine Learning.” A third might push up their glasses and whisper, “It’s actually a Transformer model based on Deep Learning principles.”</p><p>Here is the secret: <strong>They are all right.</strong></p><p>The terminology of the future can be messy. We throw around acronyms like AI, ML, and DL as if they are interchangeable, but they aren’t. They are distinct, historical milestones in our quest to create a digital mind. Understanding the difference isn’t just semantics — it’s the key to understanding where technology is going next.</p><p>If you have ever felt too embarrassed to ask the difference between a “neural network” and a “standard algorithm,” you are in the right place. We are going to peel back the layers of this technology, not with complex math, but with a simple concept you already know: <strong>The Russian Nesting Doll.</strong></p><p>Let’s crack open the first shell.</p><h3>🪆 The Outer Shell: Artificial Intelligence (AI)</h3><p>Imagine the largest doll in the set. This is <strong>Artificial Intelligence</strong>.</p><p>AI is not a specific technology; it is a <strong>broad discipline</strong>. It is the umbrella term for any computer program that performs a task “smartly.” In the early days (think 1950s–1980s), this didn’t mean the computer was learning. It meant humans had given it a massive list of rules.</p><p>If you’ve ever played a video game against a computer opponent that gets stuck running into a wall, or used a customer service chatbot that can only answer “Yes” or “No,” you’ve interacted with AI. This is often called “Good Old-Fashioned AI” (GOFAI). It is rigid. If the human programmer didn’t write a rule for a specific situation, the AI breaks.</p><ul><li><strong>The Definition:</strong> Any technique that enables computers to mimic human intelligence, using logic, if-then rules, or decision trees.</li><li><strong>The Classic Example:</strong> <strong>Deep Blue (1997)</strong>. The IBM computer that beat chess champion Garry Kasparov didn’t “learn” chess by watching humans; it used raw brute force to calculate millions of possible moves ahead based on rules humans taught it.</li></ul><h3>🪆 The Middle Shell: Machine Learning (ML)</h3><p>Now, open the big AI doll. Inside, you find a smaller, more specialized doll: <strong>Machine Learning</strong>.</p><p>By the 1980s and 90s, computer scientists realized they couldn’t write a rule for everything. You can’t write an “if-then” rule to recognize a cat, because cats come in infinite shapes, sizes, and angles.</p><p>Instead of programming the <em>rules</em>, they decided to program the <em>system to learn the rules itself</em>.</p><p>In Machine Learning, you give the computer data — lots of it — and an algorithm (a mathematical recipe). The computer analyzes the data, finds statistical patterns, and improves over time.</p><ul><li><strong>The Definition:</strong> A subset of AI where machines improve at tasks with experience (data).</li><li><strong>The Real-World Example:</strong> <strong>Your Email Spam Filter</strong>. Nobody wrote a rule saying, “If the email contains the words ‘Prince’ and ‘Bank Account’, delete it.” Instead, the filter looked at millions of emails marked as “spam” by users and statistically realized that those words often appear together in junk mail.</li><li><strong>Another Example:</strong> <strong>Netflix Recommendations</strong>. “Because you watched <em>Vampire Diaries</em>, you might like <em>The Originals</em>.” It’s not magic; it’s statistics.</li></ul><h3>🪆 The Inner Shell: Deep Learning (DL)</h3><p>Finally, open the Machine Learning doll. Inside sits the smallest, most intricate doll: <strong>Deep Learning</strong>.</p><p>This is where things get sci-fi. Deep Learning is a specialized type of Machine Learning inspired by the biological structure of the human brain. It uses <strong>Artificial Neural Networks</strong> — layers upon layers of digital “neurons” connected together.</p><p>While standard Machine Learning usually needs a human to tell it what to look for (e.g., “look for the color red to identify a strawberry”), Deep Learning figures out the features itself. You just throw a million images of strawberries at it, and it learns to identify edges, then textures, then shapes, and finally, the fruit.</p><ul><li><strong>The Definition:</strong> A subset of ML that uses multi-layered neural networks to solve vast, complex problems like perception (seeing and hearing).</li><li><strong>The Real-World Example:</strong> <strong>Self-Driving Cars</strong>. A Tesla doesn’t just follow GPS; it uses Deep Learning to “see” a stop sign, distinguish a plastic bag from a rock, and predict what a cyclist will do next.</li><li><strong>The Big Breakthrough:</strong> <strong>ChatGPT and Generative AI</strong>. These are massive Deep Learning models (LLMs) that have “read” the entire internet to learn the patterns of human language.</li></ul><h3>⏳ A Brief History of Intelligence</h3><p>To understand why we are talking about this <em>now</em>, you have to look at the timeline.</p><ul><li><strong>1950s (The Birth):</strong> Alan Turing asks, “Can machines think?”[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQH6z8ZCXCdE31iIOhuySw8Va--BhVeSnsCw9P4MoKszd9vHb913EJ5RiPZbPuE1wSv4uTFy7ZksanLq-EuEFcl_LcwwHks2Ced0vYo8XMeUKZMwle0mnmODr169R3B9oQes8sMqFC0u4lG-xOAV-eYcWiNdfWG3mX-ByfWNTLHH_dkTl9IEK-Fi0mvWvur2F-Y5YOcXxmE4EGqN_HsKSJsI_Lue_exubjM6zh3SYhtnrODc">8</a>] The term “Artificial Intelligence” was coined at the Dartmouth Conference in 1956.[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQEW6DqfEoV2Iz_e_s2HU07LUPnlh3h0uYVvtX4zeFogQN8b-Sv4dFwUUvYF_ROeNDB_37UjabH5XC4nq6jQwzPtrmjzh21czbJWNbd91ifGVbfzHHpjr88APteX9cunyggiZWLQIT5NRtjUBP_j0UvdXsDgFKhnTeYdSxEypoYl-RKCuMI2CvnQSDfGwM54dJp8ZU-XxKLnUkzInyZN3mL1TAPEx5Jvtcd7G3gMYYzUoqM2vF5fXFtTyCqw1Q%3D%3D">7</a>] Optimism is high.</li><li><strong>1970s (The Winter):</strong> The hype dies. Computers are too slow and expensive. Funding dries up. This is known as the “AI Winter.”</li><li><strong>1990s-2000s ( The ML Rise):</strong> Computers get faster. Companies like Google and Amazon start using Machine Learning for search engines and product recommendations.</li><li><strong>2012 (The Big Bang):</strong> A Deep Learning model called <strong>AlexNet</strong> crushes the competition in an image recognition contest. It proves that Neural Networks are the future.</li><li><strong>2020s (The Era of Generative AI):</strong> We have enough data and computing power to build models that can write poetry, code apps, and pass the Bar Exam.</li></ul><h3>🚀 The “So What?”: Why the Explosion Now?</h3><p>If the math behind Deep Learning (Neural Networks) was invented in the 1980s, why did it take until now to take over the world?</p><p>It comes down to a perfect storm of three things:</p><ol><li><strong>Big Data:</strong> We needed the Internet (social media, YouTube, Wikipedia) to create the massive datasets required to train these hungry models.</li><li><strong>GPUs (Hardware):</strong> It turns out that Graphics Processing Units (the chips used for video gaming) are incredibly good at the math needed for Deep Learning.</li><li><strong>Better Algorithms:</strong> Researchers finally figured out how to stack these neural layers deep enough without the system crashing (hence, “Deep” Learning).</li></ol><h3>Summary: The Cheat Sheet</h3><ul><li><strong>AI</strong> is the car. (The broad concept).</li><li><strong>Machine Learning</strong> is the engine. (The mechanism that makes it run).</li><li><strong>Deep Learning</strong> is the turbocharger. (The specialized tech that makes it incredibly powerful).</li></ul><p>We are currently living through the “Deep Learning” revolution. But remember, it’s all still just the Russian Doll — layers of math and logic, nested inside each other, trying to understand our world.</p><p>You don’t have to wait for part 2. The next step would be a deep understanding of each term(AI, machine learning, deep learning). You can see the blogs at <a href="https://iamvishnu-varapally.medium.com/">https://iamvishnu-varapally.medium.com/</a> to understand, which are currently focused on machine learning.</p><p>Happy Learning ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da1600596f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNIX 101: What Every Beginner Should Know Before Starting Their Career]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iamvishnu-varapally.medium.com/unix-101-what-every-beginner-should-know-before-starting-their-career-d6de046b4bd4?source=rss-e3f6e359f240------2"><img src="https://cdn-images-1.medium.com/max/2500/1*z0lfIgEH6JqXi9Cg2v-Jkw.png" width="2500"></a></p><p class="medium-feed-snippet">A beginner&#x2019;s guide to understanding UNIX, its roots, and why it still powers the modern world.</p><p class="medium-feed-link"><a href="https://iamvishnu-varapally.medium.com/unix-101-what-every-beginner-should-know-before-starting-their-career-d6de046b4bd4?source=rss-e3f6e359f240------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iamvishnu-varapally.medium.com/unix-101-what-every-beginner-should-know-before-starting-their-career-d6de046b4bd4?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6de046b4bd4</guid>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[techcareergrowth]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 14:22:20 GMT</pubDate>
            <atom:updated>2025-10-27T14:22:20.065Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[When One Model Isn’t Enough: Ensemble Learning Techniques Demystified]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iamvishnu-varapally.medium.com/when-one-model-isnt-enough-ensemble-learning-techniques-demystified-385abfe5e5ac?source=rss-e3f6e359f240------2"><img src="https://cdn-images-1.medium.com/max/1194/1*OM863_lLVbL9fdAosqBwcg.png" width="1194"></a></p><p class="medium-feed-snippet">If you&#x2019;ve ever built a machine learning model, you probably know the frustration: sometimes it works great, other times it struggles.</p><p class="medium-feed-link"><a href="https://iamvishnu-varapally.medium.com/when-one-model-isnt-enough-ensemble-learning-techniques-demystified-385abfe5e5ac?source=rss-e3f6e359f240------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iamvishnu-varapally.medium.com/when-one-model-isnt-enough-ensemble-learning-techniques-demystified-385abfe5e5ac?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/385abfe5e5ac</guid>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 14:04:00 GMT</pubDate>
            <atom:updated>2025-10-27T14:04:00.481Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Evaluating metrics for Multi-label Classification and Implementations]]></title>
            <link>https://medium.com/analytics-vidhya/evaluating-metrics-for-multi-label-classification-and-implementations-ebabead60afd?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebabead60afd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[multilabel-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Sun, 22 May 2022 03:09:57 GMT</pubDate>
            <atom:updated>2025-09-25T15:22:52.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*FL6eTAxBeAMsdejy.jpg" /></figure><p>This article is the continuation of <a href="https://medium.com/geekculture/evaluating-metrics-for-multi-class-classification-and-implementations-be389cb17e65?source=your_stories_page-------------------------------------"><em>this</em></a> post.</p><p>First, let’s learn about what is Multi-label classification. Multi-label classification is nothing but, having many No. of labels for one sample of data in training data.</p><p>Example: Let’s suppose in a Picture, we have a ball, pen, and bat at the same time, the classification problem is, whether these 3 items are there in the input picture are not. This means, that instead of 1 label( as in previous types of classification), we have 3 labels for one data sample.</p><p>we can produce multi-label classification data temporarily for now, with the help of the below code. I would suggest you to make it out from a data source.</p><pre>X,y = make_multilabel_classification(sparse = False, n_samples = 100, n_labels = 4, allow_unlabeled = False)</pre><p>Now, I’m gonna explain the model building and different approaches of model building for multi-label classification, as it’s different from the traditional model building like in binary(or) multi-label classification. If you want to go to metrics, you can skip this section.</p><p>There are 3 ways we can build a model for multi-label classification problem</p><ol><li>Problem Transformation</li><li>Adapted Algorithm</li><li>Ensemble Approaches</li></ol><p>Let’s explore every way…</p><ol><li><strong>Problem Transformation</strong>: This can be carried out in 3 ways</li></ol><p>a. Binary relevance</p><p>b. Classifier Chains</p><p>c. Label powerset</p><p>Let’s think, we have input data X, and label data [y1, y2, y3, y4]</p><p>A. Binary Relevance: In Binary Relevance, multi-label classification will get turned into single-class classification.</p><p>Converting into single-class classification, pairs will be formed like(X, y1),(X, y2),(X, y3), and (X, y4).</p><p>Now, the model will consider every pair, and train with X and yi.</p><p>so 4 outputs will be generated.</p><pre>from sklearn.datasets import make_multilabel_classification<br>from skmultilearn.problem_transform import BinaryRelevance, ClassifierChain, LabelPowerset<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn import metrics<br>from scipy import sparse</pre><pre>X,y = make_multilabel_classification(sparse = False, n_samples = 100, n_labels = 4, allow_unlabeled = False)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2)</pre><pre>tree_model = DecisionTreeClassifier()</pre><pre>meta_model = BinaryRelevance(tree_model)</pre><pre>meta_model.fit(X_train,y_train)</pre><pre>predictions = meta_model.predict(X_test)<br>print(metrics.accuracy_score(y_test, predictions))</pre><p>B. Classifier Chains</p><p>Here, training is gonna be like,</p><p>(input) — — (output)</p><p>X — — — y1</p><p>X, y1 — — y2</p><p>X, y1, y2 — — — y3</p><p>X, y1, y2, y3 — — — y4</p><p>So, 4 outputs will be produced…</p><p>code snippet:</p><pre>from sklearn.datasets import make_multilabel_classification<br>from skmultilearn.problem_transform import BinaryRelevance, ClassifierChain, LabelPowerset<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn import metrics<br>from scipy import sparse</pre><pre>X,y = make_multilabel_classification(sparse = False, n_samples = 100, n_labels = 4, allow_unlabeled = False)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2)</pre><pre>tree_model = DecisionTreeClassifier()</pre><pre>meta_model = ClassifierChain(tree_model)</pre><pre>meta_model.fit(X_train,y_train)</pre><pre>predictions = meta_model.predict(X_test)<br>print(metrics.accuracy_score(y_test, predictions))</pre><p>C. Label Powerset: Here, for No. of samples of data we have, a number will be assigned to the different combinations of sets of labels. for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*B0pLZqYi8yoEyGc-5wUJ6Q.png" /></figure><p>in the above 6 data samples, as we can see,x1 and x4 have the same set of labels and, x3 and x6 have the same set of labels. so we can create a new column in the dataset, assign numbers like below, and remove the remaining set of labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*io7qcDvGsk-kdHVfDjmY5w.png" /></figure><p>Now, the problem turned into multi-class classification, so we know the traditional way of building a model. right?</p><p>Now, Adapted algorithms are nothing but algorithms specifically designed for the multi-label classification itself. you can get the implementation code from algorithms GitHub(I&#39;m gonna provide the links).</p><p>Ensemble Approaches are the same as the traditional ensemble approaches and you can understand them easily(I’m not going to detail, cuz this article focuses on metrics only). the below links gonna definitely help you.</p><p>Links:</p><ol><li><a href="http://scikit.ml/api/skmultilearn.html">http://scikit.ml/api/skmultilearn.html</a></li><li><a href="https://github.com/scikit-multilearn/scikit-multilearn/blob/master/skmultilearn/adapt/mlknn.py">https://github.com/scikit-multilearn/scikit-multilearn/blob/master/skmultilearn/adapt/mlknn.py</a></li></ol><p>Go through the GitHub implementations of scikit-multilearn, so that you’ll understand the code too.</p><p>Now, let’s jump into metrics.</p><p>Now, coming to metrics,</p><p>As I always say, we can decide the performance in different ways, like using the predefined and existing metrics and designing our own metrics according to our problem.</p><p>Here, I’m gonna give some existing metrics for Multi-label classification with code.</p><p>The Metrics we are gonna discuss are,</p><ol><li>Precision @ K.</li><li>Average Precision @ K.</li><li>Mean Average Precision @ K.</li><li>Sampled F1-Score.</li></ol><p><strong>Precision @ K:</strong></p><pre>ydef patk(actual, pred, k):<br> if k == 0:<br>  return 0<br> k_pred = pred[:k]</pre><pre> actual_set = set(actual)</pre><pre> pred_set = set(k_pred)</pre><pre> common_values = actual_set.intersection(pred_set)</pre><pre> return len(common_values)/len(pred[:k])</pre><pre>y_true = [1 ,2, 0]<br>y_pred = [1, 1, 0]</pre><pre>if __name__ == &quot;__main__&quot;:<br>    print(patk(y_true, y_pred,3))</pre><p>Don’t get confused with the definition of precision we discussed earlier, with this precision in precision @k. According to my previous blogs, precision is nothing but “how much accurately +ve values got predicted in Actual +ve values”. but here, precision is <strong>“how much(or many) correctly, every prediction is made”</strong>(you’re gonna understand this with the below example). So, <strong>Precision @ K is nothing but, evaluating how correctly, a prediction is made consider only the top K elements in the list of elements of the label for a particular sample</strong>.</p><p>In the above code, we considered value 3 for K, and the length of y_true, y_pred is also 3, so we are considering all the elements in the label.</p><p>In Precision @ K, we are calculating precision for only one sample, think of it like there is a photo, which has Bat, a ball, and a pen, let’s assign it a value like Bat=1, ball=2, pen = 0.</p><p>So now, in the above code, given y_true = [1 ,2, 0], and y_pred = [1, 1, 0].This means, actually in the photo, a ball, bat, and pen are there, but according to our model, 2 bats and a pen is there.</p><p>now as we can see, 2 out of 3 elements are correct, so 66.666% of the prediction is correctly made, so precision @ K will be 0.6666666.</p><p>Normally, we can use precision @ K, for one sample.</p><p><strong>Note: </strong>Normally, we use mean average precision @ k, as it represents the optimal accuracy of the overall data. both( precision @k, average precision @k ) will lead to mean average precision @ K. I’m just explaining this(precision, average precision), so that we know what are the components(precision, average precision), of mean average precision.</p><p><strong>Mean Average @ K:</strong></p><p>Now, here we are gonna work with N no. of samples with N&gt;1,</p><p>Consider the following data:</p><p>y_true = [[1,2,0,1], [0,4], [3], [1,2]] # here we have 4 labels</p><p>y_pred = [[1,1,0,1], [1,4], [2], [1,3]]</p><p>Now, here we calculate precision for every label(set of elements), for different values of K(from 0 to K), and average all those precisions, called Average Precision @ K.</p><pre>import numpy as np</pre><pre>def patk(actual, pred, k):<br> if k == 0:<br>  return 0</pre><pre>k_pred = pred[:k]</pre><pre>actual_set = set(actual)</pre><pre>pred_set = set(k_pred)</pre><pre>common_values = actual_set.intersection(pred_set)</pre><pre>return len(common_values)/len(pred[:k])<br> <br>def apatk(acutal, pred, k):</pre><pre>precision_ = []<br> for i in range(1, k+1):</pre><pre>precision_.append(patk(acutal, pred, i))</pre><pre>if len(precision_) == 0:<br>  return 0</pre><pre>return np.mean(precision_)</pre><pre>y_true = [[1,2,0,1], [0,4], [3], [1,2]]<br>y_pred = [[1,1,0,1], [1,4], [2], [1,3]]</pre><pre>if __name__ == &quot;__main__&quot;:<br> for i in range(len(y_true)):<br>  for j in range(1, 4):<br>   print(&quot;for K = &quot;+str(j)+&quot;average precision is &quot;+str(apatk(y_true[i], y_pred[i], k=j)))</pre><p><strong>Mean Average Precision @ K:</strong></p><p>Mean Average Precision @ K is nothing but, we are averaging the average precisions of every label, which represents the accurate metric for the real data.</p><pre>import numpy as np</pre><pre>def patk(actual, pred, k):<br> if k == 0:<br>  return 0</pre><pre>k_pred = pred[:k]</pre><pre>actual_set = set(actual)</pre><pre>pred_set = set(k_pred)</pre><pre>common_values = actual_set.intersection(pred_set)</pre><pre>return len(common_values)/len(pred[:k])<br> <br>def apatk(acutal, pred, k):</pre><pre>precision_ = []<br> for i in range(1, k+1):</pre><pre>precision_.append(patk(acutal, pred, i))</pre><pre>if len(precision_) == 0:<br>  return 0</pre><pre>return np.mean(precision_)</pre><pre>y_true = [[1,2,0,1], [0,4], [3], [1,2]]<br>y_pred = [[1,1,0,1], [1,4], [2], [1,3]]</pre><pre>def mapk(acutal, pred, k):</pre><pre>#creating a list for storing the Average Precision Values<br> average_precision = []<br> #interating through the whole data and calculating the apk for each <br> for i in range(len(acutal)):<br>  average_precision.append(apatk(acutal[i], pred[i], k))</pre><pre>#returning the mean of all the data<br> return np.mean(average_precision)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    print(mapk(y_true, y_pred,3))</pre><p>Here, most of my code is from different resources, as implementation is gonna be the same for existing metrics.</p><p><strong>Log Loss:</strong></p><p>Here, what we can do is, binarize every element in the labels of the whole dataset, create different binary columns, calculate the log loss for every column, and average them to get the average log loss.</p><p>This is also known as <strong>Mean Column-wise log loss</strong>. we can implement that easily. If you want implementation, go through my GitHub <a href="https://github.com/VishnuVardhanVarapalli/Classification-Metrics">here</a>.</p><p><strong>F1-score:</strong></p><p>F1-score is also the same as the log loss, after binarizing the columns, apply the f1_score metric to it(or as I said for log loss, calculate and average f1_score for binary column labels, anyway result is going to be the same).</p><pre>from sklearn.metrics import f1_score</pre><pre>from sklearn.preprocessing import MultiLabelBinarizer</pre><pre>def f1_sampled(actual, pred):</pre><pre>   mlb = MultiLabelBinarizer()</pre><pre>   actual = mlb.fit_transform(actual)</pre><pre>   pred = mlb.fit_transform(pred)</pre><pre>   f1 = f1_score(actual, pred, average = &quot;samples&quot;)</pre><pre>   return f1</pre><pre>y_true = [[1,2,0,1], [0,4], [3], [1,2]]</pre><pre>y_pred = [[1,1,0,1], [1,4], [2], [1,3]]</pre><pre>if __name__ == &quot;__main__&quot;:</pre><pre>   print(f1_sampled(y_true, y_pred))</pre><p>Now, you can confidently say, “<strong>I know multi-label classification metrics😊”</strong></p><p><strong>Conclusion:</strong></p><ol><li>Instead of Precision, Average Precision, and Mean Average Precision @ K, We can apply to Mean Average Precision @ K, to know the accuracy of the whole data. Apply remaining metrics according to the requirement.</li><li>With this Article, Classification metrics are completed. My next topic will depend on what readers want.</li></ol><p>___________________________________________________________________</p><p>You guys can ping me your fav topic on <a href="https://in.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150">LinkedIn</a>, and follow my <a href="https://github.com/VishnuVardhanVarapalli">GitHub</a> here.</p><p>Follow me on Medium:- <a href="https://iamvishnu-varapally.medium.com/">https://iamvishnu-varapally.medium.com/</a></p><p>Happy Learning✌!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebabead60afd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/evaluating-metrics-for-multi-label-classification-and-implementations-ebabead60afd">Evaluating metrics for Multi-label Classification and Implementations</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[Evaluating Metrics for Multi-class Classification and Implementations]]></title>
            <link>https://medium.com/geekculture/evaluating-metrics-for-multi-class-classification-and-implementations-be389cb17e65?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/be389cb17e65</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 09:15:23 GMT</pubDate>
            <atom:updated>2022-02-21T06:00:01.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gCxPWQCSIp90cGyH.jpg" /><figcaption>Image from Google</figcaption></figure><p>This blog is a continuation of <a href="https://medium.com/analytics-vidhya/evaluating-metrics-for-classification-machine-learning-models-learners-at-medium-level-c956a8b8d889">this post</a>.</p><p>Till now, you went through the Binary Classification metrics. from now, we are gonna learn the metrics for Multi-class classification and in the next article, you’re gonna learn Multi-label classification and its metrics.</p><p>Multi-class Classification is nothing but solving a classification problem where we have Multiple classes( No. of classes &gt; 2) in the target column. For example, Classification of fruit images into Apples, oranges, and bananas.</p><p>I’m attaching an example dataset <a href="https://github.com/VishnuVardhanVarapalli/Classification-Metrics/blob/main/Development%20Index.csv">here</a>. In this dataset, Development Index column is the target which has Multiple classes( No. of classes &gt; 2).</p><p>As we learned the metrics in binary classification metrics, with them, we can make the multi-classification metrics.</p><p>There are 3 implementations of every binary classification metric in multi-classification metrics. you may understand when I write them…</p><p>For precision binary classification metric, in Multi-classification metrics, we have three versions,</p><ol><li>Micro averaged precision</li><li>Macro averaged precision</li><li>Weighted precision</li></ol><p>as precision, we have 3 versions of the recall binary classification metric in Multi-class classification.</p><ol><li>Micro averaged recall</li><li>Macro averaged recall</li><li>Weighted recall</li></ol><p>Like above, we can classify every binary classification metric as 3 versions and name them as multi-classification metrics.</p><p>For now, I’m gonna discuss precision and add the code of recall and all the remaining metrics gonna get built in the same way( same procedure followed for precision below). In the future post, I’m gonna show you how you can form ROC-AUC, in multi-class classification.</p><p>Note:- Don’t jump into anything, unless you know the basics. because it may eat your confidence and faith.</p><p>Let’s discuss the 3 versions of precision….</p><ol><li><strong>Micro averaged precision:- </strong>Here, first, we’re gonna find all the True positives for all of the classes and sum them to get total true positives from all classes. after that, we’re gonna find all the False positives for all of the classes and sum them to get total False positives from all classes. Now, calculate the precision for the total true positives and false positives.</li></ol><p>2. <strong>Macro averaged precision</strong>:- Here, we are gonna find the precisions for different classes in the target column, and then average them to get the final precision.</p><p>3. <strong>Weighted precision</strong>:- Here, weighted precision is the same as Macro averaged precision, but the difference is Here, it depends and weighs based on the No of samples present in each class.</p><p>I know, I’ve given small definitions for each one, But that’s the definitions and code explains everything. So, check the definition and look at the required code for definition and know what’s happening in code, you’ll understand the things.</p><p>Keep in mind that, when the data is balanced, we can use the Macro version, but when data is imbalanced Micro and weighted versions are preferable.</p><p>Note that, the below code consists of all the 3 versions of precision.</p><pre>import pandas<br>import argparse<br>import numpy<br>from collections import Counter</pre><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn import metrics</pre><pre>#there are 3 Types of precision in case of Multi-class classification. <br>#1. Macro averaged precision<br>#2. Micro averaged precision<br>#3. Weighted precision</pre><pre>def true_positive(y_true, y_pred):<br>    tp = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 1 and yp == 1:<br>            tp += 1<br>    return tp<br>    <br>def true_negative(y_true, y_pred):<br>    tn = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 0 and yp == 0:<br>            tn += 1<br>    return tn<br>    <br>def false_positive(y_true, y_pred):<br>    fp = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 0 and yp == 1:<br>            fp += 1<br>    return fp<br>    <br>def false_negative(y_true, y_pred):<br>    fn = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 1 and yp == 0:<br>            fn += 1<br>    return fn</pre><pre>def precision(y_test, y_pred):<br>    tp =true_positive(y_test, y_pred)<br>    fp = false_positive(y_test, y_pred)<br>    try:<br>        return(tp/(tp+fp))<br>    except ZeroDivisionError:<br>        return 0</pre><pre>def Macro_averaged_precision(y_test, predictions):<br>    precisions = []<br>    for i in range(1,5):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]<br>        print(temp_ypred)<br>        print(temp_ytest)<br>        prec = precision(temp_ytest, temp_ypred)<br>        precisions.append(prec)<br>    <br>    return (sum(precisions)/len(precisions))<br>         <br>def Micro_averaged_precision(y_test, predictions):<br>    tp = 0<br>    fp = 0<br>    for i in range(1,5):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]</pre><pre>        tp += true_positive(temp_ytest, temp_ypred)<br>        fp += false_positive(temp_ytest, temp_ypred)</pre><pre>    precisions = tp / (tp + fp)</pre><pre>    return precisions</pre><pre>def weighted_precision(y_test, predictions):<br>    num_classes = len(numpy.unique(y_test))<br>    #coutns for every class<br>    precision = 0<br>    for i in range(1, num_classes):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]</pre><pre>        tp = true_positive(temp_ytest, temp_ypred)<br>        fp = false_positive(temp_ytest, temp_ypred)<br>        <br>        try:<br>            preai = tp / (tp+fp)<br>        except ZeroDivisionError:<br>            preai = 0</pre><pre>        weighted = preai*sum(temp_ytest)</pre><pre>        precision += weighted</pre><pre>    precision = precision/len(y_test)<br>    return precision</pre><pre>if __name__ == &quot;__main__&quot;:<br>    <br>    data = pandas.read_csv(&quot;C:\\Users\\iamvi\\OneDrive\\Desktop\\Metrics_in_Machine_Learning\\development-index\\Development Index.csv&quot;)<br>    <br>    train = data.drop([&#39;Development Index&#39;], axis = 1).values<br>    test = data[&quot;Development Index&quot;].values</pre><pre>model = LogisticRegression()</pre><pre>X_train, X_test, y_train, y_test = train_test_split(train, test, stratify = test)</pre><pre>model.fit(X_train, y_train)<br>    predictions = model.predict(X_test)</pre><pre>print(&quot;Macro precision is:&quot;, Macro_averaged_precision(y_test, predictions))<br>    print(&quot;Micro precision is:&quot;, Micro_averaged_precision(y_test, predictions))<br>    print(&quot;Weighted precision is:&quot;, weighted_precision(y_test, predictions))<br>    print(&quot;sklearn Macro&quot;, metrics.precision_score(y_test, predictions, average = &quot;macro&quot;))<br>    print(&quot;sklearn Micro&quot;, metrics.precision_score(y_test, predictions, average = &quot;micro&quot;))<br>    print(&quot;sklearn weighted&quot;, metrics.precision_score(y_test, predictions, average = &quot;weighted&quot;))</pre><p>You may find it difficult to see the code because of inconsistent indentations due to the medium interface, click <a href="https://github.com/VishnuVardhanVarapalli/Classification-Metrics/blob/main/Multi_class_classification_precision.py">here</a> to see the code in Github.</p><p>This is how all the multi-class classification metrics are produced from binary classification metrics.</p><p>As I said, I’m gonna give you the code for recall which resembles precision only, and all the remaining metrics too.</p><pre>import pandas<br>import argparse<br>import numpy<br>from collections import Counter</pre><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn import metrics</pre><pre>#there are 3 Types of recall in case of Multi-class classification. <br>#1. Macro averaged recall<br>#2. Micro averaged recall<br>#3. Weighted recall</pre><pre>def true_positive(y_true, y_pred):<br>    tp = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 1 and yp == 1:<br>            tp += 1<br>    return tp<br>    <br>def true_negative(y_true, y_pred):<br>    tn = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 0 and yp == 0:<br>            tn += 1<br>    return tn<br>    <br>def false_positive(y_true, y_pred):<br>    fp = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 0 and yp == 1:<br>            fp += 1<br>    return fp<br>    <br>def false_negative(y_true, y_pred):<br>    fn = 0<br>    for yt, yp in zip(y_true, y_pred):<br>        if yt == 1 and yp == 0:<br>            fn += 1<br>    return fn</pre><pre>def recall(y_test, y_pred):<br>    tp = true_positive(y_test, y_pred)<br>    fn = false_negative(y_test, y_pred)<br>    return(tp/(tp+fn))</pre><pre>def Macro_averaged_recall(y_test, predictions):<br>    recalls = []<br>    for i in range(1,5):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]<br>        print(temp_ypred)<br>        print(temp_ytest)<br>        rec = recall(temp_ytest, temp_ypred)<br>        recalls.append(rec)<br>    <br>    return (sum(recalls)/len(recalls))<br>         <br>def Micro_averaged_recall(y_test, predictions):<br>    tp = 0<br>    tn = 0<br>    for i in range(1,5):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]</pre><pre>        tp += true_positive(temp_ytest, temp_ypred)<br>        tn += true_negative(temp_ytest, temp_ypred)</pre><pre>    recall = tp / (tp + tn)</pre><pre>    return recall</pre><pre>def weighted_recall(y_test, predictions):<br>    num_classes = len(numpy.unique(y_test))<br>    #counts for every class<br>    recall = 0<br>    for i in range(1, num_classes):<br>        temp_ytest = [1 if x == i else 0 for x in y_test]<br>        temp_ypred = [1 if x == i else 0 for x in predictions]</pre><pre>tp = true_positive(temp_ytest, temp_ypred)<br>        tn = true_negative(temp_ytest, temp_ypred)<br>        <br>        try:<br>            rec = tp / (tp+tn)<br>        except ZeroDivisionError:<br>            rec = 0</pre><pre>weighted = rec*sum(temp_ytest)</pre><pre>recall += weighted</pre><pre>recall = recall/len(y_test)<br>    return recall</pre><pre>if __name__ == &quot;__main__&quot;:<br>    <br>    data = pandas.read_csv(&quot;C:\\Users\\iamvi\\OneDrive\\Desktop\\Metrics_in_Machine_Learning\\development-index\\Development Index.csv&quot;)<br>    <br>    train = data.drop([&#39;Development Index&#39;], axis = 1).values<br>    test = data[&quot;Development Index&quot;].values</pre><pre>model = LogisticRegression()</pre><pre>X_train, X_test, y_train, y_test = train_test_split(train, test, stratify = test)</pre><pre>model.fit(X_train, y_train)<br>    predictions = model.predict(X_test)</pre><pre>print(&quot;Macro recall is:&quot;, Macro_averaged_recall(y_test, predictions))<br>    print(&quot;Micro recall is:&quot;, Micro_averaged_recall(y_test, predictions))<br>    print(&quot;Weighted recall is:&quot;, weighted_recall(y_test, predictions))<br>    print(&quot;sklearn Macro&quot;, metrics.recall_score(y_test, predictions, average = &quot;macro&quot;))<br>    print(&quot;sklearn Micro&quot;, metrics.recall_score(y_test, predictions, average = &quot;micro&quot;))<br>    print(&quot;sklearn weighted&quot;, metrics.recall_score(y_test, predictions, average = &quot;weighted&quot;))</pre><p>The definitions of 3 versions of precision will be applied to recall too.</p><p>After you implemented all the multi-class classification metrics as I said above in 3 versions, you can confidently say “ I know Multi-class classification”.😉</p><p>Check the <a href="https://github.com/VishnuVardhanVarapalli/Classification-Metrics">Classification-Metrics Repository</a> to get all the codes of concepts I explained. As I’m writing articles here, GitHub is gonna get updated with codes. So, keep a fork on that.</p><p>If something you want to add here or want me to explain a missing concept here, lemme know from <a href="https://iamvishnuvarapally.wixsite.com/port-folio">here</a>.</p><p>you can follow me on different platforms <a href="https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/">LinkedIn</a>, <a href="https://github.com/VishnuVardhanVarapalli">Github</a>, and <a href="https://iamvishnu-varapally.medium.com/">medium</a>.</p><p>Happy Learning✌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be389cb17e65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/evaluating-metrics-for-multi-class-classification-and-implementations-be389cb17e65">Evaluating Metrics for Multi-class Classification and Implementations</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machines Deep Intuition PART-III (Kernels)]]></title>
            <link>https://iamvishnu-varapally.medium.com/support-vector-machines-deep-intuition-part-iii-kernels-ef946adf4122?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef946adf4122</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Sat, 30 Oct 2021 22:36:18 GMT</pubDate>
            <atom:updated>2021-10-30T22:36:18.265Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is the continuation of <a href="https://medium.com/analytics-vidhya/support-vector-machines-deep-intuition-part-i-basic-intuition-3b21d841210b">this</a> and <a href="https://iamvishnu-varapally.medium.com/support-vector-machines-deep-intuition-part-ii-math-690a55923945">this</a>. Please go through them before you read this post so that you can understand the below things.</p><p>For the people who already went through PART-I and PART-II, I updated that article due to the absence of a concept called Margins. please go through that( sorry for that 😅).</p><p>In a simple way to explain, SVMs kernels will try to change the dimension of the data from a lower dimension to a higher dimension(like looking a 2-D data in 3-Dimension) so that, Non-linear data in one dimension, looks linear in some other dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*ptIHUz2rq91GdqY-B3ZMhQ.png" /><figcaption>Like this</figcaption></figure><p>Don’t worry I’ll elaborate with an example.</p><p>Let’s consider you have data of 2 columns X1 and X2, with 2 classes in the output Label Y. If the data is non-linear when you plot the data like X1 on the X-axis, and X2 on the Y-axis(or vice-versa), then the data will look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*JZafQsZSj3nNDJhc_gq92A.png" /></figure><p>what we have now is 2 Dimension, i.e., we are looking at data in 2-D dimension, so now to increase the dimension, now we’ll add another column in the data X3 which will be equal to X1 * X2 (multiplication of X1 and X2).</p><p>Before this, we have only 2 features(2-Dimensional), now X3 is there, so now data dimension is increased, now we plot the data in 3- dimensions with X1 on X-axis, X2 on the y-axis, and X3 on the z-axis. I can’t plot that here, but as we increased the dimension from 2-D to 3-D, the data may be in linear form. looking at different dimensions means literally looking at the plot of the data in different n-axis directions, and in which direction the data looks linear, we’ll draw the hyperplane there, and we fix that hyperplane as the final hyperplane. To get the optimized hyperplane we need to see the data in different dimensions.</p><p>The thing that we did above is an example of applying a kernel in SVMs</p><p>kernel function <strong>K(X1, X2) = X1*X2. ……………………… (1)</strong></p><p>Kernels in SVMs are nothing but applying the different mathematical operations (different kernel functions) on the data and transforming that into another form for getting more dimensions, and deciding which hyperplane we need to select.</p><p>As like (1), we have different kernel functions in SVMs, which can apply to data for better results.</p><p>Some of them are:</p><ol><li>Polynomial kernels</li><li>RBF kernels</li><li>Sigmoid kernels</li></ol><p>I don’t want to explain what they are, the main aim of this article is to make understand what are kernels &amp; why we are learning them. start learning one by one on your own as each kernel just represent a math formula.</p><p>Now, it’s time for the implementation.</p><p>Before that, you need to know something.</p><p>Actually, when you surf through the internet about SVMs Implementation, you’ll come across 2 types of Implementation.</p><ol><li>LinearSVC</li><li>SVC</li></ol><p>The main difference between these 2 Implementation methods is, linear SVC is particularly developed for dealing with only linear data, whereas SVC is developed for dealing with non-linear data by applying different kernels.</p><p>Also with SVC, we can use the linear kernel, but as LinearSVC is designed particularly for Linear data, LinearSVC is far better than SVC in the case of linear data. Considering other differences, <a href="https://stackoverflow.com/questions/45384185/what-is-the-difference-between-linearsvc-and-svckernel-linear">Here</a> you’ll find calculating loss and other differences. (Have a look at it, as they are explained in simple terminology)</p><p>Below is the Implementation of SVM’s with LinearSVC() and SVC():-</p><pre>import pandas as pd</pre><pre>from sklearn.datasets import make_classification</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>from sklearn.svm import LinearSVC, SVC</pre><pre>from sklearn import metrics</pre><pre>X,y = make_classification(n_samples=200,n_features=10,random_state=20)</pre><pre>X_train,X_test,y_train,y_test = train_test_split(X,y,random_state = 43)</pre><pre>Model = LinearSVC()</pre><pre>Model.fit(X_train, y_train)</pre><pre>print(&quot;Model Trained&quot;)</pre><pre>predictions = Model.predict(X_test)</pre><pre>print(&quot;predictions made&quot;)</pre><pre>print(type(predictions[0]))</pre><pre>print(predictions[:5])</pre><pre>print(type(y_test[0]))</pre><pre>Model1 = SVC()</pre><pre>Model1.fit(X_train, y_train)</pre><pre>predictions1 = Model1.predict(X_test)</pre><pre>print(&quot;Linear SVC&#39;s accuracy is:&quot;+str(round(metrics.accuracy_score(y_test, predictions)*100, 2)))</pre><pre>print(&quot;SVC&#39;s accuracy is:&quot;+str(round(metrics.accuracy_score(y_test, predictions1)*100, 2)))</pre><p>yeahhhh…</p><p>I think I covered most of the SVM’s theory in 3 parts, still, if something you want to add here or want me to explain a missing concept here, lemme know it from <a href="https://iamvishnuvarapally.wixsite.com/port-folio">here</a>.</p><p>you can follow me on different platforms <a href="https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/">LinkedIn</a>, <a href="https://github.com/VishnuVardhanVarapalli">Github</a> and, <a href="https://iamvishnu-varapally.medium.com/">medium</a>.</p><p>Happy Learning✌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef946adf4122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machines Deep Intuition PART-II (Math)]]></title>
            <link>https://iamvishnu-varapally.medium.com/support-vector-machines-deep-intuition-part-ii-math-690a55923945?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/690a55923945</guid>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 04:34:09 GMT</pubDate>
            <atom:updated>2021-08-27T13:55:38.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*IsfqyxpsBXyk6F0m.jpeg" /></figure><p>This post is the continuation post of <a href="https://medium.com/analytics-vidhya/support-vector-machines-deep-intuition-part-i-basic-intuition-3b21d841210b">this</a>. Make sure you went through <a href="https://medium.com/analytics-vidhya/support-vector-machines-deep-intuition-part-i-basic-intuition-3b21d841210b">this</a> article before proceeding.</p><p>Let’s see a diagram:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*z1ZYp1MErNXHwYZZ.png" /><figcaption>Image from ResearchGate</figcaption></figure><p><strong>Math:-</strong></p><p>We know that, for Logistic regression, the equation of the line that’ll be formed is,</p><p>y = transpose(W)X + b …………………………………………..(1)</p><p>As the line is towards the right bottom direction, let’s consider the slope = -1 (when you check it with the real coordinates in a graph, you’ll get a negative value, for making the calculations simple, I assume the case of slope = -1).</p><p>Also, consider the line is passing through the origin(0,0)(for simplifying the calculations). the (1) becomes,</p><p>y = transpose(W)X (when (1) is passing through the origin, b value becomes zero) ………………………………………………………………..(2)</p><p>Now, let’s consider the point of X1 = (-4,0) which will be located at the left side of the line (2).</p><p>while substituting (-4,0) in (2),</p><p>transpose(W) = [ -1 0 ] (where -1 is the slope, and 0 is for calculation purpose(you can keep any value there))(in vector form complex number)</p><p>x = transpose([ -4 0 ])(in vector form complex number)</p><p>Now, when we substitute the values, if you know the multiplication of matrix the (2) will become [ ( -1 * -4 ) + (0*0) ] and then the y value will be 4. which is a +ve number. (y = 4)</p><p>Whatever the coordinates you consider at the left side of line (2) it’ll be +ve only. So, for making the calculations similar let’s consider y value = + 1.</p><p>Then (1) becomes,</p><p>transpose(W)X1 + b = 1 …………………………………..(3)</p><p>Similarly, if we consider the coordinates(X2) of (1) and do the above process we’ll end up with the equation of</p><p>transpose(W)X2+ b =-1 …………………………………..(4)</p><p>subtracting (3) from (4),</p><p>transpose(W)[ X1 - X2 ] = 2 ………………………………(5)</p><p>Now, we need to divide (5) with the norm of transpose(W),</p><p><strong>Note:- </strong>if W is a complex number x + iy is a vector in the Euclidean plane, as W possesses magnitude &amp; Directions in the Euclidean plane, the quantity of square_root(x2 + y2)[x square + y square] is the Euclidean norm of W.</p><p>Now by dividing to (5),</p><p>transpose(W) / ||W|| * ( X1 - X2) = 2 / ||W|| ……..(6)</p><p>Here, 2 / ||W|| is our optimization function.</p><p>For getting the best hyperplane we need to have a max value of (6). and we observed while doing the above process that y is +ve, if transpose(W)X + b ≥1 else -ve if transpose(W)X + b &lt;1.</p><p>So what we can say is, if we multiply the value of y and transpose(W)X + b, then it should be +ve for correct prediction else -ve for the wrong prediction.[ Check the above para if you have doubt]</p><p>This is How predictions will be made.</p><p>So, for now,</p><p>Things to keep in mind as rough:</p><ol><li>There will be many hyperplanes that can give 100% accuracy.</li><li>We need to select a hyperplane in such a way that the distance of closest points from the hyperplane should be maximum.</li><li>The distance between the closest points(which passes through marginal lines) and the hyperplane will be calculated as the perpendicular projection of the point on the hyperplane.</li></ol><p>Now, for proceeding before, we need to discuss a concept called Margins.</p><p>SVMs are built of 2 types of margins:-</p><ol><li>Hard margins</li><li>Soft margins</li></ol><p>The hard margin(middle of marginal lines) is the Hyperplane, which we select as a final hyperplane when the data we had is Linear separable data.</p><p>When the data is linearly separable, we don’t want to have any misclassifications, we use SVMs with a Hard Margin. Hard margins are sensitive to outliers &amp; noise in the data.</p><p>However, for Non-linear data, we can allow some misclassifications in the hope of achieving better generality, we’ll use a soft margin for our classifier. Note that, soft margins SVMs avoid iterating over outliers.</p><p>For Hard Margins, i.e., for Linear data classifiers, we’ll have optimization function,</p><p><strong>Optimization function for linear classifiers = MAX(2 / ||W||) …… (7)</strong></p><ul><li>In the real world, the data will be not linear in nature. There will be many overlapping data points and many characteristics which lead to overfitting(I hope you know about overfitting).</li></ul><p>For dealing with Non-linear data, i.e., soft margin classifiers, Zeta(i) and C(i) factors come into the picture in optimization function(look ahead to understand 😊)</p><p>Let’s think while training with the data,</p><p>C(i) -&gt; represents No. of errors your hyperplane can consider to finalize it as the final hyperplane.</p><p>let’s think we’ve assigned a value of C(i) as 5, which means 5 errors can be considered. if more than 5 errors are encountered, then we’ll change the hyperplane.</p><p>Zeta(i) -&gt; it represents the sum of errors(like in linear regression).</p><p>Now, the Optimization function becomes,</p><p><strong>Optimiation function = MAX[ min(||W||/2) + C(i) sum(Zeta(i)) ] . (8)</strong></p><p>(8) represents the optimization function for the non-linear data, i.e., soft margin classifiers. But, this is not the end for non-linear data, as kernels comes to picture(we’ll discuss them later)</p><p>According to the optimization function, the hyper plane will be selected, the hyperplane which can give the maximum value of optimization, that hyperplane will be finalized for the model.</p><p>This is how the Model will get built with support vector machines.</p><p>For now, you can confidently say that “ I know the math &amp; stats behind how a model will get built-in support vector machines with linear type of data”. Yes, real-world data will be completely different and nonlinear.</p><p>So, to deal with nonlinear data, we have SVM-Kernels. in PART-3, we’ll discuss different types of SVM kernels, and math behind it, and the code implementation of SVMs.</p><p>That’s all for now. See you in the next Article😁.</p><p>Thank you &amp; Happy Learning✌.</p><p>If something is missing, lemme know by contacting me from <a href="https://iamvishnuvarapally.wixsite.com/port-folio">here</a>. you can follow me on different platforms <a href="https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/">LinkedIn</a>, <a href="https://github.com/VishnuVardhanVarapalli">Github</a> and, <a href="https://iamvishnu-varapally.medium.com/">medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=690a55923945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machines Deep Intuition PART-I(Basic Intuition)]]></title>
            <link>https://medium.com/analytics-vidhya/support-vector-machines-deep-intuition-part-i-basic-intuition-3b21d841210b?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b21d841210b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Thu, 13 May 2021 06:39:10 GMT</pubDate>
            <atom:updated>2021-05-14T15:23:35.944Z</atom:updated>
            <content:encoded><![CDATA[<p>Before diving into Support Vector Machines, you need to know what is Classification and Regression. For knowing them, got through <a href="https://iamvishnu-varapally.medium.com/a-brief-introduction-to-machine-learning-learners-at-medium-level-4a3d91200b60?sk=f211c648bde50546928f078c90f82fb7">this</a>.</p><p>Here, we are not discussing any math, we’ll discuss it in PART-2 and PART-3 of this post. Don’t stop if you didn’t get any concept, read twice to understand as I’m explained everything in a simple manner.</p><p>There are so many similarities between Logistic regression and SVMs. So, if you don&#39;t know about logistic regression. go through logistic regression first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*VXY0Cn_4iMUU7AagZ3CS0w.jpeg" /></figure><p>Support Vector Machines are used to solve both classification and regression problems.</p><p>SVMs are also used in Outlier Detection.</p><p>Note that, SVMs(Support Vectors Machines) is good for handling Complex but small and medium training datasets.</p><p>SVMs are designed to work only with binary data. But we can make it a Multi-class classification with OneVsOne and oneVsRest Strategies.</p><p>So now, before getting into details, you need to know something.</p><ol><li><strong>Linear Separable Vs Linearly non-separable Data</strong>:- Linearly separable data is the data that can be divided easily as shown in the figure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*vbUG0UO-EAGvWHIFTuh4XA.png" /></figure><p>let’s consider, your training data consists of 2 columns, and output variables are of 2 classes. in the above image, the x-axis represents a column and the y-axis represents another column, and when we plot the points in a 2-d plane, the + sign data points represents a class, and circled points represents another class in data labels. As we can see, the data is separable by a thick line(for now don&#39;t care about dotted lines which are parallel to the thick line). But, real-world data will be not like this. lemme show you another type of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*UJYF55R5cFJ3q3wh2aFihw.png" /></figure><p>Normally, the above data resembles real-time data.</p><p>In the above picture, the green and blue balls represent 2 classes of class labels. the above data is not linearly separable data as data is not separable with a straight line or a curved straight line precisely as like in linearly separable data.</p><p>Now, I&#39;ll say some things to keep in mind, the terminology we can say in a much better way.</p><p>lemme show you a picture,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*HY_EFgWRkxwQQw5CeKTnyg.png" /></figure><p>In the above diagram, the thick straight line is called Hyper Plane, and the parallel lines are called marginal lines, and data points(red and blue balls represents 2 classes of output labels) which are touching the marginal lines are called Support Vectors, the distance between the 2 marginal lines are called marginal distance.</p><p>You may ask what is the use of knowing this, these are the components of Support Vector Machines that we’ll discuss now deeply. We’ll go through everything, don’t worry about that.</p><p>In the above picture, if the hyperplane is formed without having those marginal lines, then it’s simply logistic regression. Without marginal lines, hyperplane will be selected as same as in logistic regression(which is close to all points). But here, we’ll have marginal lines for purpose, which makes SVMs unique.</p><p>Now, let’s understand how Hyperplane get selected from many hyperplanes, and how marginal lines get drawn &amp; its purpose:-</p><p>Assuming that data we have is linearly separable data.</p><ol><li>Let’s think you just created a hyperplane without considering the margins.</li><li>Then the hyperplane will get oriented in such a way that it is close to some of the points in our training dataset as like in linear &amp; logistic regression.</li><li>Then, there is a chance that the test data (or) new data will lie on the wrong side of the hyperplane, even if the new points lie close to training examples of the correct class.</li><li>But, when we create a hyperplane in such a way that the data points are far, then even if new data is a little closer to the wrong class than the training points, it will still lie on the correct side of the hyperplane (Approximately).</li><li>In order to select a hyperplane that is far from data points what we’ll do is we’ll select the nearest points(which will get turned as support vectors) to the hyperplanes, then we’ll have a projection of the nearest points(support vectors) on all hyperplanes, which hyperplane will give the maximum sum of distances(perpendicular distances) from all support vectors, that hyperplane will be selected as the final hyperplane.</li><li>Now, marginal lines will be drawn through the support vectors and parallel to the selected hyperplane.</li><li>Note that, there are many hyperplanes that will give good accuracy, but we need to select a hyperplane in such a way that the distance between support vectors and hyperplane is maximum.</li></ol><p>For now, you have some basic knowledge about why we have marginal lines, how hyperplane will get selected, and how marginal lines will be drawn, what is support vectors and things.</p><p>let’s talk about non-linear data. inorder to deal with non-linear data, SVM kernels are used.</p><p>In a simple way, SVM kernels will make us look at the data from the lower dimension to the higher dimension, in such a way that the data looks like linear separable data, and we can be able to get a hyperplane.</p><p>There are different types of SVM kernels like.,</p><ol><li>Polynomial kernels.</li><li>RBF(radial basis function) Kernels.</li><li>sigmoid kernels.</li></ol><p>and many others…</p><p>This is the end.</p><p>Now, you can confidently say that “I have a complete basic intuition about Support vector machines”. and of course this is not the end for SVMs, whatever we discussed above is the basic knowledge of SVMs in order to understand the math behind every concept we discussed.</p><p>Don’t worry, if you didn’t get any concept clearly, in PART-2 and PART-3 I’ll discuss the complete math of SVMs where your concepts become crystal clear.</p><p>Thank you &amp; Happy Learning✌.</p><p>If something is missing, lemme know by contacting me from <a href="https://iamvishnuvarapally.wixsite.com/port-folio">here</a>. you can follow me on different platforms <a href="https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/">LinkedIn</a>, <a href="https://github.com/VishnuVardhanVarapalli">Github</a> and, <a href="https://iamvishnu-varapally.medium.com/">medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b21d841210b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/support-vector-machines-deep-intuition-part-i-basic-intuition-3b21d841210b">Support Vector Machines Deep Intuition PART-I(Basic Intuition)</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[Deep intuition and things behind the ROC Curve and Area Under ROC Curve(AUC)]]></title>
            <link>https://medium.com/analytics-vidhya/deep-intuition-and-things-behind-the-roc-curve-and-area-under-roc-curve-auc-894337d96ed?source=rss-e3f6e359f240------2</link>
            <guid isPermaLink="false">https://medium.com/p/894337d96ed</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[sklearn-metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vishnu vardhan Varapalli]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 07:17:53 GMT</pubDate>
            <atom:updated>2020-12-11T11:56:18.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*DxDTOQyPkSXy1_xQuPbG7Q.png" /></figure><p>This Blog is the continuation of <a href="https://medium.com/analytics-vidhya/evaluating-metrics-for-classification-machine-learning-models-learners-at-medium-level-c956a8b8d889">this post</a>.</p><p>For now, I am assuming that you know the Confusion matrix, Accuracy, Precision, Recall, and F1 score.</p><p>I’m again saying, before learning these metrics you need to have knowledge about how to build a classification model.</p><p>For now, I’ll build a model for you...</p><p>Let’s get the same old code snippet,</p><pre>import pandas as pd<br>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifier</pre><pre>X,y = make_classification(n_samples=200,n_features=10,random_state=20)</pre><pre>X_train,X_test,y_train,y_test = <br>sklearn.model_selection.train_test_split(X,y,random_state = 43)</pre><pre>model = DecisionTreeClassifier()<br>model.fit(X_train,y_train)</pre><p>For now, You have a model.</p><p>Till now, what you’ve understood is, <strong>“if you saw an imbalanced dataset, then you must go with the metric of F1-Score(which combined both precision and recall)”</strong>.</p><p><strong>Note:-</strong> Please Go through my previous blog about classification metrics to understand the below things…</p><p>Before diving into ROC_AUC, we need to know some things like True +ve Rate(TPR), False +ve rate(FPR), False Negative rate(FNR), True -ve rate(TNR), sensitivity, and specificity.</p><ol><li><strong>True Positive Rate(TPR)</strong>:- True +ve Rate is the same as Recall, “it’s the rate at which predicted +ve values got correctly predicted as +ve samples”</li></ol><p><strong>TPR = TP / (TP + FN)</strong></p><p>True Positive Rate is also called <strong>Sensitivity.</strong></p><p>if the sensitivity of the model is high, then our model can predict +ve samples efficiently.</p><p>2. <strong>True Negative rate:-</strong> True Negative rate is the rate at which predicted -ve values got correctly predicted as -ve samples.</p><p><strong>TNR = TN / (TN + FP)</strong></p><p>True Negative Rate is also called <strong>Specificity.</strong></p><p>If the specificity of our model is high, then our model can predict-ve samples efficiently.</p><p>Note:- Whenever we are building our model, we need to design our model in such a way that sensitivity and specificity are very high.</p><p>3. <strong>False Negative Rate(FNR):-</strong> False Negative rate is the rate at which positives values got incorrectly predicted as Negative samples.</p><p><strong>FNR = FN / (FN + TP)</strong></p><p>Also, <strong>(False -ve rate) + ( True +ve rate) = 1</strong></p><p>i.e., <strong>FPR = (1- sensitivity).</strong></p><p>4. <strong>False Positive Rate(FPR):-</strong> False positive rate is the rate at which Negatives values got incorrectly predicted as Positive samples.</p><p><strong>FPR = FP / (FP + TN)</strong></p><p>Also, <strong>(False positive rate + True negative rate) = 1</strong></p><p>i.e.,<strong> FPR = (1-specificity).</strong></p><p>Now, you know what is TPR, TNR, FPR, and FNR.</p><p>If you’re a Machine Learning beginner, then you’ll predict the classes by doing this thing</p><pre>y_pred = model.predict(X_test)</pre><p>when we compiled the above line of code, what will happen is,</p><p>First, the model is going to predict the probabilities of test data to be Positive. Then, by comparing with a threshold of 0.5, i.e., if prediction_probability &gt; 0.5, then the predicted test sample will be said as +ve sample, else it is negative. Actually, we can do practical implementation too.</p><p>see the above implementation with an example:</p><p>Let’s think for a test sample, Predicted_probability = 0.68. Then, this probability will be compared with the threshold = 0.5 i.e., in code language,</p><pre>if( Predicted_Probability &gt; 0.5) #0.5 is threshold <br>{ <br>    return 1;<br>} <br>else <br>{ <br>    return 0;<br>}</pre><p>1 -&gt; Positive</p><p>0-&gt; negative</p><p>Here, by default, our model is considering the threshold as (0.5). So, whenever the predicted probability &gt; 0.5, then the predicted test label will be 1, if the predicted probability &lt; 0.5, then the predicted test label will be 0. All these things will be automatically calculated by the model, and in y_pred, test labels will be appended.</p><p>y_pred will be look like this[1, 0, 0, 1, 1, 1, 1, 0].</p><p>All the metrics that were discussed in the previous blog will be calculated through the above procedure only. The below complete code represents the above explanation.</p><p>Read again, if you didn’t understand…</p><pre>import pandas as pd<br>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifier</pre><pre>X,y = make_classification(n_samples=200,n_features=10,random_state=20)</pre><pre>X_train,X_test,y_train,y_test = <br>sklearn.model_selection.train_test_split(X,y,random_state = 43)</pre><pre>model = DecisionTreeClassifier()<br>model.fit(X_train,y_train)</pre><pre>#this will be predicted with the threshold of 0.5 as explained above<br>y_pred = model.predict(y_test)</pre><pre>#y_pred will be look like[1, 0, 0, 1, 1, 1, 1, 0]<br>accuracy_score = sklearn.metrics.accuracy_score(y_true,y_pred)</pre><p>Now, we’ll see another type of prediction in order to understand the ROC_AUC…</p><p>Till now, what you’ve studied is a type of prediction method which you won&#39;t use much in implementing real-time applications. Now, we’ll discuss a method of predicting, which will be used in real-world problem-solving.</p><p>The method is simple. As we consider the default threshold as 0.5, manually we’ll predict the probabilities of test samples and then, we’ll consider a threshold in such a way that our metric will give high accuracy.</p><p>Note:- From now, you should not use model.predict() function, see the below function and you should use it now.</p><p>the function is,</p><pre>model.predict_proba(X_test)</pre><p>the above function will predict the probabilities of test samples to be positive. The higher the value, the higher the chance that the test sample to be +Ve.</p><p><strong>ROC_AUC Score:- </strong>ROC_AUC score is nothing but the area of the ROC Curve, whereas the ROC Curve will get built by using different TPRs and FPRs according to different thresholds.</p><p>Let’s get dive into the ROC_AUC score step by step:-</p><ol><li>Consider a set of thresholds, let’s say, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0].</li></ol><p>Now, we’ll compare the test sample predicted probabilities with each threshold and predict the discrete values i.e. 0 or 1.</p><p>According to the predicted discrete values, the True +Ve rate, False +Ve rate will get calculated.</p><p>see the above point implementation below…</p><pre>model = sklearn.linear_model.LogisticRegression()   model.fit(X_train.values,y_train.values)</pre><pre>y_prob = model.predict_proba(X_test.values)             print(y_prob)</pre><pre>tpr = []<br>fpr = []</pre><pre>for i in threshold_list:<br>   k = y_prob[:,1] &gt; i<br>   j = []<br>   for i in k:<br>      j.append(int(i)<br>   tp = true_positive(y_test,j)<br>   fp = false_positive(y_test,j)<br>   tn = true_negative(y_test,j)<br>   fn = false_negative(y_test,j)<br>   tpr.append(tp/(tp+fn))<br>   fpr.append(fp/(fp+tn))</pre><pre>data = list(zip(tpr,fpr))<br>dataset = pandas.DataFrame(data,columns = [&quot;tpr&quot;,&quot;fpr&quot;])<br>print(dataset.values)</pre><p>the above code will give output something like below:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4zuUzHAT9Zap2IEqS7dQQ.png" /></figure><p>In the output, left values represent TPR, right values represent FPR</p><p>The dataset that I consider above is just used to show how FPR &amp; TPR will get calculated, don’t get bothered about the dataset. Just concentrate on how FPR &amp; TPR getting calculated(you can see the dataset <a href="https://github.com/vishnu2136/Datasets_for_Problem_Statements/blob/master/p3%20-%20loan%20prediction/modified.csv">here</a>).</p><p>2. Now, we’ll plot a graph which is called the ROC Curve, with the help of TPRs and FPRs, that we calculated for different thresholds.</p><p>see the code &amp; output below,</p><pre>plt.figure(figsize = (7,7))<br>plt.fill_between(dataset.fpr.values,dataset.tpr.values, alpha=0.4)<br>plt.plot(dataset.fpr.values,dataset.tpr.values,lw = 2)<br>plt.title(&quot;ROC_AUC CURVE&quot;)<br>plt.xlim(0,1.0)<br>plt.ylim(0,1.0)<br>plt.xlabel(&quot;fpr&quot;,fontsize = 16)<br>plt.ylabel(&quot;tpr&quot;,fontsize = 16)<br>plt.show()</pre><p>Output for the code is a graph which is ROC Curve, see below:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xfkTLfOSPgDGfdJXPVMnA.png" /></figure><p>Don’t bother about the curve, just concentrate on how to plot a ROC Curve. I didn&#39;t preprocessed data that much before modeling. So, the Curve is not good enough.</p><p>3. Now, we need to find out the area of the Blue region in the graph, which is called <strong>Area of the ROC</strong> <strong>Curve</strong> also called <strong>Area Under the Curve(AUC).</strong></p><p>We can go into linear algebra, integration, and many math frameworks in order to calculate the area under the curve. But we don&#39;t need to go much into them. We can calculate the area by using sklearn, which will give AUC(Area Under the Curve).</p><p>This AUC is one of the most popular metrics in machine learning for skewed targets.</p><p>let’s see the code of calculating this area(one line only😉):-</p><pre>print(sklearn.metrics.roc_auc_score(y_test,y_prob[:,1]))</pre><p>which will give the output of Area Under the Curve like:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wi5m_C4IlGxlFPXwohodyQ.png" /><figcaption>AUC score</figcaption></figure><p>the AUC score will be between 0 and 1. if the AUC score is close to 1, then the model we developed is one of the best models that one can develop for the considered dataset(there is also a chance that, it may be got overfitted, be careful about that). if AUC Score is close to 0, then our model is even worse than random guessing.</p><p>if our model gives the score = 0.5, then our model is a naive model.</p><p><strong>Big Note:-</strong></p><p>We can use the ROC Curve for another purpose too. As we can see above that, with different thresholds, different discrete predictions are produced, and different TPRs and FPRs are produced. but, while developing industrial applications, a particular value of threshold will get selected by project domain expertise people, in such a way that whether they want high TPRs or low TPRs, high FPRs or low FPRs, and according to that, a threshold will get selected. with the help of that threshold only, discrete value predictions will take place from predicted probabilities. On, those predictions, Metrics will get applied.</p><p>As we are beginners in machine learning, we will select the threshold in such a way that both TPR and FPR will get balanced. The Top-Left value in any ROC curve will give a balanced threshold.</p><p>I think this is all about the ROC_AUC score…</p><p>if anything needs to be added, lemme know…</p><p>contact me here:- <a href="https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/">https://www.linkedin.com/in/vishnu-vardhan-varapalli-b6b454150/</a></p><p>Happy Learning✌!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=894337d96ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deep-intuition-and-things-behind-the-roc-curve-and-area-under-roc-curve-auc-894337d96ed">Deep intuition and things behind the ROC Curve and Area Under ROC Curve(AUC)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>