<?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[Code the Dice - Medium]]></title>
        <description><![CDATA[Follow to learn and experience beautiful moments of Data Science and Machine Learning. - Medium]]></description>
        <link>https://medium.com/code-the-dice?source=rss----a3ba458e5453---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Code the Dice - Medium</title>
            <link>https://medium.com/code-the-dice?source=rss----a3ba458e5453---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:58:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/code-the-dice" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Accuracy Paradox. How not to fall into the trap of unbalanced dataset.]]></title>
            <link>https://medium.com/code-the-dice/accuracy-paradox-how-not-to-fall-into-the-trap-of-unbalanced-dataset-96e227880b8c?source=rss----a3ba458e5453---4</link>
            <guid isPermaLink="false">https://medium.com/p/96e227880b8c</guid>
            <category><![CDATA[accuracy-paradox]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[accuracy-and-precision]]></category>
            <dc:creator><![CDATA[Vitalii Panchyk]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 08:46:00 GMT</pubDate>
            <atom:updated>2020-11-04T08:46:00.742Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s no secret that when working with data in the field of machine learning (and not only), a significant part of the time is spent on studying the dataset, cleaning the data, feature engineering, and only a relatively small part of the efforts goes to building, evaluating and tuning our models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jflfv6Xfwcq55iDUqdTSpw.png" /></figure><p>This distribution of time is quite reasonable, since the accuracy and reliability of our results directly depends on the quality and convenience of our dataset.</p><p>But sometimes, due to lack of time or sheer laziness, data scientists ignore these important steps, hoping that smart classification or regression algorithms will figure out the data themselves.At this point, there is a pretty high probability of getting a low-quality or even useless model and, as a result, unreliable results.</p><p>In this article I will give an example of one of these unpleasant situations (the Accuracy Paradox) and show you how to deal with an unbalanced dataset in order to maintain the quality of the model.</p><p>I used a dataset from “Health Insurance Cross Sell Prediction” task on <a href="https://www.kaggle.com/anmolkumar/health-insurance-cross-sell-prediction">Kaggle</a>. In short, <strong>our task</strong> is to build a model to predict whether the health insurance policyholders from past year will also be interested in Vehicle Insurance provided by the company.</p><p>Feel free to access my source code for this project on my <a href="https://github.com/vitaliipanchyk/vehicle_insurance.git">Github</a>. In the README.txt you will find a short description of all files.</p><h3>Part 1: Accuracy Paradox &amp; Imbalanced dataset</h3><p>For the start, lets import all packages needed and load our data.</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from matplotlib import pyplot as plt<br>import seaborn as sns</pre><pre># models<br>from sklearn.linear_model import LinearRegression<strong>,</strong>LogisticRegression<strong>, </strong>RidgeClassifier<strong>, </strong>SGDClassifier<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.naive_bayes import GaussianNB<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn import metrics<br><br>#loading data<br>data = pd.read_csv(&quot;6.Train.csv&quot;)</pre><p>Now let’s take a look at our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOLHpcNOXIHYf_vGKz4yGw.png" /></figure><p>It seems that we can drop “id” feature. We also need to turn “Gender”, “Vehicle_Age” and “Vehicle_Damage” columns into numeric data. Let us do these changes and look at the data again:</p><pre>#feature engineering<br>data = data.drop(&quot;id&quot;<strong>, </strong>axis=<strong>1</strong>)<br>data[&quot;Genders&quot;] = data.Gender.apply(lambda x: <strong>0  </strong>if x == &quot;Male&quot; else <strong>1</strong>)<br>data =  data.drop(&quot;Gender&quot;<strong>,</strong>axis=<strong>1</strong>)<br>data.replace({&quot;&lt; 1 Year&quot;:<strong>0, </strong>&quot;1-2 Year&quot;:<strong>1, </strong>&quot;&gt; 2 Years&quot;:<strong>2</strong>}<strong>, </strong>inplace=True)<br>data.Vehicle_Damage.replace({&quot;Yes&quot;: <strong>1, </strong>&quot;No&quot;:<strong>0</strong>}<strong>, </strong>inplace=True)<br>data.drop_duplicates(inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iJqXptXhRyZMy2An1QF5g.png" /></figure><p>Well it looks better, doesn’t it?</p><p>Since we are too lazy to take a deeper look at our dataset, we move on to preparing the training and validation datasets:</p><pre>features = data.drop(&quot;Response&quot;<strong>,</strong>axis=<strong>1</strong>)<br>targets = data[&quot;Response&quot;]<br><br>#splitting data<br>features_train<strong>, </strong>features_val<strong>, </strong>targets_train<strong>, </strong>targets_val = train_test_split(features<strong>, </strong>targets<strong>, </strong>test_size=<strong>0.2, </strong>random_state=<strong>12</strong>)</pre><p>Finally we can build our first classification model. For the start, lets try Logistic Regression and check its accuracy score:</p><pre>#building and evaluating model<br>LogReg = LogisticRegression()<br>LogReg.fit(features_train<strong>, </strong>targets_train)<br>acc_log_reg_train = round(LogReg.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_log_reg_val = round(LogReg.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;LogReg accuracy score train &quot; + str(acc_log_reg_train))<br>print(&quot;LogReg accuracy score val &quot; + str(acc_log_reg_val))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*8KMWx9p0CF1HaZtoj0LxeQ.png" /></figure><p>Wow! 88%. Not a bad result, considering that we almost did not improve our initial dataset. It seems that our model is close to be a perfect. But, lets use one more advance model evaluating metric called “f1 score” (if your first association is racing, then you probably need to read more about this metric before continuing),<strong> where 0 is the worst result and 1 is the best one:</strong></p><pre>guesses = LogReg.predict(features_val)<br>f1_score = metrics.f1_score(targets_val<strong>, </strong>guesses)<br>print(&quot;LogReg f1 &quot; + str(f1_score))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*kF3CGsSTRgILcHU1fEe8Pg.png" /></figure><p>But how? So high accuracy and so terrible f1 score. Let’s compare our predictions and true labels using .value_counts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*l-VQIDnuPYAd4LXYcnsiFQ.png" /></figure><p>It looks really crazy: our model hardly recognizes class 1 (i.e. potential buyers). Ask why? I think you can already guess what the problem is.</p><p>Try to look at the initial dataset one more time, namely at our target column (“Response”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*It4gStPUQ-OET6wDeRfR3g.png" /></figure><p>So here we see that dataset given on Kaggle has only 14 % of positive observations (who actually bought the insurance). The rest are negative observations. <strong>So, we deal with an unbalanced dataset.</strong></p><p>Therefore, our model cannot identify a positive class well. It just doesn’t have enough observations in training set to generalize.</p><p>And since the majority of observations in training and validation set are negative, and our model almost always predicts negative class, the accuracy score of this model is high. However, the predictive power of the model is close to zero.</p><p><strong>Congratulation! We just got in the “Accuracy Paradox” trap.</strong></p><p>On the other hand I have good news for you as well. There are several methods to fix the problem, and it’s not gonna take a lot of your time.</p><p>In this article I will tell about 2 simple methods for dealing with unbalanced datasets: undersampling and oversampling.</p><h3>Part 2: Undersampling</h3><p>Simply put<strong>, Undersampling</strong> is the reduction of the number of observations of the dominant class, approaching to the number of minor class observations.</p><p>We already know that our dominating class is “0” — 334 155 observations; and the minor class is “1” — 46 685 observations. Great difference. Now we need to shorten the number of minor class observations, and not necessarily to 46685, the ratio of classes can be 60/40.</p><p>I played with the numbers a little and found out that 63 000 is the optimal number of observations of the negative class that needs to be stored in our dataset. Let’s now we can do undersampling and check what we have in modified dataset:</p><pre>#undersampling<br>positive_data = data[data[&quot;Response&quot;] == <strong>1</strong>]<br>negative_data = data[data[&quot;Response&quot;] == <strong>0</strong>]<br>short_negative_data = negative_data.iloc[:<strong>63000,</strong>]<br>prepared_data = pd.concat([positive_data<strong>, </strong>short_negative_data])<br>print(prepared_data.Response.value_counts())<br>sns.countplot(prepared_data.Response)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mr6BuyFC56r_Pf5SBP5wgA.png" /><figcaption>Modified dataset</figcaption></figure><p>So, now the ratio of classes is almost 43/57, which means that our dataset is balanced enough. We can move on to splitting our general dataset on training and validation sets and finally building our model:</p><pre>features = prepared_data.drop(&quot;Response&quot;<strong>,</strong>axis=<strong>1</strong>)<br>target = prepared_data[&quot;Response&quot;]</pre><pre>#train_test_split<br>features_train<strong>, </strong>features_val<strong>, </strong>targets_train<strong>, </strong>targets_val = train_test_split(features<strong>, </strong>target<strong>, </strong>test_size=<strong>0.2, </strong>random_state=<strong>12</strong>)</pre><pre>#building and evaluating models<br>LogReg = LogisticRegression()<br>LogReg.fit(features_train<strong>, </strong>targets_train)<br>acc_log_reg_train = round(LogReg.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_log_reg_val = round(LogReg.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;LogReg accuracy score train &quot; + str(acc_log_reg_train))<br>print(&quot;LogReg accuracy score val &quot; + str(acc_log_reg_val))<br>guesses = LogReg.predict(features_val)<br>f1_score = metrics.f1_score(targets_val<strong>, </strong>guesses)<br>print(&quot;LogReg f1 &quot; + str(f1_score))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*MeHb3BCzIb5-vhy2YXt2Ug.png" /></figure><p>So, the accuracy scores of updated model is not as high as it was before, but the f1 score explicitly says that this model is far more better and can be used for predictions.</p><p>The evaluating metrics are not very high because we have reduced the total number of observations. However, you can try to do some additional feature engineering in order to improve the results.</p><h3>Part 3: Oversampling</h3><p>Oversampling is an increase in the number of minor class examples in order to balance the dataset. It can be done in different ways but this time I will use the SMOTE (Synthetic Minority Oversampling Technique) algorithm. Click <a href="https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/">here</a> to learn more. This strategy is based on the idea of generating a number of artificial examples that would be “similar” to those in the minority class, but at the same time would not duplicate them. You can find this algorithm in <a href="https://pypi.org/project/imblearn/">imblearn</a> package on python.</p><p>I picked this way because it will take only 2 lines of your code to balance the dataset. Follow me:</p><pre>features = data.drop(&quot;Response&quot;<strong>,</strong>axis=<strong>1</strong>)<br>target = data[&quot;Response&quot;]<br><br><strong>#balancing the data<br>oversampler = SMOTE(random_state=2)<br>new_features, new_targets = oversampler.fit_sample(features,target)</strong><br><br></pre><p>Now, we can check whether our dataset is balanced:</p><pre>sns.countplot(new_targets)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHJEyEoAStYKda37SEoI9w.png" /></figure><p>Yes, our dataset is already balanced. At the same time we have many observations. Let’s build several different models and evaluate them:</p><pre>LogReg = LogisticRegression()<br>LogReg.fit(features_train<strong>, </strong>targets_train)<br>acc_log_reg_train = round(LogReg.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_log_reg_val = round(LogReg.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;LogReg accuracy train &quot; + str(acc_log_reg_train))<br>print(&quot;LogReg accuracy val &quot; + str(acc_log_reg_val))<br>guesses = LogReg.predict(features_val)<br>f1_score = metrics.f1_score(targets_val<strong>, </strong>guesses)<br>print(&quot;LogReg f1 &quot; + str(f1_score))<br><br><br>gaussian = GaussianNB()<br>gaussian.fit(features_train<strong>, </strong>targets_train)<br>acc_gaussian_train = round(gaussian.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_gaussian_val = round(gaussian.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;NB accuracy train &quot; + str(acc_gaussian_train))<br>print(&quot;NB accuracy val &quot; + str(acc_gaussian_val))<br>guesses1 = gaussian.predict(features_val)<br>f1_score = metrics.f1_score(targets_val<strong>, </strong>guesses1)<br>print(&quot;NB f1 &quot; + str(f1_score))<br><br>decision_tree = DecisionTreeClassifier()<br>decision_tree.fit(features_train<strong>, </strong>targets_train)<br>acc_decision_tree_train = round(decision_tree.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_decision_tree_val = round(decision_tree.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;decision tree accuracy train&quot; + str(acc_decision_tree_train))<br>print(&quot;decision tree accuracy val&quot; + str(acc_decision_tree_val))<br>guesses2 = decision_tree.predict(features_val)<br>f1_scoreDT = metrics.f1_score(targets_val<strong>, </strong>guesses2)<br>print(&quot;decision tree &quot; + str(f1_scoreDT))<br><br>KNC = KNeighborsClassifier(n_neighbors=<strong>2</strong>)<br>KNC.fit(features_train<strong>, </strong>targets_train)<br>acc_KNC_train = round(KNC.score(features_train<strong>, </strong>targets_train) * <strong>100, 2</strong>)<br>acc_KNC_val = round(KNC.score(features_val<strong>, </strong>targets_val) * <strong>100, 2</strong>)<br>print(&quot;K Neighbor accuracy train&quot; + str(acc_KNC_train))<br>print(&quot;K Neighbor accuracy val&quot; + str(acc_KNC_val))<br>guesses3 = KNC.predict(features_val)<br>f1_scoreKNC = metrics.f1_score(targets_val<strong>, </strong>guesses3)<br>print(&quot;K Neighbor f1 &quot; + str(f1_scoreKNC))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*-JJBKK4kl3xRhAlDYa73WQ.png" /></figure><p>Well, I think this is a victory! The results of the models after oversampling are very good. Just look at the decision tree and K-Neighbor classifier scores!</p><p>I hope this article was useful for you. Feel free to comment on this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e227880b8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-the-dice/accuracy-paradox-how-not-to-fall-into-the-trap-of-unbalanced-dataset-96e227880b8c">Accuracy Paradox. How not to fall into the trap of unbalanced dataset.</a> was originally published in <a href="https://medium.com/code-the-dice">Code the Dice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>