<?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 Vaibhav Jayaswal on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Jayaswal on Medium]]></description>
        <link>https://medium.com/@jayaswalvaibhav?source=rss-8fd8456ab811------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oMfEmgJbHNLoChwq3UjsCw.jpeg</url>
            <title>Stories by Vaibhav Jayaswal on Medium</title>
            <link>https://medium.com/@jayaswalvaibhav?source=rss-8fd8456ab811------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:55:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayaswalvaibhav/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 Strong Foundations: Understanding SOLID Principles]]></title>
            <link>https://levelup.gitconnected.com/building-strong-foundations-understanding-solid-principles-7a51dd4b8b13?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a51dd4b8b13</guid>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Tue, 28 May 2024 22:28:52 GMT</pubDate>
            <atom:updated>2024-05-28T22:28:52.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sLCQ-f469mrJ7rqGq27pHg.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/person-using-macbook-pro-on-person-s-lap-1181298/">Christina Morillo</a>, from Pexels</figcaption></figure><p>In the world of software development, writing code that is not only functional but also maintainable and scalable is crucial. Software engineers often turn to design principles to create maintainable and scalable code. Among these design principles, SOLID principles are fundamental guidelines for developing clean and maintainable object-oriented code. In this article, we will delve into each of the SOLID principles.</p><ol><li>Single Responsibility Principle (SRP)</li><li>Open/Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP), and</li><li>Dependency Inversion Principle (DIP)</li></ol><h3>1. Single Responsibility Principle (SRP)</h3><p>The <em>Single Responsibility Principle</em> states that a class should have only one reason to change, meaning it should have only one job or responsibility.</p><h4>Advantages</h4><ol><li><strong>Modularity</strong>: By ensuring that each class has only one responsibility, code becomes more modular and easier to understand, test, and maintain.</li><li><strong>Enhanced Reusability</strong>: Classes with single responsibilities are more reusable since they are focused on specific tasks, making them suitable for various contexts.</li></ol><h4>Example:</h4><p>Consider a class Employee responsible for both employee data management and generating payroll reports.</p><pre>class Employee {<br>    private int id;<br>    private String name;<br>    private double salary;<br><br>    public Employee(int id, String name, double salary) {<br>        this.id = id;<br>        this.name = name;<br>        this.salary = salary;<br>    }<br><br>    public void generatePayrollReport() {<br>        System.out.println(&quot;Payroll Report:&quot;);<br>        System.out.println(&quot;ID: &quot; + id + &quot;, Name: &quot; + name + &quot;, Salary: $&quot; + salary);<br>    }<br>}</pre><p>In the above example, the Employee class has dual responsibilities (data management and report generation). According to SRP, refactoring would involve separating these concerns into two classes: Employee (for data management) and PayrollReportGenerator (for report generation).</p><pre>class Employee {<br>    private int id;<br>    private String name;<br>    private double salary;<br><br>    public Employee(int id, String name, double salary) {<br>        this.id = id;<br>        this.name = name;<br>        this.salary = salary;<br>    }<br><br>    public int getId() {<br>        return id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public double getSalary() {<br>        return salary;<br>    }<br>}<br><br>class PayrollReportGenerator {<br>    private List&lt;Employee&gt; employees;<br><br>    public PayrollReportGenerator(List&lt;Employee&gt; employees) {<br>        this.employees = employees;<br>    }<br><br>    public void generatePayrollReport() {<br>        System.out.println(&quot;Payroll Report:&quot;);<br>        for (Employee employee : employees) {<br>            System.out.println(&quot;ID: &quot; + employee.getId() + &quot;, Name: &quot; + employee.getName() + &quot;, Salary: $&quot; + employee.getSalary());<br>        }<br>    }<br>}</pre><h3>2. Open/Closed Principle (OCP)</h3><p>The Open/Closed Principle states that classes should be open for extension but closed for modification. In other words, you should be able to extend a class’s behavior without modifying its source code.</p><h4>Advantages</h4><ol><li><strong>Scalability</strong>: Code adhering to OCP is easier to scale since new functionality can be added through extension rather than modification, reducing the risk of introducing bugs.</li><li><strong>Maintainability</strong>: Existing code remains unchanged, reducing the likelihood of introducing errors in previously tested and stable components.</li></ol><h4>Example</h4><p>Consider that your application has a logging system that logs messages to various destinations, such as a console, a file, and a database. Initially, you might have a single class responsible for logging messages to the console.</p><pre>public class ConsoleLogger {<br>    public void log(String message) {<br>        System.out.println(&quot;[Console] &quot; + message);<br>    }<br>}</pre><p>However, as your application grows, you might need to log messages to additional destinations like a file or a database. Instead of modifying the existing ConsoleLogger class every time you need to add a new logging destination, you can adhere to the <strong>Open/Closed Principle </strong>by extending the logging functionality without modifying the existing class.</p><p>Refactoring based on OCP involves</p><ol><li>Define an interface Logger which represents the behavior of logging messages.</li></ol><pre>public interface Logger {<br>    void log(String message);<br>}</pre><p>2. Implement concrete logger classes for each logging destination, implementing the Logger interface.</p><pre>public class ConsoleLogger implements Logger {<br>    @Override<br>    public void log(String message) {<br>        System.out.println(&quot;[Console] &quot; + message);<br>    }<br>}<br><br>public class FileLogger implements Logger {<br>    @Override<br>    public void log(String message) {<br>        // Code to log message to a file<br>    }<br>}<br><br>public class DatabaseLogger implements Logger {<br>    @Override<br>    public void log(String message) {<br>        // Code to log message to a database<br>    }<br>}</pre><p>3. When new logger destinations are required, we can create new classes that implement the Logger interface without modifying existing classes. This approach allows you to extend the logging system with new logging destinations without modifying existing code, thus adhering to the Open/Closed Principle.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p>The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without disrupting the class&#39;s behavior. In layman&#39;s terms, <strong>if class <em>A</em> is a subtype of class <em>B</em>, we should be able to replace <em>B </em>with <em>A</em>.</strong></p><h4>Advantages</h4><ul><li><strong>Flexibility</strong>: LSP allows for polymorphism, enabling objects of different subclasses to be used interchangeably. This promotes code reuse and flexibility.</li></ul><h4>Example</h4><p>Let’s consider a scenario where we have a base class Employee and two subclasses FullTimeEmployee and PartTimeEmployee. Each employee has a method calculatePay() to calculate their pay.<br>The LSP requires that any operation performed on Employee should also be valid for its subclasses.</p><pre>class Employee {<br>    protected String name;<br>    protected double hourlyRate;<br><br>    public Employee(String name, double hourlyRate) {<br>        this.name = name;<br>        this.hourlyRate = hourlyRate;<br>    }<br><br>    public double calculatePay(int hoursWorked) {<br>        return hoursWorked * hourlyRate;<br>    }<br>}<br><br>// Subclass FullTimeEmployee<br>class FullTimeEmployee extends Employee {<br>    public FullTimeEmployee(String name, double hourlyRate) {<br>        super(name, hourlyRate);<br>    }<br><br>    @Override<br>    public double calculatePay(int hoursWorked) {<br>        // Full-time employees get paid for 40 hours regardless of actual hours worked<br>        return 40 * hourlyRate;<br>    }<br>}<br><br>// Subclass PartTimeEmployee<br>class PartTimeEmployee extends Employee {<br>    public PartTimeEmployee(String name, double hourlyRate) {<br>        super(name, hourlyRate);<br>    }<br><br>    // Part-time employees&#39; pay is calculated based on actual hours worked<br>    @Override<br>    public double calculatePay(int hoursWorked) {<br>        return hoursWorked * hourlyRate;<br>    }<br>}</pre><h3>4. Interface Segregation Principle (ISP)</h3><p>The Interface Segregation Principle suggests that a client should not be forced to depend on interfaces it does not use. Instead of one large interface, clients should be presented with smaller, more specific interfaces.</p><h4>Advantages</h4><ol><li><strong>Reduced Coupling</strong>: Clients only depend on the methods they need, reducing coupling between components and making the system more maintainable and flexible.</li><li><strong>More explicit Contracts</strong>: Smaller, more specific interfaces provide more precise contracts between components, making understanding and implementing them easier.</li></ol><h4>Example</h4><p>Let’s consider a document management system where we have different types of documents, like WordDocument, PdfDocument, and ExcelDocument. These documents may have different functionalities, such as printing, scanning, and editing. Initially, we might have a single interface Document that contains all these methods:</p><pre>public interface Document {<br>    void print();<br>    void scan();<br>    void edit();<br>}</pre><p>However, not all types of documents need to support all functionalities. For example, a PdfDocument might not support editing, while an ExcelDocument might not support scanning. Violating ISP would mean forcing these classes to implement methods they don&#39;t need.</p><p>Refactoring based on ISP involves:</p><ul><li>Segregating the Document Interface into three smaller interfaces: Printable, Scannable, and Editable, each representing a single functionality.</li><li>Each document class (WordDocument, PdfDocument, ExcelDocument) implements only the interfaces it needs, avoiding the need to implement unnecessary methods.</li></ul><pre>// Segregated Interfaces<br>interface Printable {<br>    void print();<br>}<br><br>interface Scannable {<br>    void scan();<br>}<br><br>interface Editable {<br>    void edit();<br>}<br><br>// Classes implementing the segregated interfaces<br>class WordDocument implements Printable, Scannable, Editable {<br>    // Implementation<br>}<br><br>class PdfDocument implements Printable {<br>    // Implementation<br>}<br><br>class ExcelDocument implements Printable, Editable {<br>    // Implementation<br>}</pre><p>This approach adheres to the ISP by providing finer-grained interfaces tailored to the client&#39;s specific needs, thus avoiding unnecessary dependencies and keeping the system more flexible and maintainable.</p><h3>5. Dependency Inversion Principle (DIP):</h3><p>The Dependency Inversion Principle suggests that high-level modules should not depend on low-level modules, but both should depend on abstractions. In essence, classes should depend on abstractions rather than concrete implementations.</p><h4>Advantages</h4><ol><li><strong>Decoupling</strong>: DIP promotes loose coupling between classes by abstracting dependencies, making replacing or updating components easier without affecting others.</li></ol><h4>Example</h4><p>Let’s consider a notification system where we are NotificationService responsible for sending notifications to users through various channels such as email, SMS, or push notifications. Initially, the NotificationService might directly depend on concrete implementations of the notification channels:</p><pre>// Notification service with direct dependencies on concrete notification channels<br>public class NotificationService {<br>    private EmailNotification emailNotification;<br>    private SMSNotification smsNotification;<br>    private PushNotification pushNotification;<br><br>    public NotificationService() {<br>        this.emailNotification = new EmailNotification();<br>        this.smsNotification = new SMSNotification();<br>        this.pushNotification = new PushNotification();<br>    }<br><br>    public void sendNotification(String message) {<br>        // Sending notifications using concrete implementations<br>        emailNotification.send(message);<br>        smsNotification.send(message);<br>        pushNotification.send(message);<br>    }<br>}<br><br>// Concrete EmailNotification class<br>class EmailNotification {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending email notification: &quot; + message);<br>    }<br>}<br><br>// Concrete SMSNotification class<br>class SMSNotification {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS notification: &quot; + message);<br>    }<br>}<br><br>// Concrete PushNotification class<br>class PushNotification {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending push notification: &quot; + message);<br>    }<br>}</pre><p>However, this implementation violates the Dependency Inversion Principle because the NotificationService class is directly dependent on the concrete implementations of notification channels.<br>To adhere to the Dependency Inversion Principle, we should introduce abstractions/interfaces for the notification channels and make the NotificationService depend on these abstractions instead of concrete implementations. This way, we decouple the high-level module (NotificationService) from the low-level modules (notification channels):</p><pre>// Notification channel interface<br>interface NotificationChannel {<br>    void send(String message);<br>}<br><br>// Email notification implementation<br>class EmailNotification implements NotificationChannel {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending email notification: &quot; + message);<br>    }<br>}<br><br>// SMS notification implementation<br>class SMSNotification implements NotificationChannel {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS notification: &quot; + message);<br>    }<br>}<br><br>// Push notification implementation<br>class PushNotification implements NotificationChannel {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending push notification: &quot; + message);<br>    }<br>}<br><br>// Notification service depending on abstractions<br>public class NotificationService {<br>    private NotificationChannel emailNotification;<br>    private NotificationChannel smsNotification;<br>    private NotificationChannel pushNotification;<br><br>    public NotificationService(NotificationChannel emailNotification, <br>                               NotificationChannel smsNotification, <br>                               NotificationChannel pushNotification) {<br>        this.emailNotification = emailNotification;<br>        this.smsNotification = smsNotification;<br>        this.pushNotification = pushNotification;<br>    }<br><br>    public void sendNotification(String message) {<br>        // Sending notifications using abstractions<br>        emailNotification.send(message);<br>        smsNotification.send(message);<br>        pushNotification.send(message);<br>    }<br>}</pre><h3>Conclusion</h3><p>Developers can create modular, flexible, and easy-to-maintain code by adhering to the SOLID principles. These principles provide a solid foundation for designing object-oriented systems that can adapt to changing requirements and scale effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a51dd4b8b13" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-strong-foundations-understanding-solid-principles-7a51dd4b8b13">Building Strong Foundations: Understanding SOLID Principles</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laplace smoothing in Naïve Bayes algorithm]]></title>
            <link>https://medium.com/data-science/laplace-smoothing-in-na%C3%AFve-bayes-algorithm-9c237a8bdece?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c237a8bdece</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[laplace-smoothing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 12:56:03 GMT</pubDate>
            <atom:updated>2020-11-22T22:32:23.519Z</atom:updated>
            <content:encoded><![CDATA[<h4>Solving the zero probability problem in Naïve Bayes algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McziBBjleGqRFM7fQ2rCVQ.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/close-up-of-hands-249360/">Louis Bauer</a>, from Pexels</figcaption></figure><p>Naïve Bayes is a probabilistic classifier based on Bayes theorem and is used for classification tasks. It works well enough in text classification problems such as spam filtering and the classification of reviews as positive or negative. The algorithm seems perfect at first, but the fundamental representation of Naïve Bayes can create some problems in real-world scenarios.</p><p>This article is built upon the assumption that you have a basic understanding of Naïve Bayes. I have written an article on Naïve Bayes. Feel free to check it out.</p><p><a href="https://towardsdatascience.com/understanding-na%C3%AFve-bayes-algorithm-f9816f6f74c0">Understanding Naïve Bayes algorithm</a></p><p><strong>Example</strong></p><p>Let’s take an example of text classification where the task is to classify whether the review Is positive or negative. We build a likelihood table based on the training data. While querying a review, we use the Likelihood table values, but <strong>what if a word in a review was not present in the training dataset?</strong></p><p>Query review = w1 w2 w3 w’</p><p>We have four words in our query review, and let’s assume only w1, w2, and w3 are present in training data. So, we will have a likelihood for those words. To calculate whether the review is positive or negative, we compare P(positive|review) and P(negative|review).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ZZ7wrWI5Eq4-cLHZQUtKyg.png" /></figure><p>In the likelihood table, we have P(w1|positive), P(w2|Positive), P(w3|Positive), and P(positive). <strong>Oh, wait, but where is P(w’|positive)?</strong></p><p>If the word is absent in the training dataset, then we don’t have its likelihood. <strong>What should we do?</strong></p><p><strong>Approach1- </strong>Ignore the term P(w’|positive)</p><p>Ignoring means that we are assigning it a value of 1, which means the probability of w’ occurring in positive P(w’|positive) and negative review P(w’|negative) is 1. This approach seems logically incorrect.</p><p><strong>Approach 2- </strong>In a bag of words model, we count the occurrence of words. The occurrences of word w’ in training are 0. According to that</p><p>P(w’|positive)=0 and P(w’|negative)=0, but this will make both P(positive|review) and P(negative|review) equal to 0 since we multiply all the likelihoods. <strong>This is the problem of zero probability</strong>. <strong>So, how to deal with this problem?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gf4Ic5V66RGboWa3OXd3A.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/ask-blackboard-chalk-board-chalkboard-356079/">Pixabay</a>, from Pexels</figcaption></figure><h4>Laplace Smoothing</h4><p>Laplace smoothing is a smoothing technique that handles the problem of zero probability in Naïve Bayes. Using Laplace smoothing, we can represent P(w’|positive) as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*pvtiVc9Sqs7NJ23u0KHOpg.png" /></figure><p>Here,<br><strong>alpha </strong>represents the smoothing parameter,<br><strong>K</strong> represents the number of dimensions (features) in the data, and<br><strong>N </strong>represents the number of reviews with y=positive</p><p>If we choose a value of alpha!=0 (not equal to 0), the probability will no longer be zero even if a word is not present in the training dataset.</p><h4>Interpretation of changing alpha</h4><p>Let’s say the occurrence of word w is 3 with y=positive in training data. Assuming we have 2 features in our dataset, i.e., K=2 and N=100 (total number of positive reviews).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*XAVmGjaBCWtPPO9tb67SJg.png" /></figure><p><strong>Case 1- </strong>when alpha=1</p><p>P(w’|positive) = 3/102</p><p><strong>Case 2- </strong>when alpha = 100</p><p>P(w’|positive) = 103/300</p><p><strong>Case 3- </strong>when alpha=1000</p><p>P(w’|positive) = 1003/2100</p><p>As alpha increases, the likelihood probability moves towards uniform distribution (0.5). Most of the time, alpha = 1 is being used to remove the problem of zero probability.</p><h4>Conclusion</h4><p>Laplace smoothing is a smoothing technique that helps tackle the problem of zero probability in the Naïve Bayes machine learning algorithm. Using higher alpha values will push the likelihood towards a value of 0.5, i.e., the probability of a word equal to 0.5 for both the positive and negative reviews. Since we are not getting much information from that, it is not preferable. Therefore, it is preferred to use alpha=1.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c237a8bdece" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/laplace-smoothing-in-na%C3%AFve-bayes-algorithm-9c237a8bdece">Laplace smoothing in Naïve Bayes algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Naïve Bayes algorithm]]></title>
            <link>https://medium.com/data-science/understanding-na%C3%AFve-bayes-algorithm-f9816f6f74c0?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9816f6f74c0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[bayes-theorem]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Sun, 08 Nov 2020 13:07:09 GMT</pubDate>
            <atom:updated>2020-11-08T17:49:49.429Z</atom:updated>
            <content:encoded><![CDATA[<h4>A probabilistic classifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_SFcCMtgo22pgeuDXOboA.jpeg" /><figcaption>Image by <a href="https://unsplash.com/photos/m4sGYaHYN5o">Riho Kroll</a>, Unsplash</figcaption></figure><p>Naïve Bayes is a classification algorithm that is a probabilistic classifier based on Bayes theorem. Before getting into the intricacies of Naïve Bayes, we first understand the Bayes theorem.</p><h4>Bayes Theorem</h4><p>Bayes theorem says that if event B has occurred, then we can find the probability of event A given B.<br>Mathematically, Bayes theorem is represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*e3ZMC-ga-NlEvGEyEm7azQ.png" /></figure><p>Where P(B) != 0 (!= refers to not equal)<br>P(A|B) — the probability of event A given B (called posterior)<br>P(B|A) — the probability of event B given A (called likelihood)<br>P(A) — the probability of event A (called prior)<br>P(B) — the probability of event B (called evidence)</p><p>For example, if we have a query point X (d-dimensional Boolean vector), we have to predict which class (Y) it belongs to out of two. <strong>How to calculate the probability of Y given X?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*M4zxBsg2eDavo8pNOLUr9Q.png" /></figure><h4>Problem in the above representation</h4><p>Think of how many combinations can exist if we have the above formula. X being a d-dimensional Boolean vector, 2^d possible combinations for vector X, and 2 for output (2 class classification). The total combinations are <strong>2^(d+1)</strong> for P(X1, X2,……, Xd|Y), which is massive and not effective in real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4j1jT7tckMpF6OMrYUdlw.jpeg" /><figcaption>Image by Andrea Piacquadio, Unsplash</figcaption></figure><p>Naïve Bayes handles that problem by making an assumption.</p><h3>Naïve Bayes</h3><p><strong>Assumption </strong>— <strong>Each feature in the input vector is conditionally independent of other features.</strong></p><p>Mathematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*mHyrzhwpi8yMD4wijQQ66g.png" /></figure><p>It states that A is conditionally independent of B given C.</p><p><strong>How can this help?</strong></p><p>The numerator, i.e., P(X1, X2,…., Xd|Y)*P(Y), is equivalent to the joint probability model and can be expressed as P(X1, X2,…., Xd, Y). Then we can unfold it using conditional probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*5An6fao7CVjDtuwQ4yTu9g.png" /></figure><p>On applying the assumption of conditional independence, it can be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*_zF8czGQxU-T3Q23C48O3A.png" /></figure><p>Therefore, the probability formula using conditional independence is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*d9M5_ctu3gN3G4sJLAam5w.png" /></figure><p>The advantage is that we only have to find <strong>(2d+2) values</strong> when assuming conditional independence, <strong>which is significantly less as compared to 2^(d+2)</strong> (2^(d+1) for P(X1, X2,……, Xd|Y) and 2 for P(Y)).</p><p>If we have two classes, we can get the probability of the class Y for class 1 P(Y=1|X) and class 0 P(Y=0|X) given a query point (X). The class assigned to the query point is decided based on the MAP decision rule (maximum a posterior), i.e., the class with a higher probability given X (P(Y|X)).</p><h4>Example</h4><p>Given the features such as outlook, temperature, and windy, predict whether the conditions are appropriate for playing tennis or not.</p><p>X = [outlook, temperature, windy]<br>Y = [Yes, No]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*qJai9bufyRCNa72Ti6Z-nA.png" /><figcaption>Image by Author</figcaption></figure><p>Since Naïve Bayes follows conditional independence, we will calculate P(Xi|Yj) for all i in X and j in Y.</p><p>We will calculate the likelihood tables.</p><p><strong>Table 1</strong></p><p>Outlook P(Outlook|class)- where outlook can be <strong>overcast, rain and sunny</strong> and class can be <strong>yes and no.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*X7FeGXCu8hOTLYdUBPu0Ag.png" /></figure><p><strong>Table 2</strong></p><p>Temperature P(Temperature|class)- where temperature can be <strong>hot, mild, and cool</strong> and class can be <strong>yes and no.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*gkN5BQEI-6VPHQKbmzTs3g.png" /></figure><p><strong>Table 3</strong></p><p>Windy P(Windy |class) - where Windy can be <strong>strong and weak</strong> and class can be <strong>yes and no.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*XO4j1JK7h4mL70jmZplxbQ.png" /></figure><p>Priors are<br><strong>P(class=Yes) = 9/14<br>P(class=No) = 5/14</strong></p><p><strong>So if we have a query point, how to calculate which class it belongs to?</strong></p><p>Given a query point <strong>X’ =[sunny, cool, strong]</strong></p><p>We calculate P(class=Yes|X’) and P(class=No|X’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*web3DsC8Rbk5ZQeY-SCIyg.png" /></figure><p>P(X’) is a constant term which is equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*JOHy035g-CumNGMv14JrSw.png" /></figure><p>From the likelihood table, we get the values required in the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*zhfvBZL70NPXzrz1EayJIQ.png" /></figure><p>Since the probability of class ‘<strong>No’</strong> given X’ is higher than class <strong>‘Yes’</strong> given X’, the query point belongs to class <strong>‘No’.</strong></p><h4>Advantages</h4><ol><li>The naïve Bayes algorithm can also perform multiclass classification by comparing all the classes’ probability given a query point.</li><li>Naïve Bayes algorithm is efficient on large datasets since the time, and space complexity is less.<br>Run time complexity is O(d*c) where d is the query vector’s dimension, and c is the total classes. Space complexity is also O(d*c) since we are storing only the likelihood of each feature with respect to classes, i.e., P(Xd|Yc) where d is the feature and c is the class. Therefore, the total combination is (d*c).</li><li>Naïve Bayes works reasonably well in text classification problems such as spam filtering and reviews classification.</li></ol><p>There are different types of NB, such as<strong> Gaussian Naïve Bayes</strong>, which works well with continuous data, <strong>Multinomial Naïve Bayes</strong> for text classification by using the frequency of each word in a document. Another type is <strong>Bernoulli Naïve Bayes</strong>, which only works if the features take two values (0 and 1) similar to that in the binary Bag of Words model.</p><h4>Conclusion</h4><p>Naïve Bayes is a classification algorithm that works on the Bayes theorem with a conditional independence assumption. It works well in real-world applications that require low latency because of the low time and space complexity.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9816f6f74c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-na%C3%AFve-bayes-algorithm-f9816f6f74c0">Understanding Naïve Bayes algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Imbalanced dataset]]></title>
            <link>https://medium.com/data-science/dealing-with-imbalanced-dataset-642a5f6ee297?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/642a5f6ee297</guid>
            <category><![CDATA[undersampling]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[smote]]></category>
            <category><![CDATA[oversampling]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 13:51:49 GMT</pubDate>
            <atom:updated>2020-10-18T19:23:32.984Z</atom:updated>
            <content:encoded><![CDATA[<h4>Techniques to handle imbalanced data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*vUIIs0D85Ax_FPx8Eeqrig.jpeg" /><figcaption>Image from <a href="https://unsplash.com/photos/qEG6w8vqsaU">Fidel Fernando</a>, from Unsplash</figcaption></figure><p>The imbalanced dataset in real-world problems is not so rare. In layman terms, an imbalanced dataset is a dataset where classes are distributed unequally. An imbalanced data can create problems in the classification task. Before delving into the handling of imbalanced data, we should know the issues that an imbalanced dataset can create.</p><p>We will take an example of a credit card fraud detection problem to understand an imbalanced dataset and how to handle it in a better way.</p><p><strong>EXAMPLE — CREDIT CARD FRAUD DETECTION</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nm0-a_bUXXZtpn-I4t_Ig.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/working-macbook-computer-keyboard-34577/">Negative Space</a>, from Pexels</figcaption></figure><p>The dataset of credit card fraud detection is taken from Kaggle. The dataset contains transactions that occurred in two days, where</p><p>Total transactions in the data = 284,807</p><p>The data has two classes: <strong>0</strong> and <strong>1</strong> represents legal transactions and fraud transactions, respectively. Plotting the distribution of the classes will give us insights about the imbalance if present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*BPkNzDlVT899ri9Y0HUdFw.png" /><figcaption>Image by Author</figcaption></figure><p>The total legit transactions are 284315 out of 284807, which is <strong>99.83%.</strong> The fraud transactions are only 492 in the whole dataset (<strong>0.17%</strong>). An imbalanced dataset can occur in other scenarios such as cancer detection where large amounts of tested people are negative, and only a few people have cancer.</p><h4>Problems an imbalance dataset can create</h4><p>If we are using accuracy as a performance metric, it can create a huge problem. Let’s say our model predicts each transaction as legal (dumb model). Using an accuracy metric on the credit card dataset will give 99.83% accuracy, which is excellent. <strong>IS IT A GOOD RESULT? NO</strong></p><p>For an imbalanced dataset, other performance metrics should be used, such as the Precision-Recall AUC score, F1 score, etc.. Moreover, the model will be biased towards the majority class. Since most machine learning techniques are designed to work well with a balanced dataset, we must create balanced data out of an imbalanced dataset. <strong>HOW TO DO THAT?</strong></p><p><strong>NOTE:</strong> Before changing the dataset, we must split the dataset into training and testing because the change is only for the training purpose.</p><pre>&gt;&gt;&gt;from sklearn.model_selection import train_test_split<br>&gt;&gt;&gt;X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, <br>random_state = 2, shuffle = True, stratify = y)</pre><p>The shape of the training dataset:<br><strong>0: 190430 transactions<br>1: 330 transactions</strong></p><p>We will discuss three methods in this article for creating a balanced dataset from imbalanced data:</p><ul><li><strong>Undersampling</strong></li><li><strong>Oversampling</strong></li><li><strong>Creating synthetic data</strong></li></ul><h4>1. Undersampling</h4><p>Undersampling resamples the majority class points in the data to make them equal to the minority class points. We will be creating a new dataset out of the original dataset using undersampling. We will randomly sample the legal transactions (190490 in number) in the credit card fraud detection to make data points of class 0 equal to 330 (minority class).</p><pre>&gt;&gt;&gt;from imblearn.under_sampling import RandomUnderSampler<br>&gt;&gt;&gt;rus = RandomUnderSampler(random_state=0)<br>&gt;&gt;&gt;X_resampled_under, y_resampled_under =rus.fit_resample(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*c2PhKHjBB1-X9kRUa8_5RQ.png" /><figcaption>Image by Author</figcaption></figure><p>The major disadvantage of undersampling is that we do not use a significant chunk of the data, which contains some information<strong>. In our example, we have removed 190160 (190490–330) data points.</strong> Therefore, we are losing information, and as a result, we will not get significant results.</p><p>We can avoid that by using a technique called oversampling instead of undersampling.</p><h4>2. Oversampling</h4><p>Oversampling refers to the resampling of the minority class points to equal the total number of majority points. Repetition of the minority class points is one such type of oversampling technique.</p><p>Apart from repetition, we can provide the class weights to both the class. Providing the large weights to the minority class will give the same result as from that of repetition.</p><h4>3. Creating synthetic data</h4><p>The problem with repeating the data is that it does not provide any extra information. One way to increase the information about the data is by creating synthetic data points. One such technique is the <strong>SMOTE (Synthetic Minority Oversampling technique)</strong>. As the name suggests, SMOTE is an oversampling technique. In layman terms, SMOTE will create synthetic data points for the minority class. It creates new instances between the points of the minority class.</p><p>We can apply SMOTE on the training dataset using the <strong>imblearn</strong> library.</p><pre>&gt;&gt;&gt;from imblearn.over_sampling import SMOTE<br>&gt;&gt;&gt;sm = SMOTE(random_state = 42)<br>&gt;&gt;&gt;X_train_new, y_train_new = sm.fit_sample(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*22VoOh0eiok_Ga8TMbc9Tg.png" /><figcaption>Image by Author</figcaption></figure><h3>Conclusion</h3><p>The imbalanced dataset is extremely common when handling real-world scenarios. A machine learning model is not robust if it uses an imbalanced dataset for training purposes. Therefore, a balanced dataset is preferred for training machine learning models. Techniques such as undersampling, oversampling, and SMOTE can be used to create balanced data.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642a5f6ee297" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dealing-with-imbalanced-dataset-642a5f6ee297">Dealing with Imbalanced dataset</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Vectorization: Term Frequency — Inverse Document Frequency (TFIDF)]]></title>
            <link>https://medium.com/data-science/text-vectorization-term-frequency-inverse-document-frequency-tfidf-5a3f9604da6d?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a3f9604da6d</guid>
            <category><![CDATA[text-vectorization]]></category>
            <category><![CDATA[term-frequency]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Sun, 04 Oct 2020 14:40:45 GMT</pubDate>
            <atom:updated>2020-10-04T16:52:21.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Text Vectorization: Term Frequency — Inverse Document Frequency (TFIDF)</h3><h4>A technique for converting text into finite length vectors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug7ZvOXwIgdZgJykCeqBUA.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/black-and-white-design-text-wall-241832/">Hermaion</a> (left) and <a href="https://unsplash.com/photos/faixctm2YRQ">Tyler Easton</a> (right)</figcaption></figure><p>Bag of words (BoW) converts the text into a feature vector by counting the occurrence of words in a document. It is not considering the importance of words. <strong>Term frequency — Inverse document frequency (TFIDF) </strong>is based on the Bag of Words (BoW) model, which contains insights about the less relevant and more relevant words in a document. The importance of a word in the text is of great significance in information retrieval.</p><p><strong>Example</strong> — If you search something on the search engine, with the help of TFIDF values, search engines can give us the most relevant documents related to our search.</p><p>We will be discussing in detail how TFIDF can tell us which word is more important? We will first look into term frequency (TF) and inverse document frequency (IDF) separately and then combine it at the end.</p><h4>Term Frequency (TF)</h4><p>It is a measure of the frequency of a word (w) in a document (d). TF is defined as the ratio of a word’s occurrence in a document to the total number of words in a document. The denominator term in the formula is to normalize since all the corpus documents are of different lengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*SphmlJiMjjpHFjAuZRJDqA.png" /><figcaption>Image by Author</figcaption></figure><p><strong>EXAMPLE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*-0g0HFp9BKdgYSJOUhlKOA.png" /><figcaption>Image by Author</figcaption></figure><p>The initial step is to make a vocabulary of unique words and calculate TF for each document. TF will be more for words that frequently appear in a document and less for rare words in a document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*ZXVW1MFpPGOgDne8spdawA.png" /><figcaption>Image by Author</figcaption></figure><h4>Inverse Document Frequency (IDF)</h4><p>It is the measure of the importance of a word. Term frequency (TF) does not consider the importance of words. Some words such as’ of’, ‘and’, etc. can be most frequently present but are of little significance. IDF provides weightage to each word based on its frequency in the corpus D.</p><p>IDF of a word (w) is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*sMAGjYvUyPNMmx5zA9qo0g.png" /><figcaption>Image by Author</figcaption></figure><p>In our example, since we have two documents in the corpus, N=2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*owBBWicmILMFw7gHvE5rzw.png" /><figcaption>Image by Author</figcaption></figure><h4>Term Frequency — Inverse Document Frequency (TFIDF)</h4><p>It is the product of TF and IDF.</p><ul><li>TFIDF gives more weightage to the word that is rare in the corpus (all the documents).</li><li>TFIDF provides more importance to the word that is more frequent in the document.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*fKWpB082SSPWQWEn_2NSSw.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*FCG4RqeoOIdttCVHh9qxcA.png" /><figcaption>Image by Author</figcaption></figure><p>After applying TFIDF, text in A and B documents can be represented as a TFIDF vector of dimension equal to the vocabulary words. The value corresponding to each word represents the importance of that word in a particular document.</p><p><strong>Why are we using Ln in the IDF formula?</strong></p><p>TFIDF is the product of TF with IDF. Since TF values lie between 0 and 1, not using ln can result in high IDF for some words, thereby dominating the TFIDF. We don’t want that, and therefore, we use<strong> ln </strong>so that IDF should not completely dominate the TFIDF.</p><h4>Disadvantage of TFIDF</h4><p>It is unable to capture the <strong>semantics</strong>. For example, <strong>funny</strong> and <strong>humorous</strong> are synonyms, but TFIDF does not capture that. Moreover, TFIDF can be computationally expensive if the vocabulary is vast.</p><h4>Conclusion</h4><p>Term Frequency — Inverse Document Frequency (TFIDF) is a technique for text vectorization based on the Bag of words (BoW) model. It performs better than the BoW model as it considers the importance of the word in a document into consideration. The main limitation is that it does not capture the semantic meaning of the words. This limitation of TFIDF can be overcome by more advanced techniques such as word2Vec.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a3f9604da6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/text-vectorization-term-frequency-inverse-document-frequency-tfidf-5a3f9604da6d">Text Vectorization: Term Frequency — Inverse Document Frequency (TFIDF)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Vectorization: Bag of Words (BoW)]]></title>
            <link>https://medium.com/data-science/text-vectorization-bag-of-words-bow-441d1bfce897?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/441d1bfce897</guid>
            <category><![CDATA[bow]]></category>
            <category><![CDATA[text-vectorization]]></category>
            <category><![CDATA[bag-of-words]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 14:52:14 GMT</pubDate>
            <atom:updated>2020-09-28T16:29:31.425Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to convert text features into vectors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0hBA8NnTD6l7L8Z2j-eiQ.jpeg" /><figcaption>Image by <a href="https://unsplash.com/photos/BVyNlchWqzs">Amador Loureiro</a>, from Unsplash</figcaption></figure><p>Text data is used in natural language processing (NLP), which interacts between humans and machines using natural language. Text data helps analyze movie reviews, products using Amazon reviews, etc. But the question that arises here is <strong>how to deal with text data when building a machine learning model?</strong></p><p>Text data is converted to a real-valued vector by various techniques. One such approach is <strong>Bag of Words (BoW), </strong>which will be discussed in this article. But <strong>why do we have to convert the text into a vector? Why can’t we use text data to build a machine learning model?</strong></p><h4>Need for text vectorization</h4><p>Let’s say we have reviews of a product. Text reviews provided by the customers are of different lengths. By converting from text to numbers, we can represent a review by a finite length of the vector. In this way, the length of the vector will be equal for each review, irrespective of the text length.</p><p>Bag of words is the most trivial representation of text into vectors. Each column of a vector represents a word. The values in each cell of a row show the number of occurrences of a word in a sentence.</p><p><strong>Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*PuyVAffx2GLwqzZmmOE52w.png" /><figcaption>Image by Author</figcaption></figure><p>The initial step is to find a <strong>vocabulary of unique words</strong> (ignoring the punctuation and cases). Vocabulary in the above example:</p><p><strong>[This, movie, is, the, good, of, times, not, I, love, watch, you, will, it, too]</strong></p><p>In our vocabulary, <strong>we have 15 unique words</strong>. Therefore, <strong>each movie review is represented by a vector of 15 dimensions</strong> (each word representing a dimension). For the first review:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*fojk86PrWNcu4Y5K8oQlyw.png" /><figcaption>Image by Author</figcaption></figure><p>The values corresponding to each word shows the number of occurrences of a word in a review. Similarly, 15-dimension vectors represent the remaining reviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*S8uW62e3AbYw3gnylm4eDg.png" /><figcaption>Image by Author</figcaption></figure><p>In real-world problems, text data must be preprocessed before vectorization. Preprocessing includes removing punctuations, converting all words into lowercase, and removing unnecessary words that are not adding any value to the text.</p><p>In Natural Language Processing (NLP), unnecessary words are called <strong>stopwords</strong>. <strong>nltk </strong>library already contains the list of stopwords. There are <strong>179 stopwords in English</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*2WnkBwFQ8IXPTIjc6vHRdQ.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*BYraN4G6KT0Nyiwdld305g.png" /><figcaption>Image by Author</figcaption></figure><p>We’ll see our example after removing the stopwords.</p><p>Vocabulary <strong>— [movie, good, times, love, watch]</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*O45Br4kasWksn6E0vxWRTg.png" /><figcaption>Image by Author</figcaption></figure><p>Note that the vector for review 1 and 2 are the same because ‘not’ is present in stopwords. The model considers both the review the same since the vectors for both are equal. One solution to this problem is using <strong>n-grams.</strong></p><h4>n-grams</h4><p>n-grams are a neighboring sequence of n-words. n can be any positive integer.</p><p>Example — “Bag of words” is a three-gram, “text vectorization” is a two-gram.</p><p>We have used Uni-gram (1-gram) in our example. That means each word is considered as a feature. Removing stopwords will remove words such as ‘not’ which can be useful. Uni-gram based bag of words (BoW) does not take sequence information into account. To consider sequence information, we use <strong>bi-grams, tri-grams</strong>, etc.</p><p>In our example, if we use bi-grams vocabulary can be changed to:</p><p><strong>[This movie, movie is, is good, the movie, is not, not good, I love, love this, movie watch, watch you, you will, will love, love it, it too]</strong></p><p>As a result, n-grams will give better results than the uni-gram based model.</p><h4>Drawbacks of BoW</h4><ol><li>The length of the vector can be high, and most of the values are zero. Computationally, it is not efficient if the vocabulary is very high.</li><li>Uni-gram based BoW is unable to capture the context of the text. Bi-grams and tri-grams can do the job, but they are computationally expensive.</li></ol><h4>Conclusion</h4><p>Bag of words is a text vectorization technique that converts the text into finite length vectors. The boW model is easy to implement and understand. Bag of words has few drawbacks, which can be overcome by using advanced techniques.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=441d1bfce897" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/text-vectorization-bag-of-words-bow-441d1bfce897">Text Vectorization: Bag of Words (BoW)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics: Receiver Operating Characteristic (ROC)- Area Under Curve (AUC)]]></title>
            <link>https://medium.com/data-science/performance-metrics-receiver-operating-characteristic-roc-area-under-curve-auc-79d6d5b0b977?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d6d5b0b977</guid>
            <category><![CDATA[auc]]></category>
            <category><![CDATA[roc]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 04:22:28 GMT</pubDate>
            <atom:updated>2020-09-21T13:17:52.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding ROC — AUC performance metric with an example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvX5H2x_urnYKNS6_PCUnA.jpeg" /><figcaption>Image by <a href="https://unsplash.com/photos/AT77Q0Njnt0">Issac Smith</a>, from Unsplash</figcaption></figure><h4>ROC Curve</h4><p>The Receiver Operating characteristic (ROC) curve is explicitly used for binary classification. However, it can be extended for multiclass classification.</p><p>In binary classification, when a model gives probability scores as output, we use 0.5 as a threshold for the simplest model. If the probability of a query point is greater than 0.5, the model will classify it as class 1 (say positive) otherwise class 0 (negative). To measure the performance of the model, we can use accuracy, confusion matrix, precision, recall, and F1 score.</p><p><strong>A question that arises here is using 0.5 as a threshold will give significant results for every model?</strong></p><p><strong>NO</strong></p><p>Selecting a threshold that produces significant results is problem specific. For example, in cancer detection problems, if we keep a low threshold, more people will be predicted as positive by the model. Moreover, if we set an incredibly high threshold, there is a possibility of missing actual patients.</p><p><strong>How should we decide the appropriate threshold value?</strong></p><p><strong>ROC </strong>is one technique that can give the best threshold value.</p><p>Let’s take a trivial example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*3xfFkRl4MM9v3XUDLqsvVQ.png" /></figure><h4>STEPS</h4><ol><li>Take unique probability scores (in descending order) as a threshold and predict the class labels. If we have k unique probability scores, there will be k thresholds.</li><li>For each threshold, we measure the class labels for all the query points.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*zqZikpkrt6WnogCzVClHsQ.png" /></figure><p>For each prediction, we calculate the true positive rate (TPR) and false positive rate (FPR).<br>Let’s look at the confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*UsOWxGhFMhkfkFZivPFlpQ.png" /><figcaption>Confusion Matrix</figcaption></figure><p>The True Positive rate measures the true positive out of total actual positives (True positive (TP) + False Negative (FN)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*aqbh4isAUSC7NqFPyIhtaw.png" /></figure><p>False Negative rate measures False-positive out of total actual negatives (True Negative (TN) + False Positive (FP)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*1M0ISCcQrtPdck770foyCw.png" /></figure><p>If we have k unique probability score, we will have k different predictions. Therefore, we will have k pairs of (TPR, FPR).<br>In the above example, we have 5 predictions, so there will be 5 TPR, FPR pairs.</p><p><strong>PREDICTION 1 (threshold = 0.95)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*vIVyQxpYBpIdDHipBtr4KA.png" /><figcaption>Confusion matrix for prediction 1 (threshold = 0.95)</figcaption></figure><p>TPR1 = 1/(1+2) = 1/3<br>FPR1 = 0/2 = 0</p><p><strong>PREDICTION 2 (threshold=0.92)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*Vm-jZFMzwJRwrcMdJdtMAw.png" /><figcaption>Confusion matrix for prediction 2 (threshold = 0.92)</figcaption></figure><p>TPR2 = 2/(2+1) = 2/3<br>FPR2 = 0/2 =0</p><p><strong>PREDICTION 3 (threshold = 0.7)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*ydF5bk-F-F66Kd9bBW_j3g.png" /><figcaption>Confusion matrix for prediction 3 (threshold = 0.7)</figcaption></figure><p>TPR3 = 3/3 = 1<br>FPR3 = 0/2 = 0</p><p><strong>PREDICTION 4 (threshold = 0.6)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*fxnYGxmRJjxiBIUhlH4ORA.png" /><figcaption>Confusion matrix for prediction 4 (threshold = 0.6)</figcaption></figure><p>TPR4 = 3/3 = 1<br>FPR4 = 1/(1+1) = 1/2</p><p><strong>PREDICTION 5 (threshold = 0.46)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*HPBGDf8b_zkvtTeaqCnNhw.png" /><figcaption>Confusion matrix for prediction 5 (threshold = 0.46)</figcaption></figure><p>TPR5 = 3/3 = 1<br>FPR5 = 2/2 = 1</p><p>3. Plot the FPR vs. TPR curve with TPR on the y-axis and FPR on the x-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG2SZOBrCY8ALe0LNVYLfw.png" /><figcaption>ROC curve with 5 (FPR, TPR) pairs. The number in parenthesis denotes the prediction number.</figcaption></figure><p>Blueline shows the random model, which means the model is giving a random output (unable to classify the query points). <strong>The appropriate threshold will be the point</strong> <strong>where TPR is maximum, and FPR is minimum</strong> because we want true positive and true negative to be more than a false positive and false negative.</p><p>For our example, the best threshold value will be of <strong>prediction 3,</strong> i.e., <strong>0.70</strong>.</p><h4>AUC</h4><p>The area under the TPR-FPR curve will give an idea about the effectiveness of the model. The higher the AUC score, the better is the model. <strong>AUC scores are used to compare different models</strong>.</p><p>The maximum value of AUC can be 1. <strong>WHY?</strong></p><p>Because the maximum value of TPR and FPR is 1, respectively. So, the maximum area will be 1.</p><p>The classifier is correctly predicting both the classes. In the above example, we have a perfect classifier as the area under the orange curve is 1.</p><p>What can we infer if <strong>AUC =0.5</strong>?</p><p>This means the classifier is unable to separate both the classes. The model is giving random output.</p><p>What can we infer from <strong>AUC&lt;0.5</strong>?</p><p>That means the model predicts the opposite value, i.e., the actual positive label is being predicted as negative and vice versa.</p><p>The below image shows two models. <strong>How do we decide which one is better?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5hLRkAfX46CygTvMkUOgA.png" /><figcaption>ROC curve of 2 models</figcaption></figure><p>Model 2 area under the curve (AUC) is more than that of Model 1. Therefore, <strong>Model 2 is a better classifier than Model 1</strong>.</p><p>A<strong> limitation</strong> of AUC scores is they are <strong>sensitive to imbalanced data.</strong> If the model is dumb, AUC scores can be high.</p><h3>Conclusion</h3><p>The <strong>Receiver Operating Characteristic (ROC)</strong> curve is used to determine the appropriate threshold for the models, which give probability scores as output in binary classification. <strong>Area under the curve (AUC)</strong> scores are used to compare different models. However, they can be impacted by the imbalanced dataset.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d6d5b0b977" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/performance-metrics-receiver-operating-characteristic-roc-area-under-curve-auc-79d6d5b0b977">Performance Metrics: Receiver Operating Characteristic (ROC)- Area Under Curve (AUC)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics: Confusion matrix, Precision, Recall, and F1 Score]]></title>
            <link>https://medium.com/data-science/performance-metrics-confusion-matrix-precision-recall-and-f1-score-a8fe076a2262?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8fe076a2262</guid>
            <category><![CDATA[precision]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <category><![CDATA[recall]]></category>
            <category><![CDATA[f1-score]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 04:29:12 GMT</pubDate>
            <atom:updated>2020-09-15T00:06:35.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unraveling the confusion behind the confusion matrix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vu3W3Z6-U3XGNLwFkc25fQ.jpeg" /><figcaption>Image by <a href="https://unsplash.com/photos/hhq1Lxtuwd8">Jon Tyson</a>, from Unsplash</figcaption></figure><p>Accuracy performance metrics can be decisive when dealing with imbalanced data. In this blog, we will learn about the Confusion matrix and its associated terms, which looks confusing but are trivial. The confusion matrix, precision, recall, and F1 score gives better intuition of prediction results as compared to accuracy. To understand the concepts, we will limit this article to binary classification only.</p><h4>What is a confusion matrix?</h4><p>It is a matrix of size 2×2 for binary classification with actual values on one axis and predicted on another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*UsOWxGhFMhkfkFZivPFlpQ.png" /><figcaption>Confusion Matrix</figcaption></figure><p>Let’s understand the confusing terms in the confusion matrix: <strong>true positive, true negative, false negative, and false positive</strong> with an example.</p><p><strong>EXAMPLE</strong></p><p>A machine learning model is trained to predict tumor in patients. The test dataset consists of 100 people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*m72tZYerDLXEm0GnamIQVg.png" /><figcaption>Confusion Matrix for tumor detection</figcaption></figure><p><strong>True Positive</strong> <strong>(TP)</strong> — model correctly predicts the positive class (prediction and actual both are positive). In the above example, <strong>10 people</strong> who have tumors are predicted positively by the model.<br><strong>True Negative (TN)</strong> — model correctly predicts the negative class (prediction and actual both are negative). In the above example, <strong>60 people</strong> who don’t have tumors are predicted negatively by the model.<br><strong>False Positive (FP)</strong> — model gives the wrong prediction of the negative class (predicted-positive, actual-negative). In the above example, <strong>22 people</strong> are predicted as positive of having a tumor, although they don’t have a tumor. FP is also called a <strong>TYPE I</strong> error.<br><strong>False Negative (FN)</strong> — model wrongly predicts the positive class (predicted-negative, actual-positive). In the above example, <strong>8 people</strong> who have tumors are predicted as negative. FN is also called a <strong>TYPE II</strong> error.</p><p>With the help of these four values, we can calculate True Positive Rate (TPR), False Negative Rate (FPR), True Negative Rate (TNR), and False Negative Rate (FNR).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*k6qWU7kXeCfk2KK2y3Cysg.png" /></figure><p>Even if data is imbalanced, we can figure out that our model is working well or not. For that, <strong>the values of TPR and TNR should be high, and FPR and FNR should be as low as possible.</strong></p><p>With the help of TP, TN, FN, and FP, other performance metrics can be calculated.</p><h4>Precision, Recall</h4><p>Both precision and recall are crucial for information retrieval, where positive class mattered the most as compared to negative. <strong>Why?</strong></p><p>While searching something on the web, the model does not care about something <strong>irrelevant</strong> and <strong>not retrieved</strong> (this is the true negative case). Therefore only TP, FP, FN are used in Precision and Recall.</p><p><strong>Precision</strong></p><p>Out of all the positive predicted, what percentage is truly positive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*tHf0NHWGMwZTNe7TkylyYA.png" /></figure><p>The precision value lies between 0 and 1.</p><p><strong>Recall</strong></p><p>Out of the total positive, what percentage are predicted positive. It is the same as TPR (true positive rate).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*ynGz0zu8ZlpgZ5voYRKfLg.png" /></figure><p><strong>How are precision and recall useful?</strong> Let’s see through examples.</p><p><strong>EXAMPLE 1- Credit card fraud detection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*basHQK-PwsDupyiobifYbw.png" /><figcaption>Confusion Matrix for Credit Card Fraud Detection</figcaption></figure><p>We do not want to <strong>miss any fraud transactions</strong>. Therefore, we <strong>want False-Negative to be as low as possible.</strong> In these situations, we can compromise with the low precision, but recall should be high. Similarly, in the medical application, we don’t want to miss any patient. Therefore we focus on having a high recall.</p><p>So far, we have discussed when the recall is important than precision. <strong>But, when is the precision more important than recall?</strong></p><p><strong>EXAMPLE 2 — Spam detection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*AZCje2me1CRZEIf6eNs9jA.png" /><figcaption>Confusion Matrix for Spam detection</figcaption></figure><p>In the detection of spam mail, it is okay if any spam mail remains undetected (false negative), but what if we miss any critical mail because it is classified as spam (false positive). In this situation, <strong>False Positive</strong> should be as low as possible. Here, precision is more vital as compared to recall.</p><p>When comparing different models, it will be difficult to decide which is better (high precision and low recall or vice-versa). Therefore, there should be a metric that combines both of these. One such metric is the F1 score.</p><h4>F1 Score</h4><p>It is the harmonic mean of precision and recall. It takes both false positive and false negatives into account. Therefore, it performs well on an imbalanced dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*aKtcqDvfMQxwTc1TeAbW5w.png" /></figure><p>F1 score gives the same weightage to recall and precision.</p><p>There is a <strong>weighted F1 score</strong> in which we can give different weightage to recall and precision. As discussed in the previous section, different problems give different weightage to recall and precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*XbRzdFC2-pxiuUQQnVhhYw.png" /></figure><p><strong>Beta represents how many times recall is more important than precision</strong>. If the recall is twice as important as precision, the value of Beta is 2.</p><h4>Conclusion</h4><p>Confusion matrix, precision, recall, and F1 score provides better insights into the prediction as compared to accuracy performance metrics. Applications of precision, recall, and F1 score is in information retrieval, word segmentation, named entity recognition, and many more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8fe076a2262" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/performance-metrics-confusion-matrix-precision-recall-and-f1-score-a8fe076a2262">Performance Metrics: Confusion matrix, Precision, Recall, and F1 Score</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics: Accuracy]]></title>
            <link>https://medium.com/data-science/performance-metrics-accuracy-118f728d328f?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/118f728d328f</guid>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[accuracy]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 03:46:42 GMT</pubDate>
            <atom:updated>2020-09-08T18:47:54.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>How good is your machine learning model?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4WHBYjcNSdyIQGxt8cwow.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/black-and-white-dartboard-1552617/">Engin Akyurt</a>, from Pexels</figcaption></figure><p>The machine learning model is built using training data (which has input as well as output). Prediction is made on the test data (unseen data which does not have an output label) using the same model. <strong>But how do you figure out the effectiveness of the model?</strong> There must be some measures that will evaluate the performance of the model.</p><p>There are many performance metrics to evaluate the model performance, such as accuracy, precision, recall, F1-score, ROC curve, etc. each having its advantages and disadvantages. In this article, we will discuss the <strong>accuracy performance metric</strong>. It is only related to the classification task.</p><p>One might wonder <strong>what classification is?</strong></p><p>When the machine learning model categorizes data into classes (output belongs to a finite set), the task is referred to as classification. Examples of the classification task are — identification of fraud transactions, detection of any disease in a patient, etc.</p><p>Performance measure always evaluates the performance of the model on the test dataset. In this article, we will be using binary classification (where only two classes are present) since it is trivial to understand.</p><h3>ACCURACY</h3><p>It is the ratio of correctly classified points (prediction) to the total number of predictions. Its value ranges between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*RCF0tNYiSHs8rRWSy1BvTw.png" /></figure><p><strong>EXAMPLE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*Z1H-bqTgN3E3DlmmkyfAKw.png" /><figcaption>Actual and predicted values</figcaption></figure><p>what will be the accuracy in the above example?</p><p>Since, 2 predictions are correct out of 4, accuracy =2/4 = 0.5 or 50%. <strong>Can we conclude that if the accuracy of the model is good, the model is adequate?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EYfi-m8LTrw571mxqbXEg.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/brown-paper-with-handwritten-text-3826681/">cottonbro</a>, from Pexels</figcaption></figure><p>There are some loopholes in the accuracy performance metric:</p><ol><li>Imbalanced data</li><li>When the model gives probability scores</li></ol><h4>1. Imbalanced Data</h4><p>The example discussed above is having an equal proportion of the data points of both the classes. This type of dataset, where data points are approximately equal for both the classes, is called a balanced dataset.</p><p>What if we have an imbalanced dataset (where the number of points of one class is much greater than the other class)? An imbalanced dataset is extremely common in real-world examples. Datasets of rare diseases have very few positive people as compared to the negative ones.</p><p><strong>EXAMPLE</strong></p><p>The total number of patients is 100, and 95 out of them are positive (this is an imbalanced dataset). Let’s say the machine learning model is dumb, and it gives positive output only.</p><p>Now, what will be the accuracy?</p><p>The model will correctly classify 95 points out of 100. We will get an accuracy of 95%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-o_BWo_XHL3nmq0CmiiVA.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/amazed-formal-male-looking-at-laptop-screen-3760809/">Andrea Piacquadio</a>, from Pexels</figcaption></figure><p><strong>DON’T GET TOO EXCITED</strong>; remember, the model is dumb.</p><p><strong>Accuracy can be misleading when dealing with imbalanced data.</strong> Therefore, it’s better not to use an accuracy performance metric with imbalanced data.</p><h4>2. When the model gives probability scores</h4><p>Let’s say we have three models A, B, C, for binary classification, and all the three models give output as a probability score. In this example, we have used threshold as 0.5, i.e., if probability &gt; 0.5 — prediction will be 1, else 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*FMcgJ4QfnTD4ItI6EmJu3w.png" /><figcaption>A, B, and C model with probabilistic score and the prediction based on a threshold of 0.5</figcaption></figure><p>Based on the threshold, all three models are giving an accuracy of 100%. <strong>But can you deduce which model is best to use based on accuracy just looking at the prediction?</strong></p><p><strong>NO</strong></p><p>Therefore, accuracy is inadequate to compare models when the models give probability as the output.</p><h4>CONCLUSION</h4><p>In this article, we have seen the use of accuracy performance metrics in the classification task. The accuracy metric is not appropriate when dealing with imbalanced data and when models give the probability score. These problems of accuracy can be overcome by other performance metrics such as confusion matrix, precision, recall, and F1 score, which will be discussed in the next article.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=118f728d328f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/performance-metrics-accuracy-118f728d328f">Performance Metrics: Accuracy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Outlier Factor (LOF) — Algorithm for outlier identification]]></title>
            <link>https://medium.com/data-science/local-outlier-factor-lof-algorithm-for-outlier-identification-8efb887d9843?source=rss-8fd8456ab811------2</link>
            <guid isPermaLink="false">https://medium.com/p/8efb887d9843</guid>
            <category><![CDATA[local-outlier-factor]]></category>
            <category><![CDATA[outlier-identification]]></category>
            <dc:creator><![CDATA[Vaibhav Jayaswal]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 03:48:30 GMT</pubDate>
            <atom:updated>2020-11-09T13:53:42.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Local Outlier Factor (LOF) — Algorithm for outlier identification</h3><h4>Detection of the anomaly using LOF values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOAscxYYe3cX4pY7PZEfFg.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/crowd-reflection-color-toy-1679618/">Markus Spiske</a>, from Pexels</figcaption></figure><h3>Table of Contents:</h3><ol><li>INTRODUCTION</li><li>K-DISTANCE AND K-NEIGHBORS</li><li>REACHABILITY DISTANCE (RD)</li><li>LOCAL REACHABILITY DISTANCE (LRD)</li><li>LOCAL OUTLIER FACTOR (LOF)</li><li>EXAMPLE</li><li>ADVANTAGES OF LOF</li><li>DISADVANTAGES OF LOF</li><li>CONCLUSION</li><li>REFERENCES</li></ol><h4>1. INTRODUCTION</h4><p>An outlier is a data point that is different or far from the rest of the data points. The question that arises here is that can we identify the outliers present in the data?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZDvQFJRVQ34Gm5E5hLnnw.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/photo/board-game-box-business-card-262028/">Pixabay</a>, from Pexels</figcaption></figure><p>Local outlier factor (LOF) is an algorithm that identifies the outliers present in the dataset. But what does the <strong>local outlier </strong>mean?</p><p>When a point is considered as an outlier based on its local neighborhood, it is a <strong>local outlier</strong>. LOF will identify an outlier considering the density of the neighborhood. LOF performs well when the density of the data is not the same throughout the dataset.</p><p>To understand LOF, we have to learn a few concepts sequentially:</p><ul><li>K-distance and K-neighbors</li><li>Reachability distance (RD)</li><li>Local reachability density (LRD)</li><li>Local Outlier Factor (LOF)</li></ul><h4>2. K-DISTANCE AND K-NEIGHBORS</h4><p><strong>K-distance</strong> is the distance between the point, and it’s Kᵗʰ nearest neighbor. <strong>K-neighbors</strong> denoted by Nₖ(A) includes a set of points that lie in or on the circle of radius K-distance. K-neighbors can be more than or equal to the value of K. How’s this possible?</p><p>We’ll see an example. Let’s say we have four points A, B, C, and D (shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*kOwduufhfK0yWWd3N4r5rQ.png" /><figcaption>K-distance of A with K=2</figcaption></figure><p>If K=2, K-neighbors of A will be C, B, and D. Here, the value of K=2 but the ||N₂(A)|| = 3. Therefore, ||Nₖ(point)|| will always be greater than or equal to K.</p><h4>3. REACHABILITY DENSITY (RD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*y-Hod8WRK7BARmVRtIOg4g.png" /></figure><p>It is defined as the maximum of K-distance of Xj and the distance between Xi and Xj. The distance measure is problem-specific (Euclidean, Manhattan, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*zrk0QWDm7SXq2Iu69YnSFQ.png" /><figcaption>Illustration of reachability distance with K=2</figcaption></figure><p>In layman terms, if a point Xi lies within the K-neighbors of Xj, the reachability distance will be K-distance of Xj (blue line), else reachability distance will be the distance between Xi and Xj (orange line).</p><h4>4. LOCAL REACHABILITY DENSITY (LRD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*vXEtLH96HJKJHfzd5EwC0A.png" /></figure><p>LRD is inverse of the average reachability distance of A from its neighbors. Intuitively according to LRD formula, more the average reachability distance (i.e., neighbors are far from the point), less density of points are present around a particular point. This tells how far a point is from the nearest cluster of points. Low values of LRD implies that the closest cluster is far from the point.</p><h4>5. LOCAL OUTLIER FACTOR (LOF)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Jb2EFtlflLa6jAklVAQy9A.png" /></figure><p>LRD of each point is used to compare with the average LRD of its K neighbors. LOF is the ratio of the average LRD of the K neighbors of A to the LRD of A.</p><p>Intuitively, if the point is not an outlier (inlier), the ratio of average LRD of neighbors is approximately equal to the LRD of a point (because the density of a point and its neighbors are roughly equal). In that case, LOF is nearly equal to 1. On the other hand, if the point is an outlier, the LRD of a point is less than the average LRD of neighbors. Then LOF value will be high.</p><p>Generally, if LOF&gt; 1, it is considered as an outlier, but that is not always true. Let’s say we know that we only have one outlier in the data, then we take the maximum LOF value among all the LOF values, and the point corresponding to the maximum LOF value will be considered as an outlier.</p><h4>6. EXAMPLE</h4><p>4 points: A(0,0), B(1,0), C(1,1) and D(0,3) and K=2. We will use LOF to detect one outlier among these 4 points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*YSXLLWozQ5h0IoVN2F4IOw.png" /><figcaption>A(0,0), B(1,0), C(1,1), and D(0,3)</figcaption></figure><p>Following the procedure discussed above:</p><p>First, calculate the <strong>K-distance</strong>, <strong>distance between each pair</strong> <strong>of points</strong>, and <strong>K-neighborhood</strong> of all the points with K=2. We will be using <strong>Manhattan distance</strong> as a measure of distance.</p><p>K-distance(A) –&gt; since C is the 2ᴺᴰ nearest neighbor of A –&gt; distance(A, C) =2<br>K-distance(B) –&gt; since A, C are the 2ᴺᴰ nearest neighbor of B –&gt; distance(B,C) OR distance(B,A) = 1<br>K-distance(C) –&gt; since A is the 2ᴺᴰ nearest neighbor of C –&gt; distance(C,A) =2<br>K-distance(D) –&gt; since A,C are the 2ᴺᴰ nearest neighbor of D –&gt; distance(D,A) or distance(D,C) =3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*NygDyHNIDZjiU-2PUnieQQ.png" /></figure><p>K-neighborhood (A) = {B,C} , ||N2(A)|| =2<br>K-neighborhood (B) = {A,C}, ||N2(B)|| =2<br>K-neighborhood (C)= {B,A}, ||N2(C)|| =2<br>K-neighborhood (D) = {A,C}, ||N2(D)|| =2</p><p>K-distance, the distance between each pair of points, and K-neighborhood will be used to calculate LRD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*I-j2pTnIf2FAwhyA0llMew.png" /><figcaption>LRD for each point A, B, C, and D</figcaption></figure><p>Local reachability density (LRD) will be used to calculate the Local Outlier Factor (LOF).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*gOONbPWNC7FMcODIpyVgFA.png" /><figcaption>LOF for each point A, B, C, and D</figcaption></figure><p>Highest LOF among the four points is LOF(D). Therefore, D is an outlier.</p><h4>7. ADVANTAGES OF LOF</h4><p>A point will be considered as an outlier if it is at a small distance to the extremely dense cluster. The global approach may not consider that point as an outlier. But the LOF can effectively identify the local outliers.</p><h4>8. DISADVANTAGES OF LOF</h4><p>Since LOF is a ratio, it is tough to interpret. There is no specific threshold value above which a point is defined as an outlier. The identification of an outlier is dependent on the problem and the user.</p><h4>9. CONCLUSION</h4><p>Local outlier factor (LOF) values identify an outlier based on the local neighborhood. It gives better results than the global approach to find outliers. Since there is no threshold value of LOF, the selection of a point as an outlier is user-dependent.</p><h4>10. REFERENCES</h4><p>Breunig, M. M., Kriegel, H. P., Ng, R. T., and Sander, J. (2000). LOF: identifying density-based local outliers. In <em>ACM sigmod record</em> (Vol. 29, №2, pp. 93–104). ACM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8efb887d9843" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/local-outlier-factor-lof-algorithm-for-outlier-identification-8efb887d9843">Local Outlier Factor (LOF) — Algorithm for outlier identification</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>