<?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 Pulkit Ratna Ganjeer on Medium]]></title>
        <description><![CDATA[Stories by Pulkit Ratna Ganjeer on Medium]]></description>
        <link>https://medium.com/@pulkitratnaganjeer?source=rss-8799db75c0a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ck7jyszcSkj5vj9s.jpg</url>
            <title>Stories by Pulkit Ratna Ganjeer on Medium</title>
            <link>https://medium.com/@pulkitratnaganjeer?source=rss-8799db75c0a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:56:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pulkitratnaganjeer/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[Jigsaw Unintended Bias in Toxicity Classification]]></title>
            <link>https://pulkitratnaganjeer.medium.com/jigsaw-unintended-bias-in-toxicity-classification-367ff78aba79?source=rss-8799db75c0a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/367ff78aba79</guid>
            <category><![CDATA[toxicity]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Pulkit Ratna Ganjeer]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 01:37:28 GMT</pubDate>
            <atom:updated>2022-04-22T01:37:28.912Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, social media platforms have become an important place that provides an environment for its users, for expressing their thoughts and ideas, sharing content, and doing social interaction. Unfortunately, toxicity has become a serious issue affecting a wide range of users causing different psychological problems like depression and even suicidality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8jFGs4RT-kQfkG27j7MhA.jpeg" /><figcaption><a href="https://www.gettyimages.in/detail/illustration/the-guy-is-discussed-and-insulted-on-social-royalty-free-illustration/1167181868?adppopup=true">Image Source: gettyimages</a></figcaption></figure><p>Toxicity in online conversation can be defined as anything rude, disrespectful, troll, or anything else that is likely to initiate a discussion, offend someone, spread hatred and/or false information, etc. Toxicity online poses a serious challenge for platforms and publishers. Online abuse and harassment suppress important voices in conversation, forcing already marginalized people offline.</p><p>The prevalence of online toxicity has been growing rapidly in recent years, and the problem is a major concern. In some cases, toxic comments online have even caused real-life violence.</p><p>Social media platforms depend on thousands of human reviewers who struggle to moderate the ever-increasing volume of toxicity. In 2019, it was reported that Facebook moderators are at risk of suffering from PTSD (post-traumatic stress disorder) as a result of repeated exposure to such distressing content.</p><p>Hence, solving this problem by machine learning can help manage the rising volume of toxicity while limiting human exposure to it, and help mitigate toxicity and ensure healthy conversations online.</p><h3>Table of Contents</h3><ol><li><a href="#ce64">Prerequisites</a></li><li><a href="#8c70">Business Problem</a></li><li><a href="#3778">Machine Learning Formulation of the Business Problem</a></li><li><a href="#8fec">Business Constraints</a></li><li><a href="#5509">Source of Data</a></li><li><a href="#5111">Performance Metrics</a></li><li><a href="#fc16">Existing Approaches and Improvements over them</a></li><li><a href="#2bd6">Exploratory Data Analysis (EDA)</a></li><li><a href="#b8e3">Data Pre-processing</a></li><li><a href="#f12f">Deep Learning Models</a></li><li><a href="#94c4">Comparison of Models</a></li><li><a href="#8ca9">Final Model</a></li><li><a href="#d85a">Deployment</a></li><li><a href="#1fdb">Kaggle Score</a></li><li><a href="#ec40">Future Work</a></li><li><a href="#5b21">References</a></li><li><a href="#ab75">GitHub Repository</a></li><li><a href="#46e4">LinkedIn</a></li></ol><h3>Prerequisites</h3><ol><li>Understanding of Statistical Concepts/Plots.</li><li>Concepts of Deep Learning topics like <br>i. Neural Networks and their layers.<br>ii. Recurrent Neural Network-based models like LSTM.<br>iii. Attention Mechanism.<br>iv. Transformer-based models like BERT.</li></ol><h3>Business Problem</h3><p>Jigsaw hosted a competition in 2018 called “<a href="https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/overview">Toxic Comment Classification Challenge</a>” which aimed to identify the toxicity in a given comment. The problem was expected to build a model that should detect different kinds of toxicity like toxic, severe toxic, obscene, threat, insult, and identity hate, by predicting the probability of each type of toxicity for each comment. The dataset included a large set of Wikipedia comments labeled by humans for toxic behavior. However, it was observed that the models trained on the dataset show some biases towards minority groups. For example, the sentence “I am a black man” shows toxicity of 80%, and the sentence “I am a man” shows toxicity of 20%. Such bias happened because the dataset was prepared from sources where unfortunately certain identities like “black” are referred to in offensive ways.</p><p>To overcome such unintended bias problem, Jigsaw hosted another competition in the year 2019 called “<a href="https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification/overview">Jigsaw Unintended Bias in Toxicity Classification</a>” with the intent to detect toxic comments and minimize the unintended model bias. To solve this problem, a machine learning solution can be used to cater to a variety of different use cases, in comment sections, forums, or any text-based conversations. This case study aims to use machine learning to identify toxic comments without any bias, making it easier to host better conversations online.</p><h3>Machine Learning Formulation of the Business Problem</h3><p>The problem can be projected into a binary classification task of determining whether a given text is toxic or not, along with providing the likelihood probability of toxicity in the given text. Given the dataset containing comments and labels for identity mentions, we need to build a model that would recognize toxicity and minimize unintended bias for mentions of identities, by optimizing a metric designed to measure unintended bias.</p><h3>Business Constraints</h3><ol><li><strong>Low Latency Requirement</strong>: As the toxicity score can be given as feedback to the commenters as soon as they write something, low latency is required so that it can help a commenter know whether the text typed by him, has any toxicity or not.</li><li><strong>Class Probabilities</strong>: It would be better to provide the toxicity score which represents the percentage or likelihood that someone will perceive the given text as toxic.</li><li><strong>Minimum Unintended Bias</strong>: To overcome the problems in the Jigsaw competition of 2018, it is of utmost importance for the model to minimize any unintended bias while predicting the toxicity. The suggested metric by Jigsaw would help in considering this constraint.</li></ol><h3>Source of Data</h3><p>The data is taken from the Kaggle Competition:</p><p><a href="https://www.kaggle.com/competitions/jigsaw-unintended-bias-in-toxicity-classification/data">Jigsaw Unintended Bias in Toxicity Classification</a></p><p>The distribution of the dataset between toxic and non-toxic comments is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*-nfBktYpUh-tt2GR4yMFDQ.jpeg" /><figcaption>Dataset Distribution between toxic and non-toxic comments</figcaption></figure><h4>Dataset Details</h4><p>There are three files:</p><ol><li><strong>train.csv</strong>: Training dataset containing comment text, toxicity label, subgroup, and identities.</li><li><strong>test.csv</strong>: Test dataset containing only the comment text for which the toxicity has to be found, without any toxicity labels, subgroups, or identities.</li><li><strong>sample_submission.csv</strong>: A sample submission file in the correct format to be submitted for leaderboard scores.</li></ol><h4>Column Details</h4><p>The training dataset contains 45 columns/attributes:</p><ol><li><strong>id</strong>: Unique identifier for comment text in training and test dataset.</li><li><strong>target</strong>: Each comment in the training dataset has a toxicity label representing the fraction of human raters/annotators who believed the given comment was toxic. This has to be found out for the test dataset.</li><li><strong>comment_text</strong>: Text of the comments.</li><li><strong>Subgroup or Toxicity Subtype Attributes</strong>: Represents subtypes of toxicity. The following 6 subgroups are available: severity_toxicity, obscene, threat, insult, identity_attack, and sexual_explicit. The model does not need to predict these attributes.</li><li><strong>Identity Attributes</strong>: Represents various identities mentioned in the comment. A total of 24 identities are given in the training dataset: <strong>male</strong>, <strong>female</strong>, transgender, other_gender, heterosexual, <strong>homosexual_gay_or_lesbian</strong>, bisexual, other_sexual_orientation, <strong>christian</strong>, <strong>jewish</strong>, <strong>muslim</strong>, hindu, buddhist, atheist, other_religion, <strong>black</strong>, <strong>white</strong>, asian, latino, other_race_or_ethinicity, physical_disability, intellectual_or_learning_disability, <strong>psychiatric_or_mental_illness</strong>, and other_disability. <br>Out of these 24 identity attributes, only identities (shown in bold) with more than 500 examples in the test dataset will be included in the evaluation calculation. Hence, we will consider only the attributes: male, female, homosexual_gay_or_lesbian, christian, jewish, muslim, black, white, and psychiatric_or_mental_illness.</li><li>In addition to the attributes described above, the training dataset also provides metadata from Jigsaw’s annotation: toxicity_annotator_count and identity_annotator_count, and metadata from Civil Comments: created_date, publication_id, parent_id, article_id, rating, funny, wow, sad, likes, and disagree.</li></ol><h3>Performance Metrics</h3><p>In this case study, a newly developed custom metric has already been given, which combines several sub metrics to balance overall performance with various aspects of unintended bias.</p><p><strong>Source</strong>: <a href="https://www.kaggle.com/competitions/jigsaw-unintended-bias-in-toxicity-classification/overview/evaluation">Kaggle Evaluation</a></p><p>Before we define the final metric, let’s define each sub-metric.</p><h4>1. Overall AUC</h4><p>This is the ROC-AUC for the full evaluation set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/685523c9f72ccc5b1d1569556498bed2/href">https://medium.com/media/685523c9f72ccc5b1d1569556498bed2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf792d1dc2374472c2cbb3e679e43d4/href">https://medium.com/media/baf792d1dc2374472c2cbb3e679e43d4/href</a></iframe><h4>2. Bias AUCs</h4><p>To measure the unintended bias, we again calculate the ROC-AUC, on three specific subsets of the test dataset for each identity, each capturing a different aspect of unintended bias.</p><p>The below figure will help in understanding the terms used in the Bias AUC sub-metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*YcrtgAqczfi4XbRdvP7ubQ.jpeg" /><figcaption>Different Subgroups in the Dataset</figcaption></figure><h4>2.1. Subgroup AUC</h4><p>Here, we restrict the data set to only the examples that mention the specific identity subgroup. <em>A low value in this metric means the model does a poor job of distinguishing between toxic and non-toxic comments that mention the identity</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f89462e5ef7318d93f7aac9ec66e4714/href">https://medium.com/media/f89462e5ef7318d93f7aac9ec66e4714/href</a></iframe><h4>2.2. BPSN (Background Positive, Subgroup Negative) AUC</h4><p>Here, we restrict the test set to the non-toxic examples that mention the identity and the toxic examples that do not. <em>A low value in this metric means that the model confuses non-toxic examples that mention the identity with toxic examples that do not</em>, likely meaning that the model predicts higher toxicity scores than it should for non-toxic examples mentioning the identity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79ae6d06d2c76f0231dcfaae403be495/href">https://medium.com/media/79ae6d06d2c76f0231dcfaae403be495/href</a></iframe><h4>2.3. BNSP (Background Negative, Subgroup Positive) AUC</h4><p>Here, we restrict the test set to the toxic examples that mention the identity and the non-toxic examples that do not. <em>A low value here means that the model confuses toxic examples that mention the identity with non-toxic examples that do not</em>, likely meaning that the model predicts lower toxicity scores than it should for toxic examples mentioning the identity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1869e1c2ef5ab1a4ed9067a350f94da/href">https://medium.com/media/c1869e1c2ef5ab1a4ed9067a350f94da/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/792a00d7d7b12e56abc7e5c7d6045781/href">https://medium.com/media/792a00d7d7b12e56abc7e5c7d6045781/href</a></iframe><h4>3. Generalized Mean of Bias AUCs</h4><p>To combine the per-identity Bias AUCs into one overall measure, we calculate their generalized mean as defined below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*OluvW6FCoIPvMdyzjiQCyg.jpeg" /><figcaption>Generalized Mean of Bias AUCs (<a href="https://www.kaggle.com/competitions/jigsaw-unintended-bias-in-toxicity-classification/overview/evaluation">Source</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85755e1956933f830031bad28d4443a9/href">https://medium.com/media/85755e1956933f830031bad28d4443a9/href</a></iframe><h4>4. Final Metric</h4><p>We combine the overall AUC with the generalized mean of the Bias AUCs to calculate the final model score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*ES752T88Q3zHfAdHl0cPNA.jpeg" /><figcaption>Final Metric (<a href="https://www.kaggle.com/competitions/jigsaw-unintended-bias-in-toxicity-classification/overview/evaluation">Source</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b3e3f0be150f83ea856006ed829dab9/href">https://medium.com/media/0b3e3f0be150f83ea856006ed829dab9/href</a></iframe><h3>Existing Approaches and Improvements over them</h3><p>There are some existing solutions and research work on the problem that has been given in the references. The existing solutions use simple LSTM/GRU and CNN architecture to solve the problem.</p><p>In this solution, we would use complex architectures using bidirectional LSTM layers. Also, we would try the BERT model to extract the vector representation of the comment texts and use them as features in an MLP network.</p><h3>Exploratory Data Analysis (EDA)</h3><p>Exploratory Data Analysis (EDA) helps in analyzing the data using simple tools from statistics, plots, linear algebra, and others.</p><p>In EDA, we plot different graphs for getting a better understanding of the data. Let’s start doing the EDA on various features available in the training dataset to understand the dataset better.</p><p>There are various features in the training dataset like comment text, toxicity (target), toxicity subgroups, identities, and other metadata. In the test dataset, only two features are available viz., id and comment_text, which implies that we will just have the comment text available when predicting the toxicity in real-time.</p><h4><strong>1. EDA of ‘Target’ Class Label</strong>:</h4><p><strong>1.1. PDF and Box Plot of the data in the ‘Target’ Class</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcNDNCJRme5qVaL10RKT0Q.png" /><figcaption>Histogram/PDF and Box Plot of the data in the ‘Target’ Class Label</figcaption></figure><p><strong>Observation from the Histogram/PDF and Box Plot of the ‘Target’ Class Label</strong>:</p><ul><li>Most of the comments have 0 toxicity.</li><li>75% of the data have a toxicity of less than 0.2 ⟹ non-toxic comments.</li><li>The majority of the comments have a toxicity of less than 0.5 ⟹ non-toxic comments.</li><li>Very few comments have toxicity greater than 0.5 ⟹ toxic comments.</li></ul><p><strong>1.2. Count Plot and Pie Chart of the ‘Target’ Class</strong>:<br>Let’s plot the Count Plot for the ‘target’ class to see the number of comments in each category (toxic and non-toxic).</p><ul><li>We will consider the comments as toxic if the toxicity is greater than or equal to 0.5, otherwise non-toxic.</li><li>Let’s create a new feature called ‘IsToxic’ to indicate the class label has two values:<br> i. 1 ⟹ toxic comment (toxicity ≥ 5).<br> ii. 0 ⟹ non-toxic comment (toxicity &lt; 5).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*123jgxfdPEt1w0wOFEd7Yg.png" /><figcaption>Distribution of Class Labels (Toxic and Non-toxic)</figcaption></figure><p><strong>Observation from the Count Plot of the Class Label</strong>:</p><ul><li>The dataset is <strong>highly imbalanced</strong> with 92% non-toxic comments and 8% toxic comments.</li></ul><h4>2. Multi-variate Analysis of the Toxicity Subtype Features:</h4><ul><li>Here, we will do some multi-variate analysis of the various Subgroups or Toxicity Subgroup attributes.</li><li>These attributes represent the subtype of toxicity.</li><li>There are 6 toxicity subgroup attributes available viz., severe_toxicity, obscene, threat, insult, identity_attack, and sexual_explicit.</li><li>In the given problem, the model does not need to predict these attributes. Otherwise, the problem would have been a multi-label classification problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xh4DbyclX0BmRVw_bZg2A.jpeg" /><figcaption>PDF of the data in various Toxicity Subgroups</figcaption></figure><p><strong>Observation from the PDF of data in various Toxicity Subgroups</strong>:</p><ul><li>From the PDF, we can see that most of the toxicity subgroup ‘severe_toxicity’ are 0 ⟹ In the training data, comments are least categorized as ‘severe_toxicity’ by the annotators.</li><li>Let’s plot the percentage of subgroups having maximum toxicity in a toxic comment. In other words, we will consider and count only the toxicity subgroup having a maximum score in a particular comment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdoRkCFqfULJmoQFk7AYRA.jpeg" /><figcaption>Percentage of Toxicity Subgroups having maximum Toxicity Score in a comment</figcaption></figure><p><strong>Observation from the above plot</strong>:</p><ul><li>We can see that 79.23% of the toxic comments are of ‘insult’ type, followed by little percentages of ‘identity_attack’, ‘obscene’, and others.</li><li>A negligible portion (0.02%) of toxic comments are of ‘severe_toxicity’ type.</li><li>Based on the above count plot, we could have considered creating a new feature called ‘IsInsult’ in doing the classification, due to its huge contribution to the toxic comment. However, we won’t get any information related to the toxicity subgroup from the test data. Hence, we would skip this feature.</li></ul><h4>3. Multi-variate Analysis of the Identity Features:</h4><ul><li>Here, we will do some multi-variate analysis of the various Identity attributes that represent various identities mentioned in the comments.</li><li>There are 24 identity features in the training dataset viz., <strong>male</strong>, <strong>female</strong>, transgender, other_gender, heterosexual, <strong>homosexual_gay_or_lesbian</strong>, bisexual, other_sexual_orientation, <strong>christian</strong>, <strong>jewish</strong>, <strong>muslim</strong>, hindu, buddhist, atheist, other_religion, <strong>black</strong>, <strong>white</strong>, asian, latino, other_race_or_ethinicity, physical_disability, intellectual_or_learning_disability, <strong>psychiatric_or_mental_illness</strong>, and other_disability.</li><li>Out of these 24 identity attributes, only 9 identities (shown in bold) with more than 500 examples in the test dataset will be included in the evaluation calculation.</li><li>Hence, we will consider only these 9 from the identity features for doing the EDA.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ckcWUHLVXHEuYrTEAyN9cA.png" /><figcaption>PDF of the data in various Identity Subgroups</figcaption></figure><p><strong>Observation from the PDF of the data in various Identity Subgroups</strong>:</p><ul><li>From the above PDF, we can observe that the identity ‘psychiatric_or_mental_illness’ has the highest peak at 0 ⟹ ‘psychiatric_or_mental_illness’ is the least mentioned identity in the comments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*u-xe51Gki4RB2AeY8_PKyw.png" /><figcaption>Count Plot of various Identity Subgroups</figcaption></figure><p><strong>Observation from the Count Plot of various Identity Subgroups</strong>:</p><ul><li>‘female’ is the most occurring identity in the toxic comments, followed by the identities: ‘male’, ‘white’, ‘muslim’, and so on.</li></ul><h4>4. Uni-variate Analysis of the Comment Texts:</h4><ul><li>Here, we will perform various EDA on the comment texts which is the most important feature in the whole dataset.</li></ul><p><strong>4.1. Plot number of comments per toxic class</strong>:</p><ul><li>Let’s draw a count plot to view the number of toxic comments as well as the number of comments in each toxic subgroup where the score is greater than or equal to 50% (≥ 0.5).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*_M0Nt5UuiPBVOvlzoFJ1Yg.png" /><figcaption>Number of comments per toxic/target class and per each toxicity subgroups</figcaption></figure><p><strong>Observation from the above plot</strong>:</p><ul><li>There are a total of 1,44,334 toxic comments.</li><li>From the toxic subgroups, ‘insult’ has been attributed in maximum comments by a minimum of 50% of annotators.</li><li>Rest all toxic subgroups are less annotated.</li><li>‘severe_toxicity’ subgroup is the least attributed subgroup annotated by any annotators.</li></ul><p><strong>4.2. Trend Graph of the number of comments over time</strong>:</p><ul><li>Here, we will plot the distribution of comments over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*6wZaoepiMfpdYd2G0slbIQ.png" /><figcaption>Trend Graph of the number of comments raised over time</figcaption></figure><p><strong>Observation from the trend of toxic comments raised over time</strong>:</p><ul><li>We can see an overall upward trend in the number of toxic comments raised over time.</li><li>There is a slight dip after Jan 2017 but the trend increases again after April 2017.</li><li>The maximum number of toxic comments was raised in October 2017.</li><li>There is a drastic fall after October 2017 in the next month. This could be due to the unavailability of the data from Nov 2017 and onwards.</li><li>Let’s try to plot a similar trend graph for various types of toxicity subgroups.</li><li>However, if we just consider the toxicity score to be greater than 0.5 for each of the subgroups, there is negligible data and the graph does not show any trend.</li><li>Hence, we will plot the trend graph for the toxicity subgroups considering a non-zero score i.e., even if at least one annotator believed the comment to be of any specific toxicity, we would consider them in the trend graph.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*dvc6EGr3mxtQJVb0TSgaFQ.png" /><figcaption>Trend Graph of the number of comments for each Toxicity Subgroup raised over time</figcaption></figure><p><strong>Observation from the trend of various Toxicity Subgroup comments raised over time</strong>:</p><ul><li>The trend for all the toxicity subgroup comments follow a similar pattern.</li><li>The comments marked as ‘insult’ show a significant increase over any other kind of comments.</li></ul><p><strong>4.3. Plot the distribution of comments’ length</strong>:</p><ul><li>Here, we will plot the distribution of the length of the comments for both toxic and non-toxic classes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DLojGEGPTIji36a-jIk9w.png" /><figcaption>Histogram/PDF and Bot Plot of the distribution of comments’ length class label wise</figcaption></figure><p><strong>Observation from the distribution of comments’ length</strong>:</p><ul><li>The comment lengths follow a similar distribution for both toxic and non-toxic classes.</li><li>Most of the comments (either toxic or non-toxic) have lengths between 10 and 30.</li><li>Almost all comments have a length of fewer than 150 words. However, there are some outliers with comment lengths even up to 350+ words.</li></ul><p><strong>4.4. Word Cloud of the words in the Comments</strong>:</p><p><strong>4.4.1. Word Cloud based on the ‘Target’ Class</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*yMDfdSbxVbGpzp_dwySR9w.png" /><figcaption>Word Cloud of the words in Toxic Comments</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*HsFhzTCCHyS7QTUyDBkksQ.png" /><figcaption>Word Cloud of the words in Non-toxic Comments</figcaption></figure><p><strong>Observation from the Word Cloud of the words in Comment Texts based on Toxic and Non-toxic classes</strong>:</p><ul><li>In the toxic comments, ‘Trump’, ‘people’, and ‘like’ are the most often used words in the comment texts.</li><li>In the non-toxic comments, ‘people’ ‘one’ and ‘would’ are the most often used words.</li></ul><p><strong>4.4.2. Word Cloud based on the Toxicity Subgroups</strong></p><ul><li>Plot the word cloud of all the words in the comment text from various toxicity subgroup classes having scores greater than or equal to 0.5</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMRHQqJvzREd4EtgpltCxg.png" /><figcaption>Word Cloud of the words in all Toxicity Subgroups having toxicity score ≥ 0.5</figcaption></figure><p><strong>Observation from the Word Cloud of the words in Comment Texts in various Toxicity Subgroups</strong>:</p><ul><li>Most often used words based on the toxicity subgroup classes are as follows:<br> i. severe_toxic: kill, shit and time.<br> ii. obscene: people, get, like, would and crap.<br> iii. threat: kill and shoot.<br> iv. insult: Trump, people, like and one.<br> v. identity_attack: Muslim and black.<br> vi. sexual_explicit: sex and one.</li></ul><h3>Data Pre-processing</h3><p>As the primary data to be used in the model is text data and we would build various non-transformer-based models as well, we can perform some text pre-processing to clean the data.</p><p>The below set of text pre-processing operations have been performed:</p><ol><li><strong>Remove HTML Tags</strong>:<br>HTML Tags do not add much value to understanding and analyzing texts.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a48c00a8b55f571c0bf0e8826ef7c1f3/href">https://medium.com/media/a48c00a8b55f571c0bf0e8826ef7c1f3/href</a></iframe><p><strong>2. Remove Accented Characters</strong>:</p><ul><li>We may receive some accented characters/letters in comments. E.g., résumé, tête-à-tête, etc.</li><li>The most common accents are the acute (é), grave (è), circumflex (â, î or ô), tilde (ñ), umlaut, and dieresis (ü or ï — the same symbol is used for two different purposes), and cedilla (ç). Accent marks (also referred to as diacritics or diacriticals) usually appear above a character. (<a href="https://www.fonts.com/content/learning/fontology/level-3/signs-and-symbols/accents">Reference</a>)</li><li>We need to ensure that we convert and standardize such characters to ASCII characters.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830b54578e8430819ce80890c079d58f/href">https://medium.com/media/830b54578e8430819ce80890c079d58f/href</a></iframe><p><strong>3. Convert to Lowercase</strong>:</p><ul><li>Convert the comment text to lower case before doing further preprocessing.</li><li>Texts in lowercase help in the process of preprocessing and in later stages in NLP.</li><li>Converting the text to lowercase is pretty easy and can be done by the ‘.lower()’ method of a string.</li></ul><p><strong>4. Remove IP Address, Hyperlinks, and Numbers</strong>:</p><ul><li>Remove any IP Addresses, Hyperlinks, and numbers from the comment text as they won’t add any value to perform the toxicity classification.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47862d1d1217d540e162f7e97c54805b/href">https://medium.com/media/47862d1d1217d540e162f7e97c54805b/href</a></iframe><p><strong>5. Replace Emoticons with the corresponding words</strong>:</p><ul><li>Replace the emoticons with the corresponding words like “:-(” with “sad”.</li><li>The emoticons and their corresponding words have been referenced from <a href="https://pc.net/emoticons/">PC.net</a>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6cd772f4150bdded317109db4bb288c/href">https://medium.com/media/a6cd772f4150bdded317109db4bb288c/href</a></iframe><p><strong>6. Remove Special Characters</strong>:</p><p>Remove special characters except for the below four characters because we would use these characters in tokenization and embeddings due to their importance in a sentence:<br>i. Single quote: <strong>’ <br></strong>ii. Full stop (period): <strong>.</strong><br>iii. Question mark: <strong>?<br></strong>iv. Exclamation mark: <strong>!</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34d99def322a1697947f1e05f9aa2aab/href">https://medium.com/media/34d99def322a1697947f1e05f9aa2aab/href</a></iframe><p><strong>7. Add space around sentence end markers and remove duplicate markers</strong>:</p><ul><li>Add one space around sentence end markers and remove duplicate end markers.</li><li>If there are multiple same sentence end markers separated by space or without space, then a single end marker will be used and space between them will be removed.</li><li>For example:<br> i. ‘ !! ’ will be replaced with ‘ ! ’<br> ii. ‘ ? ? ’will be replaced with ‘ ? ’</li><li>This is done to not lose information about these markers at the stage of transformation of the text into a word embedding.</li><li>This can be omitted while using BERT.</li><li>The following end markers will be considered:<br>i. Full stop (period): <strong>.</strong><br>ii. Question mark: <strong>?<br></strong>iii. Exclamation mark: <strong>!</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2e8df558d4b39d9937ca1de885b819/href">https://medium.com/media/ca2e8df558d4b39d9937ca1de885b819/href</a></iframe><p><strong>8. Decontraction</strong>:</p><ul><li>A contraction, or short-form, is an abbreviated form of a word or words, from which one or more letters have been left out and replaced by an apostrophe. They are very common in English sentences. (<a href="https://typely.com/blogs/entry/15-how-to-use-english-contractions-correctly-with-word-list-and-examples/">Reference</a>)</li><li>For example:<br> i. I am ⟶ I’m.<br> ii. He is ⟶ He’s.<br> iii. It is ⟶ It’s.<br> iv. We will ⟶ We’ll.</li><li>We need to de-contract (opposite of contraction) the words to their original form, to help with text standardization.</li><li>Here we will use a dictionary (contraction map) containing the contracted form in its keys and their corresponding expanded form in its values. (<a href="https://github.com/dipanjanS/practical-machine-learning-with-python/blob/master/bonus%20content/nlp%20proven%20approach/contractions.py">Reference</a>)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/143fca54be6f73f06d58b3b2b2e5c28d/href">https://medium.com/media/143fca54be6f73f06d58b3b2b2e5c28d/href</a></iframe><h3>Deep Learning Models</h3><ul><li>To classify and find the toxicity in a given text, various deep learning models from simple architecture to more complex ones have been tried.</li><li>For text embeddings, <strong>GloVe</strong> Model has been used to generate a vector representation of a word and create an embedding matrix for all the words (tokens). This embedding matrix is used in the embedding layer to generate a vector representation of the given comment/sentence/text.</li><li>Sentence embedding using the state-of-the-art (SOTA) Transformer-based <strong>BERT</strong> model (DistilBert) has also been tried.</li><li>We will see the architecture of all the models tried and a brief about them.</li></ul><p><strong>1. CNN-based Models</strong></p><ul><li>Below are two 1D CNN-based architectures used for the baseline modeling:<br>i. One with one Input Layer for the tokenized texts.<br>ii. Other with two Input Layers, one for the tokenized texts and another for the numerical feature indicating the “number of words in the comment text”.</li><li>The architectures of both the models are shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bJT3pex0b_jSl_o1aGPAg.png" /><figcaption>CNN-based Model with one Input Layer for tokenized texts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTSj3lzMiGopa1qcclc0_Q.png" /><figcaption>CNN-based Model with one Input Layer for tokenized texts and another Input Layer for numerical feature</figcaption></figure><ul><li>The inclusion of the word count feature did not help in getting a better score. Hence, this feature has not been used in the later models.</li></ul><p><strong>2. Bidirectional LSTM-based Models</strong></p><ul><li>Below are the bidirectional LSTM-based models’ architecture with skip connections:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5ZXLtBBRRCLHPldmigcTQ.png" /><figcaption>Bidirectional LSTM Model with skip connection (Architecture 1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PXkn8VNM5unEUA-kzJtCg.png" /><figcaption>Bidirectional LSTM Architecture with skip connection (Architecture 2)</figcaption></figure><p><strong>3. Bidirectional LSTM-based Model with Attention Mechanism</strong></p><ul><li>Attention Layer using Bahdanu Attention Mechanism was used:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTdVn_lV_xzusxyWy2Ef6A.png" /><figcaption>Attention Mechanism (<a href="https://matthewmcateer.me/media/attention/additive_attention.png">Source</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSBhjzj8mxGgH650M2l_Zw.png" /><figcaption>Bidirectional LSTM Model with Attention Mechanism</figcaption></figure><p><strong>4. BERT Models</strong></p><ul><li>BERT (Bidirectional Encoder Representations from Transformers) is a SOTA transformer-based machine learning technique for the natural language process (NLP).</li><li>A lightweight BERT model called DistilBERT from Hugging Face Library was used to extract vector representation of the tokenized comment texts.</li><li>The comment texts were tokenized using DistilBERT Tokenizer first and then the text embedding was done on the tokenized texts using the DistilBERT Model ‘distilbert-base-uncased’.</li><li>The embedded vector was then passed to a simple Multi-level Perceptron Network (MLP).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*NWh-9laMaImM29cWptCOlA.png" /><figcaption>MLP Model using BERT embedded vectors as input</figcaption></figure><p><strong>5. Bidirectional LSTM Model with GloVe and BERT Features</strong></p><ul><li>The bidirectional LSTM Model was used with GloVe Embedding Layer and the output was combined with the BERT features, followed by skip connections.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKz2nMMgsldBWrosfa-oow.png" /><figcaption>Bidirectional LSTM Model with GloVe and BERT Features</figcaption></figure><h3>Comparison of Models</h3><ul><li>Various Deep Learning Models (discussed above) were trained and evaluated on the test dataset.</li><li>The table below shows a comparison between various models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*H-nyMGgLD7g2jwD-Yyipug.png" /><figcaption>Comparison of Models</figcaption></figure><ul><li><strong>Conclusion</strong>: As the Bidirectional LSTM Model with skip connections (Architecture 1) outperformed the other models, we have chosen it as the final model.</li></ul><h3>Final Model</h3><ul><li>The final model is chosen based on the evaluation score on the test dataset.</li><li>The final model is built using bidirectional LSTM layers followed by skip connections.</li><li>The architecture of the final model is shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5ZXLtBBRRCLHPldmigcTQ.png" /><figcaption>The architecture of the Final Model</figcaption></figure><ul><li>A sample code for building the architecture of the final model is shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afe05a78d255e4b59622c1a987974029/href">https://medium.com/media/afe05a78d255e4b59622c1a987974029/href</a></iframe><ul><li>The model was trained for 21 epochs but it was early stopped after the 11th epoch.</li><li>Below is the learning curve of the model over different epochs:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Fhe1yb8VC576PsIyvdU0eg.png" /><figcaption>Learning Curve of Loss and Accuracy w.r.t. epochs</figcaption></figure><h3>Deployment</h3><p>Flask API has been used to build REST APIs for the productionisation of the model.</p><p>The Web Application requires a comment text to be entered in a text area and shows the toxicity after prediction.</p><p>Below is the demo from localhost (which will be updated to show the demo from hosted environment later):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kezE11pr8cWOPURQdHrazw.gif" /><figcaption>Demo of the Model Prediction</figcaption></figure><h3>Kaggle Score</h3><p>The final score on the validation data came to be 0.92620.</p><p>Kaggle’s Score on the test data came as 0.92482.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Pg5-5PJYT4j-WbqahXD7Q.png" /><figcaption>Kaggle Score of the Final Model</figcaption></figure><h3>Future Work</h3><p>The future scope of this problem could be:</p><ul><li>Use a trainable embedding layer when using the GloVe Embedding Matrix.</li><li>Fine-tune the BERT Model. This could be resource-intensive.</li><li>Use a more advanced transformer-based model called <strong>XLNet</strong>, which overcomes the limitations of BERT.</li></ul><h3>References</h3><ol><li><a href="https://www.kaggle.com/code/dborkan/benchmark-kernel/notebook">Benchmark Kernel</a></li><li><a href="https://ieeexplore.ieee.org/document/8614166">Imbalance Toxic Comments Classification using Data Augmentation and Deep Learning</a></li><li><a href="https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1184/reports/6837517.pdf">Detecting and Classifying Toxic Comments</a></li><li><a href="https://ieeexplore.ieee.org/abstract/document/9087368">Avoiding Unintended Bias in Toxicity Classification with Neural Networks</a></li><li><a href="https://towardsdatascience.com/working-with-hugging-face-transformers-and-tf-2-0-89bf35e3555a">Working with Hugging Face Transformers and TF 2.0</a></li><li><a href="https://www.kdnuggets.com/2018/08/practitioners-guide-processing-understanding-text-2.html">Text Wrangling &amp; Pre-processing: A Practitioner’s Guide to NLP</a></li><li><a href="https://medium.com/jigsaw/helping-authors-understand-toxicity-one-comment-at-a-time-f8b43824cf41">Helping Authors Understand Toxicity, One Comment at a Time</a></li><li><a href="http://jalammar.github.io/a-visual-guide-to-using-bert-for-the-first-time/">A Visual Guide to Using BERT for the First Time</a></li><li><a href="https://matthewmcateer.me/blog/getting-started-with-attention-for-classification/">Getting started with Attention for Classification</a></li><li><a href="https://medium.com/the-artificial-impostor/notes-jigsaw-unintended-bias-in-toxicity-classification-fd6c8d3e7459">[Notes] Jigsaw Unintended Bias in Toxicity Classification</a></li><li><a href="https://www.appliedaicourse.com/">Applied Roots</a></li></ol><h3>GitHub Repository</h3><p><a href="https://github.com/pulkitratnaganjeer/ToxicityClassification">GitHub - pulkitratnaganjeer/ToxicityClassification</a></p><h3>LinkedIn</h3><p><a href="https://www.linkedin.com/in/pulkit-ganjeer-90047140/">Pulkit Ganjeer - Principal Software Engineer - emids | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=367ff78aba79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Healthcare Fraud Detection using Machine Learning]]></title>
            <link>https://pulkitratnaganjeer.medium.com/healthcare-fraud-detection-using-machine-learning-5996d63bd3c7?source=rss-8799db75c0a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5996d63bd3c7</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[classification-problem]]></category>
            <category><![CDATA[healthcare-fraud]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <dc:creator><![CDATA[Pulkit Ratna Ganjeer]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 10:43:03 GMT</pubDate>
            <atom:updated>2022-02-16T10:43:03.332Z</atom:updated>
            <content:encoded><![CDATA[<p>The US Healthcare System has become a major expenditure in recent years. According to a report by the GAO (General Accounting Office) to Congress in 2004, annual health care expenditures were approaching two trillion dollars, which accounted for 15.3% of the GDP (Gross Domestic Product). Both the size of the system and the humongous amount of money make it an attractive target for fraud.</p><figure><img alt="Healthcare Fraud" src="https://cdn-images-1.medium.com/max/1024/1*l3KxuPeT8UoM-Az6nksANQ.jpeg" /><figcaption><a href="https://www.johntfloyd.com/wp-content/uploads/2016/03/Dallas-Doctor-Used-Homeless-Patients-in-Healthcare-Fraud-Scheme.jpg">Image Source</a></figcaption></figure><p>Healthcare Fraud is one of the major problems in the US Healthcare System, and it leads to huge financial losses and also impacts the quality of healthcare facilities. The Payers or Insurance Agencies like Medicare, Medicaid, and other agencies have to spend more money, and to incur the financial losses, they have to decide to increase the insurance premium amount. Eventually, the healthcare system is becoming more and more expensive.</p><p>Not only is the financial loss a major concern, but fraud also severely hinders the quality of healthcare being provided to legitimate patients. There are ways of detecting fraud manually but it requires intensive medical research and is also too time-consuming.</p><p>Hence, effective fraud detection using sophisticated machine learning techniques along with aided medical domain expertise is very important for improving the quality and reducing the cost of healthcare services.</p><h3><strong>Table of Contents</strong></h3><ol><li><a href="#c2c4">Prerequisites</a></li><li><a href="#323e">Business Problem</a></li><li><a href="#75bf">Machine Learning Formulation of the Business Problem</a></li><li><a href="#c32c">Business Constraints</a></li><li><a href="#d2ec">Source of Data</a></li><li><a href="#cfb2">Performance Metrics</a></li><li><a href="#7c6e">Existing Approaches and Improvements over them</a></li><li><a href="#a85e">Exploratory Data Analysis (EDA)</a></li><li><a href="#93cf">Data Pre-processing</a></li><li><a href="#fa7e">Machine Learning Models — Hyperparameter Tuning and Model Training</a></li><li><a href="#aa92">Comparison of Models</a></li><li><a href="#1548">Model Interpretability</a></li><li><a href="#edb1">Deployment</a></li><li><a href="#90cc">Future Work</a></li><li><a href="#f21c">References</a></li><li><a href="#ff5a">GitHub Repository</a></li><li><a href="#0a26">LinkedIn</a></li></ol><h3><strong>Prerequisites</strong></h3><ol><li>Understanding of Statistical Concepts/Plots<em>.</em></li><li>Concepts of Machine Learning.</li></ol><h3>Business Problem</h3><p>Fraud, Waste, and Abuse have become one of the biggest concerns in the healthcare system of the United States and can be caused by different healthcare entities (<strong>3 Ps</strong>) viz, <strong>Patients </strong>(Insurance Subscriber/Beneficiary), Healthcare <strong>Providers </strong>(Hospitals, Physicians, Laboratories, Pharmacies, etc) and <strong>Payers </strong>(Insurance Providers like Medicare, Medicaid, and other agencies). Frauds can be caused by either a single entity or by a conspiracy of multiple entities. In this case study, we primarily focus on the frauds caused by the Providers as part of insurance claims submitted to the Insurance Agencies.</p><p>Many healthcare systems rely on domain experts to manually review insurance claims and detect potential frauds. There are hundreds of thousands to millions of claims data getting generated over time. Manual review of the claims is very time-consuming and challenging. To reduce such effort, various machine learning techniques can be leveraged to automate the manual processing of the claims and identify the potential frauds. Such a system would certainly help in reducing the cost, manual effort, processing &amp; review time, and other challenges in the system. This case study aims to solve the problem of detecting potential frauds in a healthcare system and assist in making the healthcare system better.</p><h3>Machine Learning Formulation of the Business Problem</h3><p>Identify the potential frauds made by the Providers, in the insurance claims submitted to the Insurance Agencies.</p><p>The problem can be projected into a <strong>binary classification task</strong> of determining whether the claim record(s) submitted by the Providers is/are fraudulent or legitimate. Given the data related to the Providers and the claim submitted by them, a Machine Learning Model can be built to determine whether a claim record is fraudulent or not.</p><h3>Business Constraints</h3><ol><li><strong>No Latency Requirement</strong>: As the current process of manually labeling the claims as fraudulent or not, takes much time, there won’t be a strict need to have a low-latency system for fraud detection. However, the time taken should be reasonable depending on the business need.</li><li><strong>Interpretability</strong>: Interpretability is very important as the machine learning model needs to justify why it classifies a claim as fraudulent or not. There could be legal proceedings involved on the Providers after identifying a fraudulent claim filed by them. Hence, it is of utmost importance that the Machine Learning Model gives proper justification in case of detecting fraud.<br>If a legitimate Provider is detected as fraud and has to undergo legal proceedings, it may plan to restrict its facility and cooperation with the Government, and the reachability of the healthcare systems will be compromised.</li><li><strong>Errors</strong>: False Negative Rate (FNR) should be as low as possible. In some healthcare systems which conduct some manual review after the machine classification, a slightly higher False Positive Rate (FPR) is acceptable. However, FNR should always be minimum, otherwise, the actual fraud Providers would escape and continue to impact the healthcare system.</li><li><strong>Class Probabilities</strong>: It would be better to provide class probabilities so that the user can know how probable a particular fraudulent claim is.</li></ol><h3>Source of Data</h3><p>The data is taken from Kaggle:</p><p><a href="https://www.kaggle.com/rohitrox/healthcare-provider-fraud-detection-analysis">HEALTHCARE PROVIDER FRAUD DETECTION ANALYSIS</a></p><h4><strong>Dataset Details</strong></h4><p>The dataset is present in the form of excel files and there are a total of eight files, four for each train and test data. These are:</p><ol><li><strong>Mapping Data</strong> (Train-1542865627584.csv and Test-1542969243754.csv): Contains the mapping of Provider’s unique id and the class label signifying whether the Provider is fraud or not. For the Test data, only the Provider’s unique id is given and the class label has to be found.</li><li><strong>Beneficiary Data</strong> (Train_Beneficiarydata-1542865627584.csv and Test_Beneficiarydata-1542969243754.csv): Contains the demographic, disease, premium, and reimbursement related information of the beneficiaries/patients.</li><li><strong>Inpatient Data</strong> (Train_Inpatientdata-1542865627584.csv and Test_Inpatientdata-1542969243754.csv): Provides the details of the claims filed for the patients who were admitted to the hospitals for their treatment.</li><li><strong>Outpatient Data</strong> (Train_Outpatientdata-1542865627584.csv and Test_Outpatientdata-1542969243754.csv): Provides the details related to the claims filed for the patients who visited the hospitals but were not admitted.</li></ol><h4>Column Details</h4><p>Each of the columns present in the excel sheets is described below:</p><ul><li><strong>Mapping Data<br></strong>Mapping Data is present for both training and testing.<br><strong>Train Data</strong>:<br>1. <strong>Provider</strong>: Unique identifier for a Provider (Hospital, Pharmacy, Laboratories, etc).<br>2. <strong>Potential Fraud</strong>: Class label to indicate whether the Provider is a fraud or not.<br><strong>Test Data</strong>: Test data only contains the unique identifier for a Provider and not a class label as the class label has to be found out.</li><li><strong>Beneficiary Data<br></strong>1. <strong>BeneID</strong>: Unique identifier of the patient/beneficiary who is registered to the health insurance provided by the Payer (Insurance Agencies like Medicare, Medicaid, and other agencies).<br>2. <strong>DOB</strong>: Date of birth of the beneficiary.<br>3. <strong>DOD</strong>: Date of death of the beneficiary in case the beneficiary is dead. Otherwise, this contains the NaN value.<br>4. <strong>Gender, Race, State, Country</strong>: Contains numeric code for gender, race, state, and country of the beneficiary.<br>5. <strong>RenalDiseaseIndicator</strong>: Flag to indicate whether the beneficiary has any problem related to kidney failure or not.<br>6. <strong>Chronic Condition columns</strong>: Indicate whether a beneficiary has a disease for more than a year and requires ongoing medical attention or limited activities of daily living or both. There are columns to indicate whether the beneficiary has chronic conditions related to Alzheimer’s, heart failure, kidney disease, cancer, obstructive pulmonary, depression, diabetes, ischemic heart disease, osteoporosis, rheumatoid arthritis, and stroke.<br>7. <strong>IPAnnualReimbursementAmt</strong>: annual amount reimbursed for the treatment of the beneficiary when admitted to the hospital.<br>8. <strong>IPAnnualDeductibleAmt</strong>: annual premium amount paid to the Insurance Agency towards the treatment of the beneficiary when he was admitted to the hospital.<br>9. <strong>OPAnnualReimbursementAmt</strong>: annual amount reimbursed for the treatment of the beneficiary when visited the hospital but not admitted.<br>10. <strong>OPAnnualDeductibleAmt</strong>: annual premium amount paid to the Insurance Agency towards the treatment of the beneficiary when he visited the hospital but was not admitted.</li><li><strong>Inpatient and Outpatient Data</strong>:<br>1. <strong>BeneID</strong>: Unique identifier of the beneficiary.<br>2. <strong>ClaimID</strong>: Unique identifier of the health insurance claim.<br>3. <strong>ClaimStartDt </strong>and <strong>ClaimEndDt</strong>: Dates indicating when the insurance claim was submitted and when it was settled and closed.<br>4. <strong>Provider</strong>: Unique identifier for a Provider.<br>5. <strong>InscClaimAmtReimbursed</strong>: Amount reimbursed by the Payer (Insurance Agency) for the healthcare services provided to the beneficiary.<br>6. <strong>Physicians-related columns</strong>: Columns showing the physicians who attended the beneficiary/patient, operated the patient, and any other physicians if any.<br>7. <strong>Admission and Discharge Date (Inpatient Data)</strong>: Columns showing the dates on which the beneficiary was admitted to the hospital and when he was discharged.<br>8. <strong>ClmAdmitDiagnosisCode</strong>: Diagnosis code indicating the beneficiary’s initial diagnosis at admission.<br>9. <strong>Claim Diagnosis Codes 1–10</strong>:<br><strong>ClmDiagnosisCode_1</strong>: Diagnosis code identifying the beneficiary’s principal diagnosis.<br><strong>ClmDiagnosisCode_2–10</strong>: Diagnosis code in the 2nd, 3rd, and so on, till the 10th position identifying the condition(s) for which the beneficiary is receiving care.<br>10. <strong>Claim Procedure Codes 1–6</strong>: Codes that indicate the principal or other procedures performed during the period covered by the institutional claim.<br>11. <strong>DiagnosisGroupCode (Inpatient Data)</strong>: Code to classify hospital cases according to certain groups, also referred to as DRGs, which are expected to have similar hospital resource use (cost).<br>12. <strong>DeductibleAmtPaid</strong>: Amount the beneficiary has to pay as part of the claim, and the rest of the amount is paid by the insurance company. It is equal to the total claim amount minus the reimbursed amount.</li></ul><h3>Performance Metrics</h3><p>To evaluate how well a Machine Learning Model is built, the below set of Performance Metrics is used.</p><p><strong>I. Binary Log Loss</strong>: Important metric when the ML Model gives the probability estimates. It lies in the range from zero to infinity. The lower the value, the better is the ML Model.<br>Given by the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GliMSslpPVlArOhQ7X3ePA.png" /><figcaption>Binary Log-loss</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfaa0d736a544fd514837657736a00e2/href">https://medium.com/media/bfaa0d736a544fd514837657736a00e2/href</a></iframe><p><strong>II. Performance Metric: Confusion Matrix and other related metrics</strong>:<br>We will use Confusion Matrix and derive different metrics from the values in the Confusion Matrix.<br>Confusion Matrix is a good metric for binary classification and also robust to class imbalance.<br>1. <strong>Confusion Matrix:<br></strong>A confusion matrix is a way of assessing the performance of a classification model. It is a comparison between the ground truth (actual values) and the predicted values emitted by the model for the target variable.</p><figure><img alt="Confusion Matrix" src="https://cdn-images-1.medium.com/max/373/1*ZpkTGQ-loHzTet_D6BMwKA.png" /><figcaption>Confusion Matrix</figcaption></figure><p>2. <strong>Precision Matrix</strong>:<br>Precision Matrix helps in knowing the Precision values which lie on the diagonal of the matrix.</p><figure><img alt="Precision Matrix" src="https://cdn-images-1.medium.com/max/374/1*hLtiB8NadIo3jwMB2dQ_lg.png" /><figcaption>Precision Matrix</figcaption></figure><p><strong>Precision </strong>or <strong>Positive Predicted Value (PPV) </strong>indicates “<em>Of all predicted positives, how many are actual positives</em>”.<br>Given by the equation:</p><figure><img alt="Precision or Positive Predicted Value" src="https://cdn-images-1.medium.com/max/1008/1*8vjoAScrPg2TlLPc70r9Wg.png" /><figcaption>Precision or Positive Predicted Value (PPV)</figcaption></figure><p>The other diagonal in the Precision Matrix tells “<em>Of all predicted negatives, how many are actual negatives</em>”.<br>Given by the equation:</p><figure><img alt="Negative Predicted Value" src="https://cdn-images-1.medium.com/max/1024/1*MbEDA_dkbpMikyfTJIHBgg.png" /><figcaption>Negative Predicted Value (NPV)</figcaption></figure><p>3. <strong>Recall Matrix</strong>:<br>Recall Matrix helps in knowing the Recall (or Sensitivity) and Specificity values, which lie on the diagonal elements.</p><figure><img alt="Recall Matrix" src="https://cdn-images-1.medium.com/max/372/1*3p7qyA3NzQM9vHMJ1XtQuQ.png" /><figcaption>Recall Matrix</figcaption></figure><p><strong>Recall/Sensitivity </strong>or <strong>True Positive Rate (TPR)</strong> indicates “<em>Of all actual positives, how many are predicted positives</em>”.<br>Given by the equation:</p><figure><img alt="Recall/Sensitivity or True Positive Rate" src="https://cdn-images-1.medium.com/max/358/1*QmebJlXI4gbgsCqvc9ECmw.png" /><figcaption>Recall/Sensitivity or True Positive Rate</figcaption></figure><p><strong>Specificity</strong> indicates “<em>Of all actual negatives, how many are predicted negatives</em>”.<br>Given by the equation:</p><figure><img alt="Specificity or True Negative Rate" src="https://cdn-images-1.medium.com/max/257/1*0UW5DkvOkl_P_lOOzcdKGg.png" /><figcaption>Specificity or True Negative Rate</figcaption></figure><p>4. <strong>False Positive Rate (FPR) </strong>and <strong>False Negative Rate (FNR)</strong>:<br><strong>Fall-out </strong>or <strong>False Positive Rate (FPR)</strong> indicates “<em>Of all actual negatives, how many are predicted positives</em>”.<br>Given by the equation:</p><figure><img alt="Fall-out or False Positive Rate" src="https://cdn-images-1.medium.com/max/154/1*1trq0k3rjMuyoXCbxIj34w.png" /><figcaption>Fall-out or False Positive Rate</figcaption></figure><p><strong>Miss rate </strong>or <strong>False Negative Rate (FNR)</strong> indicates “<em>Of all actual positives, how many are predicted negatives</em>”.<br>Given by the equation:</p><figure><img alt="Miss rate or False Negative Rate" src="https://cdn-images-1.medium.com/max/161/1*FrifgNRJf9jVMJm9Jtqj9g.png" /><figcaption>Miss rate or False Negative Rate</figcaption></figure><p><strong>III. Balanced Accuracy (BACC)</strong>: Focuses on high recall (TPR and TNR).<br>Computes balanced accuracy and is the average of recall obtained on each class.<br>Given by the equation:</p><figure><img alt="Balanced Accuracy Score" src="https://cdn-images-1.medium.com/max/747/1*u2O05OS22Ka8a_bglJ8IlA.png" /><figcaption>Balanced Accuracy</figcaption></figure><p><strong>IV. Matthew’s Correlation Coefficient (MCC)</strong>: Considers all the values from a Confusion Matrix and gives more value when the predictions are correct.<br>Given by the equation:</p><figure><img alt="Matthew’s Correlation Coefficient" src="https://cdn-images-1.medium.com/max/793/1*vBBMm4ZQTW2pha1Y2eAPXA.png" /><figcaption>Matthew’s Correlation Coefficient</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/358193f355090ee0df5a16a8395a17e8/href">https://medium.com/media/358193f355090ee0df5a16a8395a17e8/href</a></iframe><p><strong>IV. F1-Score</strong>: F1-Score is a measure of a test’s accuracy.<br>F1-Score considers both Precision and Recall and is the harmonic mean of them.<br>Given by the equation:</p><figure><img alt="F1-Score" src="https://cdn-images-1.medium.com/max/578/1*DNEYZCykduZeM7WGKIbOwA.png" /><figcaption>F1-Score</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826ab0c45dd47f11a43cb02273c68e9f/href">https://medium.com/media/826ab0c45dd47f11a43cb02273c68e9f/href</a></iframe><p><strong>V. Area Under the Curve (AUC)</strong>: AUC is the area under the curve of Receiver Operating Characteristic (ROC).</p><figure><img alt="AUC" src="https://cdn-images-1.medium.com/max/667/0*XyJCmevZtgV0KQ23.png" /><figcaption>AUC (<a href="https://www.researchgate.net/profile/Oxana-Trifonova/publication/276079439/figure/fig2/AS:614187332034565@1523445079168/An-example-of-ROC-curves-with-good-AUC-09-and-satisfactory-AUC-065-parameters.png">Image Source</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f54856d24606329ce800319d0f6c80b/href">https://medium.com/media/6f54856d24606329ce800319d0f6c80b/href</a></iframe><h3>Existing Approaches and Improvements over them</h3><p>There are some existing solutions and research work on the problem and have been given in the references. The existing solutions use various oversampling and undersampling techniques but with limited feature engineering.</p><p>In this solution, we would see that we have created many new features by doing feature engineering on various features. Have ensured that there is no data leakage when doing hyperparameter tuning with k-fold cross-validation using Random Search CV and, also during model training and evaluation. Also, implemented the Model Interpretability to explain why the model predicts a particular claim record as fraudulent or not.</p><h3>Exploratory Data Analysis (EDA)</h3><p>Exploratory Data Analysis (EDA) helps in analyzing the data using simple tools from statistics, plots, linear algebra, and others.</p><p>In EDA, we plot different graphs for getting a better understanding of the data. Let’s start doing the univariate analysis of all the features using various plots and conclude each.</p><ol><li><strong>EDA of Provider Dataset</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*dm5sOxAQ7wXamlhBdN6ZpA.png" /></figure><p><strong>Observation</strong>:</p><ul><li>The dataset is <strong>highly imbalanced</strong> with 90.6% non-fraud Providers and 9.4% fraud Providers class labels.</li></ul><p>2. <strong>EDA of Beneficiary Dataset</strong>:<br>2.1. <strong>EDA of Beneficiary Dataset — Gender Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*RpOdbjtaFdWxC4hAqUVUUw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>The gender feature is almost balanced.</li><li>42.9% of the beneficiaries (patients) are males and the rest 57.1% are females.</li></ul><p>2.2. <strong>EDA of Beneficiary Dataset — Race Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*o-9E5ckf5Y_n00IQiXwA1Q.png" /></figure><p><strong>Observation</strong>:</p><ul><li>There are four different races encoded as: ‘1’, ‘2’, ‘3’ and ‘5’.</li><li>Most of the beneficiaries (84.5%) belong to race ‘1’, followed by race ‘2’, ‘3’ and ‘5’.</li><li>Very few beneficiaries (2.1%) belong to race ‘5’.</li></ul><p>2.3. <strong>EDA of Beneficiary Dataset — RenalDiseaseIndicator Feature</strong>:<br>Renal Disease Indicator is a flag to indicate whether the beneficiary has any problem related to kidney failure or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*El4VrH-KsZ8_CfqpliGh-Q.png" /></figure><p><strong>Observation</strong>:</p><ul><li>As this feature is a flag to indicate any kind of renal disease, there are two possible values: 0/No and ‘Y’/Yes.</li><li>Most of the beneficiaries (85.87%) do not have any renal disease.</li></ul><p>2.4. <strong>EDA of Beneficiary Dataset — State Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*vENN-hE43MDzUImsyNw8nQ.png" /></figure><p><strong>Observation</strong>:</p><ul><li>There are a total of 52 states.</li><li>State with maximum beneficiaries (8.70%) is state encoded as ‘5’.</li><li>State with minimum beneficiaries (0.14%) is state encoded as ‘2’.</li></ul><p>2.5. <strong>EDA of Beneficiary Dataset — Country Feature</strong>:<br>There are a total of 314 countries in the dataset. Plotting the distribution of data for the top 50 countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*ZxcePic8K1lIBrZ2J_9d7w.png" /></figure><p><strong>Observation</strong>:</p><ul><li>Countries having maximum beneficiaries are in the order: 200, 10, 20, and so on.</li><li>Countries encoded as ‘200’ have 2.85% of the beneficiaries.</li></ul><p>2.6. <strong>EDA of Beneficiary Dataset — NoOfMonths_PartACov and NoOfMonths_PartBCov Features</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uX3ap-GOo1RYWtMwNadjKg.png" /></figure><p><strong>Observation</strong>:</p><ul><li>99.16% of the data in the ‘NoOfMonths_PartACov’ feature has a value of ‘12’ and 0.72% of the data has a value of ‘0’.</li><li>98.81% of the data in the ‘NoOfMonths_PartBCov’ feature has a value of ‘12’.</li><li>All other values are negligible.</li><li>As almost all values of this feature is having a value of 12, this feature won’t make any impact in doing the classification. Hence, we can drop these features.</li></ul><p>2.7. <strong>EDA of Beneficiary Dataset — Chronic Condition Features</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2dHh8N753_MOgIszgX2iA.png" /></figure><p><strong>Observation</strong>:</p><ul><li>There are two values in each of the Chronic Condition features: ‘1’ and ‘2’.</li><li>The value of ‘2’ will be replaced with ‘0’ to indicate ‘0’ as ‘No’ and ‘1’ as ‘Yes’ later during the featurization.</li><li>The data is reasonably balanced for all features except for ‘ChronicCond_Cancer’ and ‘ChronicCond_stroke’ where the data is imbalanced.</li></ul><p>2.8. <strong>EDA of Beneficiary Dataset — Annual Reimbursement and Deductible Amount Features for both Inpatient and Outpatient</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jwZ-CpWNHueve_gOmIhJg.png" /></figure><p><strong>Observation</strong>:</p><ul><li>For IPAnnualReimbursementAmt Feature, most of the amount lies between 0 and 5000.</li><li>For IPAnnualDeductibleAmt Feature, most of the amount lies between 0 and 2000.</li><li>For OPAnnualReimbursementAmt Feature, most of the amount lies between 0 and 5000.</li><li>For OPAnnualDeductibleAmt Feature, most of the amount lies between 0 and 2000.</li><li>Rest all the amounts greater than the above ranges are outliers. In this case study, those high amount values can be the potential fraud cases. Hence, we won’t remove those outliers.</li></ul><p>2.9. <strong>EDA of Beneficiary Dataset — Date of Birth Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*1x5iU0GLcsmSok6yaH6C5A.png" /></figure><p><strong>Observation</strong>:</p><ul><li>Most of the patients were born in the year 1941, followed by the years: 1939, 1943, 1940, and so on.</li></ul><p>2.10. <strong>EDA of Beneficiary Dataset — Date of Death Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqua6R0cpPug4u4Rf7NqXw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>All the dead patients died in the year ‘2009’.</li><li>Most of the dead patients died in December month.</li></ul><p>3. <strong>EDA of Inpatient and Outpatient Dataset<br></strong>Inpatient Dataset has a total of 30 features and Outpatient Dataset has a total of 27 features.<br>All the 27 features of Outpatient are also present in the Inpatient Dataset.<br>Inpatient Dataset has 3 extra features viz., ‘AdmissionDt’, ‘DischargeDt’ and ‘DiagnosisGroupCode’.<br>Hence, we will merge the data from the Inpatient and Outpatient Dataset along with the common columns and do the EDA on the merged data.</p><p>3.1. <strong>EDA of Claim (Inpatient and Outpatient) Dataset — Date Features</strong>:<br>There are four date features in the Claim dataset viz., ClaimStartDt, ClaimEndDt, AdmissionDt and DischargeDt.</p><p>We will derive the below new features from these date features to do EDA:<br> 1. Claim Settlement Delay: Difference between the Claim End Date and Claim Start Date.<br> 2. Treatment Duration: Difference between Discharge Date and Admission Date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYG_jtZAX_srZe4JaXYkzw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>The distribution of data in both the ‘ClaimSettlementDelay’ and ‘TreatmentDuration’ features follow a similar pattern. The ‘TreatmentDuration’ is present only for Inpatient data and not for Outpatient data.</li><li>Hence, we can keep ‘ClaimSettlementDelay’ and <strong>discard the ‘TreatmentDuration’ feature</strong>.</li><li>Also, the data distribution for both classes (fraud and non-fraud) for each feature follows the same trend.</li><li>There are outliers in the feature for both fraudulent and non-fraudulent cases, which should not be removed because those could be critical factors to identify a claim record as fraudulent or not.</li></ul><p>3.2. <strong>EDA of Claim (Inpatient and Outpatient) Dataset — Amount Features</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ndBlqZXfR4WQJHL0fSocw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>From the PDF, we can see that the data distribution of positive class and negative class follow an almost similar distribution.</li><li>From the Box Plot, we can see that there are many outliers as well for both fraudulent and non-fraudulent classes.</li><li>However, we will not remove the outliers because this feature is an important feature for a claim, and the records corresponding to the outliers can be classified as a potential fraud case when this feature is clubbed with other features to do the classification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5r76fZjmMxmk3CL9kV7Nw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>For the ‘DeductibleAmtPaid’ feature, most of the amount values are zero.</li><li>Because of the too many zero values, we see the non-zero values as outliers in the Box Plot.</li></ul><p>3.3. <strong>EDA of Claim (Inpatient and Outpatient) Dataset — ClmAdmitDiagnosisCode Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*snGzoFVI0UKQJ5t625q55Q.png" /></figure><p><strong>Observation</strong>:</p><ul><li>From the top 50 categories of the ‘ClmAdmitDiagnosisCode’ feature, we can see that all the codes (categories) are present for both positive (fraud) and negative (non-fraud) cases.</li><li>From the bottom 50 categories of the ‘ClmAdmitDiagnosisCode’ feature, we can see that some codes (categories) are not present for both the classes but are present for either of them. For example, category ‘V452’ is present only once for fraud cases and category ‘37883’ is present only once for the non-fraud case.</li><li>The top 5 Claim Admit Diagnosis Codes are ‘V7612’, ‘42731’, ‘78605’, ‘4019’ and ‘25000’.</li></ul><p>3.4. <strong>EDA of Claim (Inpatient) Dataset — DiagnosisGroupCode Feature</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*wwLooRvo9Z_CdyKuEUq-lg.png" /></figure><p><strong>Observation</strong>:</p><ul><li>From the top 50 categories of the ‘DiagnosisGroupCode’ feature, we cannot deduce much information.</li><li>From the bottom 50 categories of the ‘DiagnosisGroupCode’ feature, we can see that there are few codes that occur only once (Count = 1). In the ‘ClmAdmitDiagnosisCode’ feature, there are comparatively lot of codes that had only one occurrence.</li><li>We cannot deduce much meaningful insight from this feature.</li></ul><p>3.5. <strong>EDA of Claim (Inpatient and Outpatient) Dataset — Claim Diagnosis Codes Features</strong>:<br>Here, we will do the EDA for all the ten Claim Diagnosis Code Features.<br> i. ClmDiagnosisCode_1: Diagnosis code identifying the beneficiary’s principal diagnosis.<br> ii. ClmDiagnosisCode_2–10: Diagnosis code in the 2nd, 3rd, and so on, till the 10th position identifying the condition(s) for which the beneficiary is receiving care.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RICdQ7-yBhr2pJmDZbVIQw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>In all the Diagnosis Codes, code ‘4019’ has the highest percentage of claims.</li><li>In ‘ClmDiagnosisCode_1’, the 2nd and 3rd most occurrent codes are ‘4011’ and ‘2724’ respectively.</li><li>In all features except ‘ClmDiagnosisCode_1’, the 2nd and 3rd most occurrent codes are ‘25000’ and ‘2724’ respectively.</li><li>The codes ‘4019’, ‘2724’ and ‘42731’ occur in all features.</li></ul><p>3.6. <strong>EDA of Inpatient Dataset — Claim Procedure Codes Features</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKhfxo19lv4BbmBupBYuzw.png" /></figure><p><strong>Observation</strong>:</p><ul><li>For ‘ClmProcedureCode_1’, code ‘9904.0’ has the most occurrence, followed by ‘8154.0’, ‘66.0’, ‘3893.0’, ‘3995’, and so on. None of these 5 codes occur in any of the top 10 codes of the other 4 features.</li><li>Code ‘4019.0’ is most occurring code in the 3 features ‘ClmProcedureCode_2’, ‘ClmProcedureCode_3’ and ‘ClmProcedureCode_4’.</li><li>The most common codes in all the 5 features are ‘2724.0’, ‘5185.0’ and ‘4139.0’ with four occurrences.</li><li>Features ‘ClmProcedureCode_4’ and ‘ClmProcedureCode_5’ have very negligible (~0%) codes present and can be dropped.</li></ul><p>3.7. <strong>EDA of Inpatient Dataset — Physician Features</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcGo19YgsUguNEJKtTv1WA.png" /></figure><p><strong>Observation</strong>:</p><ul><li>In each of the plots of ‘AttendingPhysician’, ‘OperatingPhysician’ and ‘OtherPhysician’, it can be seen that the top Physicians (12+ in number) are involved in fraud cases only.</li><li>Physician ‘PHY330576’ attended as well as operated on most of the patients.</li><li>Around 2500+ patients were attended by the physician ‘PHY330576’.</li><li>Around 425 operations were performed by the physician ‘PHY330576’.</li><li>Physician ‘PHY412132’ was another physician for most of the patients.</li></ul><h3>Data Pre-processing</h3><p><strong>I. Merge the Datasets</strong><br>Merge the given dataset as:</p><ul><li>Inpatient and Outpatient contain almost all similar columns and hence, can be concatenated. This would give a single dataset containing the details of both inpatient and outpatient details related to the claims.</li><li>The resultant dataset can be combined with the Beneficiary dataset based on the Beneficiary Id to add the beneficiary-related information to the dataset.</li><li>Finally, the dataset can be merged with the Provider dataset to map the class label to decide whether the Provider is fraudulent or not.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec4ee976e2cb4014923b19f1e6c5ee7/href">https://medium.com/media/2ec4ee976e2cb4014923b19f1e6c5ee7/href</a></iframe><p><strong>II. Data Preparation</strong><br>Here, we will do clean-up, pre-processing, and feature engineering of the data.</p><ol><li><strong>Data Clean-up</strong>:</li></ol><ul><li>Convert the features having binary values indicating flags like ‘Y’/‘N’, ‘Yes’/‘No’ and 1/2 to 1/0.</li><li>Drop the columns having all null values.</li></ul><p><strong>2. Percentage of Null or Empty values</strong>:</p><ul><li>Check the percentage of null values for each column in the dataset.</li><li>Also, plot a heatmap to see the percentage of missing values in the dataset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeTfX0RC5GYJQVzDUPYIQA.png" /></figure><p><strong>Observation</strong>:</p><ul><li>Few of the Diagnosis Code and Procedural Codes are having a high percentage of empty values in the dataset.</li><li>The variables having more than 99.5% empty cells are:<br> 1. ClmProcedureCode_3<br> 2. ClmProcedureCode_4<br> 3. ClmProcedureCode_5</li><li>These columns can be removed as they have almost all empty cells and won’t contribute much to the classification.</li></ul><p><strong>3. Feature Engineering</strong>:</p><p><strong>3.1. New Features from Date Features</strong>:</p><ul><li>Here, we will generate new features from the date features:<br> 1. Claim Settlement Delay: Difference between the Claim End Date and Claim Start Date.<br> 2. Treatment Duration: Difference between Discharge Date and Admission Date.<br> 3. Age: Based on the DOB.<br> 4. IsDead: Based on the DOD.</li></ul><p><strong>3.2. New Features from Reimbursement Amount and Deductible Amount</strong>:</p><ul><li>Here, we will generate new features from the features:<br>InscClaimAmtReimbursed, DeductibleAmtPaid, IPAnnualReimbursementAmt, IPAnnualDeductibleAmt, OPAnnualReimbursementAmt and OPAnnualDeductibleAmt.</li><li>TotalClaimAmount = InscClaimAmtReimbursed + DeductibleAmtPaid.</li><li>IPTotalAmount = IPAnnualReimbursementAmt + IPAnnualDeductibleAmt.</li><li>OPTotalAmount = OPAnnualReimbursementAmt + OPAnnualDeductibleAmt.</li></ul><p><strong>3.3. New Features to indicate Inpatient and Outpatient</strong>:</p><ul><li>Here, we will generate a new feature called ‘IsInpatient’ having a value of 1 if the claim record is for Inpatient data and 0 if the claim record is for Outpatient data.</li><li>As the feature ‘DiagnosisGroupCode’ exists only for the Inpatient dataset, we will create the values for ‘IsInpatient’ based on whether is a value in the ‘DiagnosisGroupCode’ feature.</li></ul><p><strong>3.4. New Features from the Physician related features</strong>:</p><ul><li>We will derive new features from the features ‘AttendingPhysician’, ‘OperatingPhysician’ and ‘OtherPhysician’ as:<br> 1. UniquePhysCount: Number of different physicians who attended/operated the patient and/or performed any other work in a claim record.<br> 2. PhysRoleCount: Total number of attending, operating and other physicians who worked for a patient in a claim record.<br> 3. IsSamePhysMultiRole1: Flag to indicate if a single physician is involved with multiple roles for a patient in a claim record.<br> 4. IsSamePhysMultiRole2: Flag to indicate if there are only two physicians involved in a claim record and one of them had multiple roles.</li><li>Consider the below table data to understand it better:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xhl5KiegYsnMyo60kx05Qg.png" /></figure><ul><li>Will create 3 new features for the top 3 physicians and count the number of times they appeared as attending, operating or other physicians in a claim record.</li><li>If ‘PHY412132’, ‘PHY337425’ and ‘PHY330576’ are the top 3 most occurring physicians, consider the below table data to understand the new features:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*G6wopnHa8GG_Pe_nPgrezw.png" /></figure><p><strong>3.5. New Features from the Claim Diagnosis Codes and Claim Procedure Codes</strong>:</p><ul><li>For all the features related to the Claim Diagnosis Codes and Claim Procedure Codes, we would generate new features for the top ‘k’ codes similar to what we did for the top 3 physicians above.</li></ul><p><strong>3.6. Update the ClmAdmitDiagnosisCode and DiagnosisGroupCode Feature</strong>:</p><ul><li>Replace the value of the features with a flag to indicate whether a value exists or not.</li></ul><p><strong>3.7. New Features for State and Country</strong>:</p><ul><li>We will do the below two kinds of encoding for the ‘State’ and ‘Country’ features, after splitting the data into train, test, and CV:<br> 1. <strong>Response Encoding</strong>: will be used in the models suitable for lower dimensions like Decision Tree, Random Forest, GBDT, etc.<br> 2. <strong>One-hot Encoding</strong>: for a model suitable for handling large dimensions as well. Eg., Naive Bayes, Logistic Regression, etc.</li></ul><p><strong>4. Correlation Plot</strong>:</p><ul><li>We will plot the <strong>Spearman Rank Correlation Coefficient</strong> Graph for the final dataset prepared and see if any features can be removed based on the Correlation Coefficient.</li><li>Will consider the correlation coefficient of threshold 0.70.</li><li>Will check for the pair of features having a correlation coefficient greater than 0.70.</li><li>Out of the two features in a pair, we will remove the feature having a lesser correlation coefficient with the Class Label ‘PotentialFraud’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEx9QrO1pTJt8a8eqcRuNw.png" /></figure><p><strong>Observation from the Correlation Plot</strong>:</p><ul><li>Here, we see few features are having high Spearman Correlation Coefficient.</li><li>Spearman Correlation Coefficient between some of the features having coefficient greater than 0.70 are:<br> 1. TreatmentDuration and DiagnosisGroupCode: 0.99<br> 2. TreatmentDuration and ClmProcedureCode_1: 0.74<br> 3. DiagnosisGroupCode and ClmProcedureCode_1: 0.74<br> 4. ClmDiagnosisCode_3 and ClmDiagnosisCode_4: 0.74<br> 5. ClmDiagnosisCode_4 and ClmDiagnosisCode_5: 0.77<br> 6. ClmDiagnosisCode_5 and ClmDiagnosisCode_6: 0.84<br> 7. ClmDiagnosisCode_5 and ClmDiagnosisCode_7: 0.73<br> 8. ClmDiagnosisCode_6 and ClmDiagnosisCode_7: 0.87<br> 9. ClmDiagnosisCode_6 and ClmDiagnosisCode_8: 0.77<br> 10. ClmDiagnosisCode_7 and ClmDiagnosisCode_8: 0.89<br> 11. ClmDiagnosisCode_7 and ClmDiagnosisCode_9: 0.78<br> 12. ClmDiagnosisCode_8 and ClmDiagnosisCode_9: 0.87</li></ul><p><strong>Removal of Features</strong>:</p><ul><li>Will remove one of the features among these pairs that has a lesser correlation coefficient with the Class Label ‘PotentialFraud’.</li><li>The Correlation Coefficient of the Feature with the Class Label is shown in parenthesis.</li><li>Removing the below feature among the pair of features based on the correlation coefficient with the Class Label:<br> 1. TreatmentDuration (0.11) and DiagnosisGroupCode (0.11): Any feature can be removed as both have a correlation coefficient of 0.11 with the Class Label. Remove the feature ‘DiagnosisGroupCode’ here.<br> 2. TreatmentDuration (0.11) and ClmProcedureCode_1 (0.086): Remove the feature ‘ClmProcedureCode_1’.<br> 3. DiagnosisGroupCode (0.11) and ClmProcedureCode_1 (0.086): Both these features are already accounted for removal.<br> 4. ClmDiagnosisCode_3 (0.034) and ClmDiagnosisCode_4 (0.045): Remove the feature ‘ClmDiagnosisCode_3’.<br> 5. ClmDiagnosisCode_4 (0.045) and ClmDiagnosisCode_5 (0.057): Remove the feature ‘ClmDiagnosisCode_4’.<br> 6. ClmDiagnosisCode_5 (0.057) and ClmDiagnosisCode_6 (0.064): Remove the feature ‘ClmDiagnosisCode_5’.<br> 7. ClmDiagnosisCode_5 (0.057) and ClmDiagnosisCode_7 (0.069): ‘ClmDiagnosisCode_5’ has the lesser coefficient and is already accounted in the above point.<br> 8. ClmDiagnosisCode_6 (0.064) and ClmDiagnosisCode_7 (0.069): Remove the feature ‘ClmDiagnosisCode_6’.<br> 9. ClmDiagnosisCode_6 (0.064) and ClmDiagnosisCode_8 (0.072): ‘ClmDiagnosisCode_6’ has the lesser coefficient and is already accounted in the above point.<br> 10. ClmDiagnosisCode_7 (0.069) and ClmDiagnosisCode_8 (0.072): Remove the feature ‘ClmDiagnosisCode_7’.<br> 11. ClmDiagnosisCode_7 (0.069) and ClmDiagnosisCode_9 (0.073): ‘ClmDiagnosisCode_7’ has the lesser coefficient and is already accounted in the above point.<br> 12. ClmDiagnosisCode_8 (0.072) and ClmDiagnosisCode_9 (0.073): Remove the feature ‘ClmDiagnosisCode_8’.</li></ul><p><strong>Code for all the Data Pre-processing</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67fd430d408c914196279a436bbecda8/href">https://medium.com/media/67fd430d408c914196279a436bbecda8/href</a></iframe><p><strong>4. Handling Data Leakage</strong></p><ul><li>So far whatever features have been generated, do not have any data leakage problem.</li><li>No data imputation has been done based on the mean, standard deviation, median, etc.</li><li>Standardization or Normalization of the data has also not been done so far.</li><li>Unlike the imputation techniques like mean imputation that considers all the data points in the dataset, the new features that have been generated like the physician, diagnosis codes, procedure codes, and other code-related features, have got values by considering the corresponding data point and not all the data points. Hence, this does not lead to any data leakage issue.</li><li>However, for generating new features for the ‘State’ and ‘Country’ features like response encoding and one-hot encoding, we need to consider only the training dataset and not the whole dataset. Otherwise, there will be a data leakage issue.</li><li>We need to ensure that we do response encoding, one-hot encoding, or standardization of the data by only considering the training dataset and not the test dataset while training a model. Otherwise, the Model would have access to the data which it would not have in real-time predictions and it would cause the model to outperform while training and under-perform in real-time.</li><li>We will make use of <strong>pipelines</strong> to overcome the data leakage issues.</li></ul><p><strong>5. Encoding Categorical Features: Response Encoding</strong></p><ul><li>We would use Response Encoding for the ‘State’ and ‘Country’ features.</li><li>For each categorical feature, Response Encoding creates ’n’ number of new features for an ’n’ class classification problem.</li><li>As this problem is a case of binary classification to identify a claim record as either fraud or non-fraud, there would be a total of 4 new features created for ‘State’ and ‘Country’ features (two for each feature).</li><li>The value in the new feature signifies the <strong>likelihood probability</strong> of the feature given a particular class label.</li><li>The below image explains the concept of Response Encoding:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_-eYLnM8K4qn27uDlSfhQ.png" /><figcaption>Response Encoding (<a href="https://imgur.com/TufZptV">Image Source</a>)</figcaption></figure><ul><li>When we fit the response encoding technique on the Train dataset, it generates a Response table and encoded features.</li><li>The test data is transformed based on the response table and new encoded features are generated for the test dataset.</li><li>The response label is built only on the training dataset. For a category that is not there in train data and present in test data, we will encode them with default values. Eg., In our test data if have the State ‘D”, then we encode it as [0.5, 0.05].</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d56aca424f6bad4e1c6b2771f56260d/href">https://medium.com/media/4d56aca424f6bad4e1c6b2771f56260d/href</a></iframe><p><strong>6. Encoding Categorical Features: One-hot Encoding</strong></p><ul><li>We would do one-hot encoding of the categorical features viz., ‘State’ and ‘Country’.</li><li>To avoid any data leakage issue, we will make use of sklearn’s Pipeline.</li><li>To use the Pipeline, we need to create a class with the fit() and transform() method inheriting BaseEstimator, TransformerMixin class.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/462a0eaa2985b654d16ff82884cb82e9/href">https://medium.com/media/462a0eaa2985b654d16ff82884cb82e9/href</a></iframe><p><strong>7. Encoding Numerical Features: Column Standardization</strong></p><ul><li>We will standardize the below numerical features available in the dataset:<br> i. Race<br> ii. ClaimSettlementDelay<br> iii. TreatmentDuration<br> iv. Age<br> v. TotalClaimAmount<br> vi. IPTotalAmount<br> vii. OPTotalAmount<br> viii. UniquePhysCount<br> viii. PhysRoleCount</li><li>Again for standardizing the features, we need to ensure that there is no data leakage.</li><li>Hence, we will create a class with fit() and transform() method inheriting BaseEstimator, TransformerMixin class.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a0ae77d1400289eda3b3c860b7021f0/href">https://medium.com/media/1a0ae77d1400289eda3b3c860b7021f0/href</a></iframe><h3>Machine Learning Models — Hyperparameter Tuning and Model Training</h3><ul><li>Here, we will do hyperparameter tuning on various Machine Learning Models to find the best hyperparameters.</li><li>With the best hyperparameters, we will train the models with different data sampling techniques and do the evaluation.</li></ul><h4>Split the Dataset for Training and Testing</h4><ul><li>We would split the data into a ratio of <strong>80:20</strong>. 80% of the data will be used for doing k-fold cross-validation hyperparameter tuning of the model and the rest 20% of the data (unseen) will be used in evaluating the model.</li></ul><h4>Sampling — Oversampling and Undersampling</h4><ul><li>We will use different sampling techniques for sampling the data before training the Models.</li><li>We would do 4 kinds of data sampling:<br> <strong>1. Raw Data</strong>: Use raw data without any undersampling or oversampling.<br> <strong>2. Balanced Class Weights</strong>: Use balanced class weights.<br> <strong>3. Random Undersampling</strong>: Randomly undersample the majority class data to an have equal number of data points as that in the minority class data.<br> <strong>4. Oversampling using SMOTE</strong>: Oversample the minority class data to have an equal number of data points as that in the majority class data, using <strong>SMOTE (Synthetic Minority Over-sampling Technique)</strong>.</li><li>We would use the below Machine Learning Models for doing hyperparameter tuning and evaluation, with each of the 4 sampling techniques:<br>1. Logistic Regression.<br>2. Decision Tree.<br>3. Random Forest.<br>4. XGBoost.<br>5. LightGBM.</li><li>A sample code for doing hyperparameter tuning, training the model with the best hyperparameters found, and doing the evaluation is shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7174ca3792a7869b2bb734b9190c7a09/href">https://medium.com/media/7174ca3792a7869b2bb734b9190c7a09/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5AA8lXCMf9dGpmUqemWgw.png" /><figcaption>Hyperparameter Tuning on Response Encoded Data with SMOTE Oversampling using XGBoost</figcaption></figure><ul><li>After getting the best hyperparameters using k-fold cross-validation and random search, train the model using the best hyperparameters as shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f179ea692563cd80e16b5f8756e11503/href">https://medium.com/media/f179ea692563cd80e16b5f8756e11503/href</a></iframe><ul><li>Evaluate the trained model on various performance metrics discussed before. The result looks like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRIej8qCh3sVgwaPC0IYNg.png" /><figcaption>Performance Metrics of XGBoost Model</figcaption></figure><h3>Comparison of Models</h3><ul><li>We did the hyperparameter tuning on various models using different sampling techniques, trained the models, and evaluated them.</li><li>The table below shows a comparison between various models used with different sampling techniques.</li><li>The green highlighted cells indicate the best value of the metric across all the models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yL0-xTsDEDNilA1oVApKuA.png" /><figcaption>Comparison of Models on different performance metrics</figcaption></figure><p>One-Hot Encoding*: One-hot Encoding of ‘State’ and ‘Country’ features.<br>Response Encoding**: Response Encoding of ‘State’ and ‘Country’ features.</p><ul><li>We can observe that:<br>1. Decision Tree with balanced class weights received the least ‘FNR’ score of 0.24791.<br>2. Random Forest with balanced class weights received the minimum ‘Train AUC’ and minimum ‘Train Log-loss’.<br>3. XGBoost with SMOTE Oversampling received the least ‘Test Log-loss’, ‘percentage misclassification’, ‘FPR’ and the maximum ‘Test AUC’, ‘F1-Score’, ‘BACC’, and ‘MCC’ score.</li><li><strong>Conclusion</strong>: As the XGBoost Model with SMOTE oversampling gives the best scores for most of the performance metrics, we will choose <strong>XGBoost with SMOTE Oversampling</strong> as the final model.</li><li>However, the decision to choose the best model depending on which all performance metrics to be considered is subjective to the business need.</li></ul><h3>Model Interpretability</h3><p>Interpretability is very important as the model needs to justify why it classifies a Provider’s claim record as fraudulent or not.</p><p>We have tried providing Model Interpretability using approaches:</p><ol><li><strong>Global Structure of the Data</strong>: Provides the model interpretability by using the feature importance learned by the model on the whole training dataset.<br>The figure below shows the model interpretability of XGBoost using the feature importance of the top 15 features:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*0mJYKmp19KCrKYOfEHKs0g.png" /><figcaption>Model Interpretability using Feature Importance</figcaption></figure><p>The interpretability using feature importance remains the same for all query points.</p><p>2. <strong>Local Structure of the Query Point</strong>: Provides the model interpretability by looking at the local structure of the data points.<br>The figure below shows the model interpretability for a query point using the LIME (Local Interpretable Model Agnostic) technique:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr0D1e7Jl3s3cnRj5WCT5Q.png" /><figcaption>Model Interpretability using LIME</figcaption></figure><p>The interpretability using LIME is different for every query point as it considers the local structure of the query points in its neighborhood.</p><h3>Deployment</h3><p>We have used Flask API to build REST APIs required for the productionising the model.</p><p>The Web Application takes 4 excel sheets in the required format as mentioned in the ‘Source of Data’ section and gives prediction of whether the claims submitted by the Providers are fraudulent or not.</p><p>Below is the demo from localhost (will be updated to show the demo from AWS EC2 instance after resolving a few package installation issues later):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aI8NhxuXWi6QqKUgpRlMeQ.gif" /><figcaption>Demo of the Model Prediction</figcaption></figure><h3>Future Work</h3><p>The future scope for this problem could be:</p><ul><li>Implementing more complex ensemble modeling techniques like stacking and cascading.</li><li>Develop a deep Multi-layer Perceptron (MLP) Model (Deep Learning Model).</li><li>Explain the Model’s interpretability using more advanced techniques like SHAP (SHapley Additive exPlanations).</li></ul><h3>References</h3><ol><li><a href="https://ieeexplore.ieee.org/abstract/document/8260744">Medicare Fraud Detection using Machine Learning Models</a>.</li><li><a href="https://www.aaai.org/ocs/index.php/FLAIRS/FLAIRS18/paper/view/17617/16814">The Detection of Medicare Fraud using ML Methods with excluded Provider Labels</a>.</li><li><a href="https://www.researchgate.net/publication/350132738_A_Comparative_Study_of_Using_Various_Machine_Learning_and_Deep_Learning-Based_Fraud_Detection_Models_For_Universal_Health_Coverage_Schemes">A Comparative Study of Using Various Machine Learning and Deep Learning-Based Fraud Detection Models For Universal Health Coverage Schemes</a>.</li><li><a href="https://ieeexplore.ieee.org/abstract/document/8123782">Credit card fraud detection using machine learning techniques: A comparative analysis</a>.</li><li><a href="https://www.kaggle.com/rohitrox/medical-provider-fraud-detection/notebook">Medical Provider Fraud Detection — Kaggle</a></li><li><a href="https://www.appliedaicourse.com/">Applied Roots</a>.</li></ol><h3>GitHub Repository</h3><p><a href="https://github.com/pulkitratnaganjeer/HealthcareFraudDetection">GitHub - pulkitratnaganjeer/HealthcareFraudDetection</a></p><h3>LinkedIn</h3><p><a href="https://www.linkedin.com/in/pulkit-ganjeer-90047140/">Pulkit Ganjeer - Principal Software Engineer - emids | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5996d63bd3c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text to Numerical Vector Conversion Techniques]]></title>
            <link>https://medium.com/analytics-vidhya/text-to-numerical-vector-conversion-techniques-f2b97ab9b895?source=rss-8799db75c0a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2b97ab9b895</guid>
            <category><![CDATA[doc2vec]]></category>
            <category><![CDATA[text-embedding]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bag-of-words]]></category>
            <dc:creator><![CDATA[Pulkit Ratna Ganjeer]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 06:15:24 GMT</pubDate>
            <atom:updated>2021-08-08T17:16:45.691Z</atom:updated>
            <content:encoded><![CDATA[<p>In this era of Modern Computing, there is a humongous amount of data available today and it keeps increasing every second through various means like “comments on Facebook”, “tweets on Twitter”, “WhatsApp chats”, “emails”, “blogs”, “Google searches” and a lot of many other ways you can think of.</p><p>In Machine Learning, Data plays a vital role. We need to train a model on a large amount of data and then do evaluations on unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17-GgNl8Ty7Uw2uJLxy-dg.png" /><figcaption><a href="https://www.thetalkingmachines.com/sites/default/files/styles/widescreen_large/public/2019-05/34_binary_space_data.jpg?itok=fYxXjksG">Image Source</a></figcaption></figure><h3>Table of Contents</h3><ol><li><a href="#9389">Prerequisites</a></li><li><a href="#5ba2">Different forms of data</a></li><li><a href="#26bc">Different types of data</a></li><li><a href="#a3d9">Need for conversion of data to a numerical data/vector</a></li><li><a href="#96f0">Embedding techniques for converting data into numerical data/vector</a><br>i. <a href="#0fb4">Bag of words (BoWs)</a><br>ii. <a href="#c411">Term Frequency-Inverted Document Frequency (TF-IDF)</a><br>iii. <a href="#e207">Word2Vec</a><br>iv. <a href="#3771">Doc2Vec</a></li><li><a href="#bb44">Summary</a></li><li><a href="#376d">References</a></li></ol><h3>Prerequisites</h3><ol><li>Basic Mathematics</li><li>Basic knowledge of features in Machine Learning.</li></ol><h3>Different forms of data</h3><p>Data can exist in any form viz., text, audio, video, and images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LzecyVHLx8Oq27fvjMzdQ.png" /><figcaption><a href="https://techblogwriter.co.uk/wp-content/uploads/2016/01/text-video-audio-and-images..png">Image Source</a></figcaption></figure><h3>Different types of data</h3><p>The data in any of the above forms can be broadly classified into four main types, which any Machine Learning Model can rely on. These types are:</p><ol><li><strong>Numerical Data</strong></li><li><strong>Categorical Data</strong></li><li><strong>Time Series Data</strong></li><li><strong>Text Data.</strong></li></ol><figure><img alt="Different types of data" src="https://cdn-images-1.medium.com/max/762/1*bgsaKzWUeReVqtgE17NAGg.png" /><figcaption>Broad categories of data</figcaption></figure><p>Let me brief about these data types:</p><ol><li><strong>Numerical Data</strong> or <strong>Quantitative Data</strong>: Any form of measurable data such as your height, weight, or cost of your mobile phone.<br>i. <strong>Continuous</strong>: Numerical data that can take any value within a range such as height, weight, temperature, etc.<br>ii. <strong>Discrete</strong>: Numerical data that can take only distinct values such as the number of employees/students, units sold, etc.</li><li><strong>Categorical Data</strong>: Any sort of categories that can be counted such as gender, city, state, country, etc.<br>i. <strong>Nominal</strong>: Categorical Data that can be counted but not ordered, such as gender, hair color, mobile brand, etc.<br>ii. <strong>Ordinal</strong>: Categorical Data that can be counted as well as ordered, such as IMDB movie ratings (1–10), Hotel star ratings, etc.</li><li><strong>Time Series Data</strong>: Any data that consists of data points indexed at specific points in time, such as stock prices, <a href="https://en.wikipedia.org/wiki/Electrocardiography">ECG</a>, weather conditions, etc.</li><li><strong>Text Data</strong>: Text data is simple words, sentences, or paragraphs that can provide some insight such as product reviews, Facebook comments, etc.</li></ol><h3>Need for conversion of data to a numerical data/vector</h3><p>Many Machine Models require the data to be present in numerical format.</p><p>Are you wondering? “<em>Why do we need to convert any data to numerical data before feeding it into a Machine Learning Model?</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*8r5pYRf3DI4BUXtupyqaag.png" /></figure><p>Well, Machine Learning Model involves performing various mathematical operations under the hood. Like Humans need oxygen, mathematics needs numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*uuGtQGjoLXHy_uMcXrHWRQ.png" /></figure><p>The Numerical Data are already having numbers and do not need any conversion.<br>In this article, we will primarily focus on Text Data for conversion into a numerical vector.</p><h4><strong>Embedding</strong></h4><p>The process of conversion of text data into a vector is called <strong>embedding</strong>.</p><p>Before we look into various techniques of converting a text into a numerical vector, let&#39;s understand some terminologies:</p><ol><li><a href="#347d"><strong>Vector</strong></a></li><li><a href="#54ce"><strong>Document</strong></a></li><li><a href="#95cf"><strong>Corpus</strong></a></li><li><a href="#f45f"><strong>Tokens</strong></a></li><li><a href="#9dc1"><strong>Vocabulary</strong></a></li></ol><h4>Vector</h4><p>In Physics, a Vector is an entity that has a magnitude and a direction. For example, the Velocity of a car.</p><p>In Computer Science, a Vector is nothing but a collection of one or more numbers. Each number in a Vector represents the magnitude of the Vector in a particular dimension.<br>For example, a Vector in 3-dimensional space can be represented by three number as v = [2, 1, 3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*b4z2dLcLA-APVOGUGWr-xg.png" /></figure><h4>Document</h4><p>A Document is a collection of sentences that represent a specific fact or entity. Examples of documents include a product review, a blog, a tweet, or a log file generated by the software.</p><h4>Corpus</h4><p>A Corpus is a collection of documents. <br>Documents inside a corpus are related to each other. For example, a corpus may include all reviews for a given product in a month, all movies’ reviews in the IMDB platform, or all Facebook comments by a Facebook user.</p><p>Just for information: The plural of Corpus is called <strong>Corpora</strong>.</p><h4>Tokens</h4><p>Tokens are the building blocks of Natural Language. It refers to the units into which, a text is broken. The process of obtaining tokens is called <strong>Tokenization</strong>.</p><p>There are different types of tokenization:</p><ol><li><strong>Word Tokenization</strong>: The tokenization where a text is split based on the words in it.</li><li><strong>Character Tokenization</strong>: The tokenization where a text is split based on the characters in it.<br>In this article, we won’t go into the details of character tokenization.</li><li><strong>n-gram Tokenization</strong>: The tokenization is done by splitting a text based on n-consecutive words in it.</li></ol><h4>Vocabulary</h4><p>A Vocabulary is a collection of all unique words/tokens in the Corpus.</p><p>Let us see the figure below to understand the above terminologies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeKMXYsTtKlC2mzHIf17fQ.png" /><figcaption>Documents, Corpus, Tokens, and Vocabulary</figcaption></figure><p><strong>Please note that we will use the example of the above document to understand different text embedding techniques.</strong></p><h3>Embedding techniques for converting data into numerical data/vector</h3><p>Let us see how can we convert a text into a numerical vector. We will discuss some of the standard techniques for converting a text into a numerical vector.</p><p>Below are some of the text embedding techniques:</p><ol><li><a href="#0fb4"><strong>Bag of words (BoWs)</strong></a><strong><br>i. Uni-gram BoWs<br>ii. Bi-gram BoWs<br>iii. Tri-gram BoWs<br>iv. n-gram BoWs</strong></li><li><a href="#c411"><strong>Term Frequence-Inverted Document Frequency (TF-IDF)</strong></a></li><li><a href="#e207"><strong>Word2Vec</strong></a><strong><br>i. </strong><a href="#f1d9"><strong>Average Word2Vec</strong></a><strong><br>ii. </strong><a href="#a9e1"><strong>TF-IDF Word2Vec</strong></a></li><li><a href="#3771"><strong>Doc2Vec</strong></a></li></ol><h3>Bag of Words (BoW)</h3><p>A bag-of-words Model, or BoW for short, is a very simple and flexible technique to represent a text as a numerical vector.<br>It involves two things:</p><ol><li>A vocabulary of known words.</li><li>The measure of the presence of known words.</li></ol><p>Imagine a bag containing 9 different balls, each labeled as the unique words in the vocabulary. As we saw earlier that for our Corpus, we have a set of 9 unique words in the Vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*X5qVzeNFzhkjdbKtMGSoeQ.png" /><figcaption>Illustration of BoWs concept</figcaption></figure><p>These 9 unique balls represent all the dimensions in which the numeric vectors can be represented.</p><p>To represent a document as a vector, we need to mark the number of occurrences (frequency) for each of the words in a document against the balls of vocabulary as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7B_vZnzYI-bU43V2w0tbQ.png" /><figcaption>BoWs table for all the four documents</figcaption></figure><p>From the above table, we can represent the Documents as a vector by writing the collection of numbers (row-wise) as:<br> Vector of Document 1: [1, 0, 0, 0, 0, 1, 0, 1, 1]<br> Vector of Document 2: [0, 0, 0, 0, 1, 1, 1, 0, 2]<br> Vector of Document 3: [1, 1, 0, 1, 0, 1, 0, 1, 0]<br> Vector of Document 4: [1, 0, 1, 0, 0, 0, 0, 1, 1]<br>Here, we are writing the number of occurrences of the words for each Document.</p><h4>Binary Bag of Words</h4><p>Instead of using the number of occurrences, we can also use either 1 or 0 to represent whether the word is present in the Document or not.<br>If we use either 1 or 0 to just check whether the word occurs or not, this implementation of BoWs is called <strong>Binary Bag of Words</strong>.</p><h4>Bag of n-grams</h4><p>A bag of n-grams is an extension of the Bag of Words. In n-gram BoWs, we take n-consecutive words as tokens. What we saw in the example above are uni-gram BoWs.</p><ol><li><strong>Uni-gram or 1-gram BoW</strong>: Tokens consist of a single word. The example we discussed above is unigram BoWs.</li><li><strong>Bi-grams or 2-grams BoW</strong>: Tokens consist of two consecutive words. For example, for Document 1 (You create your life), the tokens would be {“you create”, “create your”, “your life”}.<br>Similarly, the Corpus would contain the tokens having distinct two consecutive words.</li><li><strong>Tri-grams or 3-grams BoW</strong>: Tokens consist of three consecutive words.<br> Similarly, this concept can be extended to generate n-grams BoWs.</li></ol><p>Let’s see the numerical vectors using bigram BoWs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JldAiqecWWoOBGwdIwL-yA.png" /><figcaption>Bi-grams Tokenization</figcaption></figure><p>To represent a text as a vector, we can write the number of occurrences of the two consecutive words against the corresponding tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24MfLn7-VKYiniPp92G4Ow.png" /></figure><p>Based on the above table, we can represent the Documents as a vector by writing the collection of numbers (row-wise) as:<br> Vector of Document 1: [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]<br> Vector of Document 2: [0, 0, 1, 1, 1, 1, 0, 0, 0, 0]<br> Vector of Document 3: [1, 0, 0, 0, 0, 0, 1, 1, 1, 0]<br> Vector of Document 4: [1, 1, 0, 0, 0, 0, 0, 0, 0, 1]</p><p>Similarly, we can do the trigram BoWs and ngram BoWs.</p><p>A bag of n-grams can be more informative than the Bag of unigrams because they capture more context around each word (eg., “create your life” is more informative than just “life”).</p><p>BoWs can be used for both <strong>Categorical</strong> and <strong>Text</strong> Data.</p><h4>Drawbacks of using a Bag-of-words</h4><ol><li>BoWs depend on the count of words and discards the semantic meaning of the Documents.</li><li>The Vocabulary size would increase with the inclusion of new Documents.</li><li>The Vectors would contain too many zeros for a Document, resulting in a sparse matrix. Hence, it consumes more memory for less information.</li><li>No information on the grammar of the Documents nor the ordering of the words in the text is retained.</li></ol><h3>Term Frequency-Inverse Document Frequency (TF-IDF)</h3><p>TF-IDF, short for Term Frequency-Inverse Document Frequency, is defined in <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">Wikipedia</a> as “a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus”.</p><p>This is another technique to convert a text into a numerical vector.</p><p>Before we understand how TF-IDF works, let&#39;s understand the individual terms TF and IDF separately.</p><h4>Term Frequency (TF)</h4><p>Term Frequency of a word is a measure of the frequency of a word in a Document.<br>TF is defined by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*QNajp_DGkKL-5VjGbUI4uQ.png" /><figcaption>Term Frequency Formula</figcaption></figure><p>As Term Frequency lies between 0 and 1, it can be interpreted as Probability.<br>Hence, TF can also be defined as:<br> i. Probability of finding a word in the Document.<br> ii. Probability of how often word occurs in a Document.</p><h4>Inverse Document Frequency (IDF)</h4><p>IDF is a measure of how important a word is.<br>IDF is defined by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*3PUtJEz6KioVCVU_8T2-FQ.png" /><figcaption>Inverse Document Frequency Formula</figcaption></figure><p>As the logarithm function is a <a href="https://en.wikipedia.org/wiki/Monotonic_function">monotonically increasing function</a>, the IDF value of a word is inversely proportional to the number of Documents having the given word.<br>Hence, if a word is less frequent in the Corpus, its IDF value will be more.<br> <br>In BoWs, we created vectors by filling the dimensions with the number of occurrences of a word.<br>In TF-IDF, we create the vectors by multiplying the Term Frequency and Inverse Document Frequency of a word. Please see the below table using TF-IDF values of the words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MUjxhly8t7FQ95bq7B-aw.png" /><figcaption>TF-IDF Calculations</figcaption></figure><p>From the above table, we can represent the Documents as a vector by writing the TF-IDF values of the words (row-wise) as:<br> Vector of Document 1: [0.03, 0.00, 0.00, 0.00, 0.00, 0.03, 0.00, 0.03, 0.03]<br> Vector of Document 2: [0.00, 0.00, 0.00, 0.00, 0.12, 0.02, 0.12, 0.00, 0.05]<br> Vector of Document 3: [0.02, 0.12, 0.00, 0.12, 0.00, 0.02, 0.00, 0.02, 0.00]<br> Vector of Document 4: [0.03, 0.00, 0.15, 0.00, 0.00, 0.00, 0.00, 0.03, 0.03]</p><p>In TF-IDF, more importance is given to the words that are frequent in a Document and also, to the rare words in a Corpus.<br>We can even use only the Inverse Document Frequency alone to generate vectors depending on the problem.</p><h4>Advantage of TF-IDF</h4><p>It contains the information on the more important words and the less important ones as well.</p><h4>Disadvantage of TF-IDF</h4><p>Like BoWs, the TFIDF does not consider Semantic Meaning.</p><h3>Word2Vec</h3><p>Word2Vec or <strong>Word to Vector</strong>, also denoted by <strong>W2V</strong>, is a state-of-the-art (SOTA) technique to convert a word into a vector by considering the semantic meaning of the words, unlike BoWs and TF-IDF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*1xavsXIqsHdjOLuftniK0w.png" /><figcaption>Word2Vec Model: Input and Output</figcaption></figure><p>Work2Vec uses a Neural Network Model to learn word associations from a large corpus of text.<br>We won’t go into details on how a Word2Vec is implemented under the hood, as it will require a different set of advanced concepts from Deep Learning and would turn away from the intent of this article.<br>For simplicity, we would consider it as a black box for this article.</p><p>With Word2Vec, a word is transformed into a numerical dense vector (not sparse vector as retrieved in BoW and TF-IDF) with d-dimensions typically 50, 100, 200, 300, etc.<br>If two words are semantically similar, then the vectors of these words are closer geometrically.<br>For example, if we have 3 words: tasty, delicious, and baseball. After Word2Vec transformation, the Vectors for the words viz., “tasty” and “delicious” will be close in the d-dimension space, and the Vector for the word “baseball” will be farther.</p><h4>Word2Vec Key Points</h4><p>If two words are semantically similar, then their vectors will be closer.<br>W2V retains/satisfies relationships between words such as King::Queen, Man::Woman, Country:: Capital.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0m2VIiG_LxcEPMOEZnbtw.png" /><figcaption>Semantic relationship in Word2Vec</figcaption></figure><p>We can use any pre-trained Word2Vec Model directly. For example, we can use Google’s Word2Vec Model trained on Google News data, which contains 300-dimensional vectors for 100 billion words.<br>A pre-trained model is nothing more than a file containing tokens and their associated word vectors.</p><p>As we saw that the Word2Vec converts a word into a vector and not a Document (sentence) to a vector.<br>A Document is a collection of words/sentences. We need to convert a Document to a vector.<br>We could convert a Document to a vector in two ways:</p><ol><li><strong>Average Word2Vec</strong>:<br>In Average Word2Vec, we take the average Word2Vec values of all the words in a Document to get the vector for a Document.<br>It is a simple way to leverage the Word2Vec concept to build vectors for texts.<br>Average Word2Vec works fairly well but is not perfect.</li><li><strong>TF-IDF Word2Vec</strong>:<br>TF-IDF weighted Word2Vec is a weighted average of the words based on their TF-IDF values.</li></ol><p>The formula for Average weighted Word2Vec and TF-IDF weighted Word2Vec is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*OygCfTj34o0SMBH9uwTtzQ.png" /><figcaption>Formulae for Average Word2Vec and TF-IDF Word2Vec</figcaption></figure><h4>The disadvantage of Average Word2Vec</h4><p>As we have the intention to convert a text into a numerical vector, averaging Word2Vec of words is a very naïve way to capture information about the sentence.</p><p>TF-IDF weighted Word2Vec is better than simple Average Word2Vec as it performs the weightage based on the importance of the words.</p><p>Still, these two techniques are not the best way to convert a text into vectors as when we average, we inherently lose information.</p><h3>Doc2Vec</h3><p>We can probably guess this technique based on its name. Doc2Vec stands for <strong>Document to Vector</strong>.<br>Instead of creating a vector for each word and then taking the average to find the vector representation of text, this technique creates a vector for each document or collection of texts.</p><p>The goal is the same as Word2Vec.<br>Just as the Word2Vec pre-trained Models, we do have pre-trained Doc2Vec models trained on a very large corpus of texts like Wikipedia or Google News.</p><p>The beauty of the Doc2Vec Model is that it cuts the consolidation step as we have in the Word2Vec Model.<br>We can directly pass a Document to the Doc2Vec Model and get a vector representation of it.</p><p>This is a much easier process to use for Machine Learning than Word2Vec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*mPjfWl8NPyGeuLJ4SW7qWQ.png" /><figcaption>Doc2Vec Model: Input and Output</figcaption></figure><h3>Summary</h3><p>These are some of the basic techniques for converting a text into numerical vectors and can be used as Featurization Techniques in Machine Learning.</p><p>One can also explore some of the advanced embedding techniques like <a href="https://arxiv.org/abs/1803.11175">Universal Sentence Encoder</a>, <a href="https://keras.io/api/layers/core_layers/embedding/">Embedding Layer</a> in Neural Networks, <a href="https://arxiv.org/abs/1810.04805">BERT</a>, etc.</p><p>Let me summarize the different techniques learned through a mind map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_TnSMxld2pYGwclt_bx1Q.png" /><figcaption>Mind map of different embedding techniques covered in this article</figcaption></figure><h3>References</h3><ul><li><a href="https://algorithmia.com/blog/the-importance-of-machine-learning-data">https://algorithmia.com/blog/the-importance-of-machine-learning-dat</a>a</li><li><a href="https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf/">https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf</a></li><li><a href="https://en.wikipedia.org/wiki/Word2vec">https://en.wikipedia.org/wiki/Word2vec</a></li><li><a href="https://en.wikipedia.org/wiki/Main_Page">Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2b97ab9b895" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/text-to-numerical-vector-conversion-techniques-f2b97ab9b895">Text to Numerical Vector Conversion Techniques</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>