<?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 Sarbari Roy on Medium]]></title>
        <description><![CDATA[Stories by Sarbari Roy on Medium]]></description>
        <link>https://medium.com/@roysubs1992?source=rss-ef87cf3f5b24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VzGbwI9B3JmmKWlCo2wAog@2x.jpeg</url>
            <title>Stories by Sarbari Roy on Medium</title>
            <link>https://medium.com/@roysubs1992?source=rss-ef87cf3f5b24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:26:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roysubs1992/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[Imbalanced Data : 10 Proven Strategies for Handling Skewed Data]]></title>
            <link>https://medium.com/@roysubs1992/unlock-data-analysis-success-learn-the-10-proven-strategies-for-handling-skewed-datasets-b58a2f24a650?source=rss-ef87cf3f5b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58a2f24a650</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[resampling]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <dc:creator><![CDATA[Sarbari Roy]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 18:07:27 GMT</pubDate>
            <atom:updated>2023-06-12T10:39:06.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>A compressive guide for handling class imbalance in data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yUW9t6rjMTvr1E5J2k9DQ@2x.jpeg" /><figcaption>Photo by Gustavo Torres on Unsplash</figcaption></figure><p>Ever tried predicting Credit Card Fraud? It is a classic problem in the Banking industry to predict if certain credit card transaction is fraudulent or not. Let’s say You have past credit card transaction records, you can build a nice classification model using that data, but when it’s time for the truth, it is quite possible that, your model is not predicting any transaction as fraud. According to this model, all transactions are legitimate and never ever there’s going to be fraud. Why does this happen? Is it a poor model? let’s look at the accuracy.</p><p>Accuracy is 99.27%. Is that even possible?</p><p>: Yes. It happened due to data imbalance. You are looking at the correct accuracy number, but <strong>accuracy is not the metric you should be looking at.</strong></p><h3>Understanding data imbalance</h3><p>Data imbalance occurs when one class significantly outweighs the others in the data. For example, in a medical diagnosis dataset, the number of healthy patients may far exceed the number of patients with a specific disease. In credit card fraud detection, The majority of transactions are legitimate, while fraudulent transactions form a small fraction of the dataset.</p><h3>Challenges and Consequences</h3><p>In the above Credit Card fraud example, our dependent variable <em>transaction credibility</em> has two classes: Fraud and Legitimate. However, thankfully for the bank, credit card transactions generally have a very less ( &lt; 1%) portion of frauds, the rest are legitimate transactions. This means <em>Legitimate</em> class is outweighing the <em>Fraud</em> class.</p><p>After building a model with this data, if the model predicts everything as legitimate, in that case also Accuracy would be very high. Here is how :</p><p><em>Overall Accuracy</em></p><p><em>= Correctly Classified Transactions/ Total Transactions</em></p><p><em>= Percentage of Legitimate Transactions (since Legitimate transactions are all correctly classified)</em></p><p><em>= 99.27% (Accuracy is very high)</em></p><blockquote>Accuracy for Legitimate class</blockquote><blockquote>= Correctly classified Legitimate transaction/ total Legitimate transactions</blockquote><blockquote>= 100 %</blockquote><blockquote>Accuracy for Fraud transactions</blockquote><blockquote>= Correctly Classified Fraud transactions/ Total Fraud transactions</blockquote><blockquote>Since the model didn’t classify anything as Fraud,</blockquote><blockquote>= 0%</blockquote><p>This is where the problem lies. <strong>We want to detect fraud and our fraud detection accuracy itself is 0%</strong>. That’s the blunder our models run into if data imbalance is not handled.</p><h3>How to handle data imbalance?</h3><ol><li><strong>Collect more data — </strong>If possible, gather more data, especially for the minority class. Increasing the number of samples in the minority class can provide the model with more information to learn from and improve its ability to generalize.</li></ol><p><strong>2. Resampling — </strong>You can modify the class distribution by either oversampling the minority class, undersampling the majority class, or a combination of both. Here are some popular resampling methods</p><ul><li><strong>Random Oversampling —</strong> This technique randomly duplicates samples from the minority class to increase its representation in the dataset. It helps to balance the class distribution but may lead to overfitting if not carefully applied.</li><li><strong>Random Undersampling — </strong>This technique randomly removes samples from the majority class to reduce its dominance in the dataset. It helps balance the class distribution but may discard potentially useful information and lead to information loss.</li><li><strong>Cluster Centroids — </strong>This method selects centroids from the majority class by clustering techniques and reduces the number of majority class samples. It aims to retain the representative information of the majority class while alleviating the class imbalance.</li><li><strong>NearMiss —</strong> NearMiss is an undersampling technique that selects samples from the majority class based on their proximity to the minority class instances. It chooses samples that are closest to the minority class instances, effectively preserving the boundary information.</li><li><strong>Edited Nearest Neighbors (ENN) —</strong> ENN is an undersampling technique that removes samples from the majority class if their class label is misclassified by their nearest neighbours. It aims to remove noisy samples that might negatively affect the classification performance.</li><li><strong>Combination of Oversampling and Undersampling — </strong>This approach combines oversampling the minority class with undersampling the majority class. By oversampling and undersampling simultaneously, it aims to capture the important patterns of both classes while balancing the class distribution.</li></ul><p>3. <strong>Class weight balancing (Penalising) — </strong>Assign different weights to the classes during model training to give higher importance to the minority class. This can be achieved by adjusting the class weights in the loss function or using algorithms that inherently support class weights, such as scikit-learn’s <em>class_weight</em> parameter.</p><p>4. <strong>Data Augmentation —</strong> Generating synthetic data for the minority class can help alleviate class imbalance. SMOTE and ADASYN are some popular data augmentation techniques .</p><ul><li><strong>Synthetic Minority Over-sampling Technique (SMOTE) — </strong>SMOTE (Synthetic Minority Over-sampling Technique) create synthetic samples based on the characteristics of existing minority class samples.</li><li><strong>Adaptive Synthetic (ADASYN) —</strong> ADASYN is an extension of SMOTE that generates more synthetic samples for the minority class instances that are harder to learn. It considers the distribution of the feature space for each minority class sample and generates synthetic samples proportionally.</li></ul><p><strong>5. Generating new features for Improved Discrimination — </strong>New features can be engineered to capture characteristics or patterns that are more discriminative for the minority class. By incorporating domain knowledge or performing feature engineering techniques, you can create features that highlight important aspects specific to the minority class, making it easier for the model to learn and make accurate predictions. This is particularly relevant when the minority class has distinct attributes or exhibits unique patterns that are not adequately captured by the existing features.</p><p><strong>6. Ensemble methods</strong> — Ensemble methods such as bagging and boosting can be effective in handling class imbalance. They involve training multiple models and combining their predictions to improve overall performance. Techniques like Adaptive Boosting (AdaBoost) and Gradient Boosting (XGBoost, LightGBM) can be useful for imbalanced datasets.</p><p><strong>7. Adjusting the decision threshold —</strong> By changing the threshold for classification, you can <strong>control the trade-off between precision and recall</strong>. In imbalanced datasets, it’s common for models to have high precision but low recall. By lowering the decision threshold, you can increase the sensitivity of the model to the minority class, but this may come at the expense of more false positives.</p><p><strong>8. Collecting more diverse data —</strong> Sometimes, imbalances arise due to biases in the data collection process. Ensuring a more <strong>diverse</strong> and representative dataset can help mitigate the imbalance problem.</p><p><strong>9. Algorithm Selection —</strong> Some machine learning algorithms are inherently more robust to class imbalance than others. Algorithms like Random Forests and Support Vector Machines (SVM) can handle imbalanced data more effectively.</p><p><strong>10.</strong> <strong>Performance Metrics</strong>: Traditional evaluation metrics like accuracy can be misleading in the presence of imbalanced data, as happened in the above Fraud Prediction Model. A model that predicts the majority class for every instance can achieve high accuracy, even though it fails to capture the nuances of the minority class(es). It is essential to consider alternative evaluation metrics such as precision, recall, F1-score, or area under the ROC curve (AUC-ROC) that provide a more comprehensive assessment of model performance.</p><h3>Conclusion</h3><p>The challenges posed by imbalanced data can have significant consequences on model performance, particularly for the minority class. While handling Class Imbalance, the choice of strategy depends on the specific problem and dataset. I would suggest you experiment with multiple techniques and evaluate their performance using appropriate evaluation metrics such as precision, recall, F1-score, or area under the receiver operating characteristic curve (AUC-ROC).</p><p>Thank you for reading! I hope this blog has been helpful in guiding you towards effective solutions for handling class imbalance. If you have any further questions or need assistance, feel free to reach out. Happy modelling!</p><p>Which one of these techniques have you already used? Share in the comments :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58a2f24a650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Central Limit Theorem Simplified with Python!]]></title>
            <link>https://ai.plainenglish.io/boost-your-statistical-skills-central-limit-theorem-demystified-with-python-e26efb572232?source=rss-ef87cf3f5b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26efb572232</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sarbari Roy]]></dc:creator>
            <pubDate>Wed, 31 May 2023 16:50:23 GMT</pubDate>
            <atom:updated>2024-02-28T19:19:39.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Central Limit Theorem in Python!</h3><h4>A simplified explanation of CLT with Python demonstation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzcDqHnChYZvuGYtxNQfEQ@2x.jpeg" /><figcaption>Photo by Afif Ramdhasuma on Unsplash</figcaption></figure><p>Data scientists often face the challenge of working with limited samples of data, yet they need to make meaningful inferences about larger populations based on these samples. This is where the <strong>Central Limit Theorem (CLT)</strong> comes into play as a fundamental concept.</p><p>In predictive modelling, Central Limit Theorem allows us to assume a normal distribution for errors or residuals, enabling the application of powerful techniques like linear regression, and time series analysis. And if you are wondering why the normal distribution arises so commonly (from the heights of students in a class to the lifetime of light bulbs), CLT is behind that as well.</p><h3><strong>Learning Objectives</strong></h3><p>In this article, we will first look at the formal definition of CLT followed by a simplified explanation with a real-life example. Finally, to make our understanding crystal clear, we will also verify this theorem on a synthetic dataset using Python code.</p><p>Before starting with CLT, we must understand the most popular distribution of all time: The Normal distribution.</p><h3>What is normal distribution:</h3><p>Normal or Gaussian distribution is a statistical pattern that often appears in various aspects of our everyday lives. If you plot the frequencies of a class full of students&#39; heights, with height in feet on the <em>x-axis</em> and count of students on the <em>y-axis</em>, you would see a bell-shaped plot. That’s Normal Distribution. Very few students will be very short (left tapered edge), the majority will have a moderate height (peak in the middle), and again very few will be very tall (right tapered edge). It is also known as a bell curve because of its characteristic shape, resembling a symmetrical curve that peaks in the middle and tapers off towards the edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*SoMJ5P57PmvvHONGo3nioQ.png" /></figure><p>In a Normal distribution, the average, the median, and the mode (the most common value) are all the same and located at the peak of the curve. The curve is symmetric around this point, meaning that an equal number of values fall on both sides of the peak. As you move away from the peak, the number of values gradually decreases, forming the tapering edges of the curve.</p><p>Now that we know what is Normal Distribution, it will be a cakewalk going through the Central limit Theorem.</p><h3>What is Central limit theorem?</h3><blockquote>Given a dataset with unknown distribution (it could be uniform, binomial or completely random), the sample means will approximate the normal distribution.</blockquote><h3>Central Limit Theorem: Simplified</h3><p>Let’s break that down. Imagine we have the exam scores of a group of 100 students who took a very tough exam. If you draw a curve of their exam scores on a graph, the curve is likely to be skewed to the right. In this case, most students would have low test scores, and a smaller number of people would have high scores that skew the curve toward the right of the graph(chart below). this asymmetry tells that the scores are clearly not distributed Normally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*KPV2D3U49_7cyvN_k4CXbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPvjA0_rSckgpFOLF5wuvA.png" /></figure><p>Notice the histogram on the right, it shows how the scores are distributed in a positively skewed manner.</p><p>Now the fun part, let’s take 30 scores from this chart randomly and calculate their average. We call it <strong>1st sample mean</strong>.</p><p>Similarly, let’s take another set of 30 scores chosen randomly from this 100 and note down the average of those 30 scores (2nd sample mean)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYhr8ir_NzqicW0rmde0eQ.png" /></figure><p>Continue this process<em> n</em> times and we will end up having <em>n</em> such sample means.</p><p>Let’s plot the histogram of these <em>n</em> sample means. Histogram visualises how these sample means are distributed.</p><p>Central Limit Theorem says, if <em>n</em> is very high, it means if we keep on repeating this process for a long time, this histogram will form a bell-like shape. OR, In statistical terms, it will follow Normal distribution.</p><p>Correctly so, for <em>n</em> = 10000, we got this histogram by plotting the frequencies of the sample means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVofwhP7_A0GLcEoa8hL_A.png" /></figure><p>What’s amazing about the CLT is that even if the original distribution of scores in the exam was weird or lopsided, the average scores of the samples is still following this symmetric normal distribution.</p><p>Now we are ready to answer this question:</p><h3>Why is normal distribution found so commonly in nature and data?</h3><p>In simpler terms, the CLT tells us that many natural phenomena are the result of numerous underlying factors working together. Each factor contributes a small amount to the overall outcome, and when these contributions are combined, their collective effect follows a normal distribution. This is why we often observe the normal distribution appearing in various aspects of our lives, as diverse phenomena can be seen as a sum or average of multiple independent factors.</p><h3>Verifying CLT ( Using Exam Score data)</h3><p>Now that the Theorem is clear to us, let us see how we can use Python to validate it.</p><p>I have loaded this data into a Jupyter Notebook. The following code selects a set of 30 scores randomly and calculates their average.</p><pre>import pandas as pd<br>import random <br>import numpy as np<br><br>#reading data from csv<br>dt = pd.read_csv(&quot;score_data.csv&quot;)<br>score_vector = dt.Score<br><br>#selecting 30 scores randomly<br>sample1 = random.sample(set(score_vector), 30)<br><br>#calculating sample mean of First sample<br>np.mean(sample1)</pre><p>Repeating the sampling <em>n</em> times and storing the sample means.</p><pre>import pandas as pd<br>import random <br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Reading data from csv<br>dt = pd.read_csv(&quot;score_data.csv&quot;)<br>score_vector = dt.Score<br><br># Setting the value of n<br>n = 10000<br><br># Initialising list where sample means will be stored<br>ls = []<br>for i in range(0,n):<br><br>    #selecting 30 scores randomly<br>    sample1 = random.sample(set(score_vector), 30)<br><br>    #calculating sample mean of 30 scores and appending with the existing list<br>    ls = ls + [np.mean(sample1)]<br>    <br># Plotting Histograms<br>sns.distplot(a=ls, color=&#39;purple&#39;, bins = 30,<br>             hist_kws={&quot;edgecolor&quot;: &#39;black&#39;})<br><br># Adding title and axis names<br>plt.title(&#39;n = &#39;+ str(n))<br>plt.xlabel(&#39;Scores&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><p><strong>Output Histograms :</strong></p><p>For <em>n</em> = 5, 20, 100, …, 50000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*7R3efDa4lAaLZQfbTuVoGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*P8RDpC70Jq-JKAn5ScFeKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ZPXzalzFbagTrQ56dxvxyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*cReOc4AWczhCjvIhWFq5Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*snisCE9bOXi3b6CtHLB1Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*9ZdS48T0A_mna0CZS5OCjw.png" /><figcaption><strong>Distribution of Sample Means gradually converging to bell-shaped Normal Dist.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*MbhyzoHvRW7sJqTIp7b1Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*3AojiqFhzOnZgKMoZIBodw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*mSBMYN5Qy2FxrCxK4jsucg.png" /></figure><p>We can clearly see how the histogram tends to look more and more like Normal distribution’s. That’s Central Limit Theorem in action :)</p><h3>Verifying CLT on synthetic data ( drawn Samples from a Poisson distribution)</h3><p>Now we will draw samples from a distribution that is <strong>not symmetric/bell-shaped</strong> and show that the distribution of its sample means still converges to a Normal Distribution. For this exercise, I have chosen Gamma(a,b) distribution, where a and b are the shape and scale parameters. Gamma distribution is <strong>heavily skewed</strong> if the shape parameter is low.</p><p>We will draw 100 values from a Gamma(1,10) random variable. This is our base data (like 100 exam score data) for testing out CLT.</p><pre>#Generating 100 samples from Gamma distribution<br>s = np.random.gamma(1, 10, 100)<br><br># Display histogram of the sample:<br>sns.distplot(a=s, color=&#39;red&#39;,<br>             hist_kws={&quot;edgecolor&quot;: &#39;black&#39;})<br>plt.title(&#39;Gamma random Variable (Shape = 1, Scale = 50)&#39;)</pre><p><strong>Histogram</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*EjHGto4ZpH-E1EXkzvUmQw.png" /></figure><p>As expected the values have formed a positively skewed histogram (the right tail is longer).</p><p>The next step is selecting a sample of size = 30 from those 100 values, and then calculating the mean. This way repeat the sampling n times and store all the sample means, like we did for the exam score data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*w7g_Fpkl-5pr7oJ1FIFVEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*P_lSyGqGijSrnpav0tWTiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*kp29aEKsL86nCFKXjdamXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*jry2DARkZ6hcuH5mhLI-OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*zQInSZ_7nPMEo3a8O5aX1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Mr253GWD1bq3i2nAkMOoFQ.png" /></figure><p>See how beautifully it converges to a bell-shaped plot, even though the values are sample means from a skewed Gamma distribution.</p><h3>Conclusion</h3><p>The Central Limit Theorem is like a superhero cape for statisticians, empowering us to draw robust conclusions and make confident predictions even in the face of complex data. It’s a fundamental concept that has revolutionized the world of statistics and plays a pivotal role in decision-making across various industries.</p><p>Let’s celebrate this extraordinary theorem that has shaped the way we understand and interpret data! If you’re fascinated by the power of statistics and want to learn more, drop a comment below or connect with me. I’m always excited to collaborate and dive into data-driven discussions :)</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26efb572232" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/boost-your-statistical-skills-central-limit-theorem-demystified-with-python-e26efb572232">Central Limit Theorem Simplified with Python!</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Ways to Handle Missing Values in Data]]></title>
            <link>https://ai.plainenglish.io/12-ways-to-handle-missing-values-in-data-4f5de4af064d?source=rss-ef87cf3f5b24------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5de4af064d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[missing-values]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Sarbari Roy]]></dc:creator>
            <pubDate>Thu, 25 May 2023 13:35:34 GMT</pubDate>
            <atom:updated>2023-05-29T21:36:20.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QS75Gx8Jv9YlNgKM" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Many machine learning algorithms fail if the dataset contains missing values. Also, sometimes missing records impact the accuracy of the whole analysis. That is why it is very important to handle missing values in the data. Let’s see how you can deal with missing values like an expert!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrJiUrLNcKurZlQ72P6VnA.png" /></figure><h3>1. Delete the row that has missing values</h3><p>If you have <strong>less number of missing values</strong> and your total data size is large enough for your analysis, in that case you can remove the rows that have missing data. This is a quick and dirty method that can be applied if you need to quickly analyse your data without having to handle its missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW58OFXDnmsUV2hFE_892A.png" /></figure><p><strong>Pros</strong></p><ul><li>Easy to Apply</li><li>Quick</li></ul><p><strong>Cons</strong></p><ul><li>Loss of information</li><li>Works only for smaller number of missing values and big data size</li></ul><h3>2. Delete the entire column that has missing values</h3><p>Sometimes no information is better than incomplete information. So If you have <strong>too many missing values</strong> in the same column, then you can remove the whole column from analysis to avoid having incomplete data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxdzohAaoJuu55MU_M10pQ.png" /></figure><p><strong>Pros</strong></p><ul><li>Easy to Apply</li><li>Quick</li></ul><p><strong>Cons</strong></p><ul><li>Loss of information</li></ul><h3>3. Impute missing values with Mean</h3><p>If you have missing values in a <strong>numeric column</strong> and you cannot afford to lose data by removing the entire row or column then you can impute the missing value with the mean value of the whole column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCfKCUVUcObNXhNhAlOvhg.png" /></figure><p><strong>Pros</strong></p><ul><li>No Data Loss</li></ul><p><strong>Cons</strong></p><ul><li>Only works on numeric data</li><li>Only works if no outliers</li></ul><h3>4. Impute missing values with Median</h3><p>If you have <strong>outliers in this data</strong>, then the mean would become much higher/lower than most of the values. In that case we should use median to impute missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYEfwfBpwDyV5VeSpPR20A.png" /></figure><p>Pros</p><ul><li>No Data Loss</li><li>Works on datasets with outliers</li></ul><p>Cons</p><ul><li>Only works on numeric data</li></ul><h3><strong>5. Impute missing values with Mode</strong></h3><p>If there are missing values in a <strong>categorical column</strong> then we cannot calculate its mean or median. In that case we impute missing values using the Most frequent category in the column or the Mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tljjNaWHbDvsLKk3UghfbQ.png" /></figure><p>Pros</p><ul><li>Better than deleting entire row</li></ul><p>Cons</p><ul><li>Not recommended if too many missing values</li></ul><h3>6. Impute missing values with a new category</h3><p>If your <strong>categorical column</strong> has <strong>too many missing values</strong> then it is safer create a new category for them. Like in the example below we have created a new category called ‘missing’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chdwfvzU63isgVZZxZQypg.png" /></figure><p>Pros</p><ul><li>Easy to implement</li></ul><p>Cons</p><ul><li>Adds a new feature to the analysis</li></ul><h3><strong>7. Last observation carried forward (LOCF) method</strong></h3><p>Let’s say, a student drops out of a study before the session ends, then his/her last observed score is used for all subsequent (i.e., missing) observation points. This is called Last observation carried forward method or <strong>Forward fill</strong>. This method is only applicable to <strong>Longitudinal data</strong> (Repeated Measure per subject). Similarly we can also do <strong>Backward Fill</strong> (Filling up with the next available value).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQ1-taHPRkv6Ff5pd8DNQw.png" /></figure><p>Pros</p><ul><li>Better than removing all records for that subject (in this case student)</li></ul><p>Cons</p><ul><li>Gets influenced by outliers. Sometimes Forward/Backward fillcould be far from actuals due to outliers. For example, during Covid 19 period some exams were not taken and marks were forward filled using previous exam marks. If a student is an overall good performer, but in the latest exam somehow she could not perform well, then after applying LOCF she will be given a low score, which is far from the reality. Here her marks in previous exam were outliers and the LOCF method got impacted by that.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzJnZNcOM4VfbT9TXd4gBQ.png" /></figure><p>Same thing applies to the scenario if an average performer student accidentally got very high marks in the latest exam, and scores in next exams are imputed based on those good marks.</p><h3>8. <strong>Interpolate Missing Values</strong></h3><p>It is also a good idea to interpolate missing values using the rest of the values in the series. Interpolation means completing the chart. It could be completed using a line, using a curve. And then fill in the missing value using the data points that fall on the line or the curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymN-Nr4cqsInkfkV65jKYw.png" /></figure><p>Pros</p><ul><li>More accurate than forward or backward fill</li></ul><p>Cons</p><ul><li>Does not work well if other values in the column vary a lot</li></ul><pre>import interpolate </pre><p>In Python we have an inbuilt function called interpolate under pandas library which imputes missing values by interpolating and it allows us to choose if we want ‘polynomial’, ‘linear’, ‘quadratic’ interpolation.</p><h3>9. Use IterativeImputer or Regression</h3><p>If the variable that has missing values is related to another column in the dataset then we can impute the missing values using a regression model. In this data we have name, age and salary. If age and salary are related to each other such that people with lower age are likely to have lower salary, in that case the best way to impute missing values would be running a regression model of salary → age and then predict the missing salary values by using regression model on their corresponding age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxbmbRudpdtvgHlpVz6o0A.png" /></figure><p>It is very easy to do in python using <em>IterativeImputer()</em> function from sci-kit learn Library.</p><p>Pros</p><ul><li>More accurate than forward or backward fill</li></ul><p>Cons</p><ul><li>Requires One or more columns that are correlated to missing value column</li><li>Does not work well if the underlying relationship is not significant</li></ul><h3>10. Nearest Neighbours Imputations (KNNImputer)</h3><p>For example, if Salary column has missing values for age 25 and tenure 2 years, this method will try to find the employees with the closest possible age and tenure. and take an average of their salaries. This is called <strong>K Nearest Neighbour Imputation </strong>method.</p><p>In python we have KNNImputer in <strong>sklearn</strong> library that can impute missing values using this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrPTHjUpLsb1z5AXbLcbTA.png" /></figure><p>Pros</p><ul><li>More accurate than forward or backward fill</li></ul><p>Cons</p><ul><li>Does not work well if other values in missing data column vary a lot</li></ul><h3>11. Imputation using Deep Learning Library — Datawig</h3><p>This method works very well with categorical, continuous, and non-numerical features. <strong>Datawig</strong> is a library that learns ML models using Deep Neural Networks to impute missing values in the datagram. Datawig can take a data frame and fit an imputation model for each column with missing values, with all other columns as inputs.</p><pre>import datawig<br><br>#Fit an imputer model on the train data<br>imputer.fit(train_df=df_train, num_epochs=50)<br><br>#Impute missing values and return original dataframe with predictions<br>imputed = imputer.predict(df_test)</pre><p>Pros</p><ul><li>More Accurate as compared to other approaches</li></ul><p>Cons</p><ul><li>May take long time to run</li></ul><h3>12. Use Algorithms that support missing values</h3><p>Some of the Machine learning or Data Mining algorithms support missing values. For example K Nearesr Neighber Algorithm, Naive Bayes. These algorithms can be used when the dataset contains null or missing values.</p><p>Pros</p><ul><li>No need to handle missing values</li></ul><p>Cons</p><ul><li>Limits to certain data analysis approaches/algorithms</li></ul><h3>Conclusion</h3><p>Every data is different and before handling missing values we should always understand the data, how the missing values column is related to other columns, what is the data type of missing value column, what percentage of the data is missing. This is going to help us find an appropriate method for missing value imputation.</p><p>Reference</p><p>[1] Datawig: <a href="https://github.com/awslabs/datawig">https://github.com/awslabs/datawig</a></p><p>Thank You for Reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5de4af064d" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/12-ways-to-handle-missing-values-in-data-4f5de4af064d">12 Ways to Handle Missing Values in Data</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>