<?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 Kshitij Chawla on Medium]]></title>
        <description><![CDATA[Stories by Kshitij Chawla on Medium]]></description>
        <link>https://medium.com/@chawla.kshitij?source=rss-62aff9bfa826------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gB3objDRnUwQlGlCRMId1w.jpeg</url>
            <title>Stories by Kshitij Chawla on Medium</title>
            <link>https://medium.com/@chawla.kshitij?source=rss-62aff9bfa826------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:21:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chawla.kshitij/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[Step by Step guide to Predict Census Income using Classification Models]]></title>
            <link>https://medium.com/@chawla.kshitij/step-by-step-guide-to-predict-census-income-using-classification-models-c90bab497ef8?source=rss-62aff9bfa826------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90bab497ef8</guid>
            <category><![CDATA[census]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kshitij Chawla]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 14:02:29 GMT</pubDate>
            <atom:updated>2021-07-23T14:02:29.904Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Problem Statement:</strong></h3><p>This data was extracted from the <a href="http://www.census.gov/en.html">1994 Census bureau database</a>. The data set contains different information required to predict the Income of the individuals. The prediction task is to determine whether a person makes over $50K a year or not.</p><p>Attribute information:</p><p>The dataset contains the following columns-&gt;</p><ol><li>age: Age of the person.</li><li>workclass: Working class of the person.</li><li>fnlwgt: Final weight (this is the number of people the census believes the entry represents)</li><li>education: Highest education done by the person</li><li>education-num: Education number done by the person.</li><li>marital-status: Marital status of the person</li><li>occupation: occupation of the person</li><li>relationship: Relationship status of the person</li><li>race: Race of the person</li><li>sex: Sex of the person</li><li>capital-gain: Capital-gain of the person</li><li>capital-loss: Capital-loss of the person</li><li>hours-per-week: Hours per week worked by the person</li><li>native-country: Native country of the person</li><li>Income: Income status of the person</li></ol><h3><strong>Data Analysis:</strong></h3><p>First, we will import few basic Python libraries that will be required for this project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*DAHwTgu8xbSQwrrxagKfsQ.png" /></figure><p>Now we will import the dataset using pandas -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQDj_tysmxZPEFgTKN9QZw.png" /></figure><p>Here ‘df’ will be our data frame in which we have imported the dataset.</p><p>Let’s start exploring our dataset for the Census Income problem.</p><p>First step for analyzing the data is checking whether we have the right type of data in the columns or not. We can test this by checking the head of the dataset. To check the head of the dataset we can use ‘head()’ function available in pandas.</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_tqrK_0h8liJxSDgrK-ww.png" /></figure><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhTjrvK4_wQ5RpQ8C-vPoQ.png" /></figure><p>We got the head of the dataset. But the question is what does it means to have right type of data in the columns?</p><p>We can explore one example from the above head : For ‘Hours_per_week’ column we can infer that numeric i.e. Integer values should be present in this object. But further if we check the data type of the ‘Hours_per_week’ column using dtypes() function of pandas and if it turns out to be object type. This means there is a miss match between the object type that is present and object type that is required. In that case, we will be required to convert the type and correct it. But for now, let’s get back to our current dataset and its scenarios.</p><p>Further we will check what is the shape of the dataset. We can do this by using shape attribute in pandas.</p><p><em>Code/Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpInMdP9nrFfd8QMVp_6dg.png" /></figure><p>So, we have 32560 rows and 15 columns in our dataset.</p><p>Now, we will find whether the dataset contains incorrect, corrupted, incorrectly formatted, duplicate, or incomplete data.</p><p><em>Q) What can we do to check all of the above in our dataset?</em></p><p><em>A) There are various techniques to explore our dataset for the anomalies, few of them are checking null values, duplicate values, outliers, skewness and checking whether the data is normally distributed or not.</em></p><p><strong>Let’s discuss them one by one:</strong></p><p><strong>1)</strong> <strong>Checking null values:</strong></p><p>We can use the pandas inbuilt function to check the null values in the dataset:</p><p><em>Code/Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txFRo1HsSCIRpzo23YQ-SA.png" /></figure><p>We can see that there are no null values in the dataset.</p><p>We have both integer and string type values in our dataset, keeping that in mind, is this the correct result? Do we need to cross validate this? What should we do?</p><p>.</p><p>.</p><p>Yes, we need to cross validate this as in string type columns we might have null values present in the form of ‘?’, ‘- ‘or any other special character. How can we check the same in the string type column? The dataset is huge and checking values manually will cost us time and efforts. But we need not worry as we have huge number of inbuilt functions in python libraries at our hands.</p><p>We can use ‘value_count’ function in pandas to check the unique values and its count present in the columns:</p><p><em>Code/Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSsYNJhWm4CRI0x6ypHxmw.png" /></figure><p>As highlighted above, there is ‘?’ value present in the ‘Workclass’ column. Hence, null values are present in this column but according to the isnull() function there were no null values. Therefore, for string datatypes it is always better to cross validate the result. The more we explore our dataset the better result it will provide during model building.</p><p>Similarly, we can find the null values for other columns.</p><p><strong>2)</strong> <strong>Duplicate Rows:</strong></p><p>To check the duplicate rows in the dataset we will use ‘duplicated’ function available in pandas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zn8aofwrcpOijPvE_b6X0w.png" /></figure><p>We have 24 duplicated rows in the dataset.</p><p><strong>3)</strong> <strong>Outliers:</strong></p><p>We will check the outliers in the Integer/Float type columns. Various methods are available to check outliers in the dataset and we will use one of the methods i.e., by plotting Box-Plot to check the outliers in the dataset.</p><p>We will import the seaborn library to plot the boxplot.</p><p>The code for checking the outliers for the numeric columns of our dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqtoIP1xOTVjbuCmhOe-Yg.png" /></figure><p>In the above code, we have stored the Numeric/Integer/Float columns name in a list to plot their box-plot one by one.</p><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lImMoALp2BRIlrB4uSnvWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zU8my2XLRYrRwMRbJx3qvQ.png" /></figure><p>We can observe that outliers are present in all the numeric columns. How did we got to know from the above plots that outliers are present? Well, if any value is present in the plot outside of the upper limit and lower limit of the box plot that are considered as outliers.</p><p>If we need to calculate the upper/lower limit we can do it using below formula:</p><p>IQR = df[i].quantile(0.75)-df[i].quantile(0.25)</p><p>Upper_limit = df[i].quantile(0.75) + 1.5*IQR</p><p>Lowerl_imit = df[i].quantile(0.25) — 1.5*IQR</p><p>(Here ‘i’ denotes the column name)</p><p>Any values below the lower limit and any values above the upper limit will be identified as outliers.</p><p><strong>4)</strong> <strong>Skewness:</strong></p><p>Let’s check the skewness of the dataset using pandas function skew()</p><p><em>Code/ Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AERWZiR71luvFvkTHBo9OQ.png" /></figure><p>As we know that the skewness outside the range of -0.5 to +0.5 is not good for model building and in our dataset skewness for few columns is very high.</p><p>We can see that ‘Capital_gain’ and ‘Capital_loss’ columns ‘Fnlwgt’ are highly right skewed.</p><p><strong>5)</strong> <strong>Distribution of the data in columns:</strong></p><p>We can check whether the data is normally distributed or not using distance plot. We will use same sea born library to plot this graph</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AotpXdXb8C81kIiCieXsVg.png" /></figure><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEJiQIGpryEXN4hfZ_A4zw.png" /></figure><p>From above plots we can see for ‘Fnlwgt’, ‘Education_num’ and ‘Hours_per_week’ have multiple peeks in the graph which means that the data is not normally distributed.</p><p>Now, after checking anomalies in our dataset, let’s check whether there is any correlation between the columns.</p><p>We will use ‘corr()’ method to find correlation and ‘heatmap’ plot to visualize the same.</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDrcxCd1xVVpuO0Ay5BSkQ.png" /></figure><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*3rkBgC_V4XSiKpraiRI6jg.png" /></figure><p>We can see that there is very weak correlation between the Numeric columns.</p><p>Now, let’s explore our String type or we can say object type columns in the dataset.</p><p>One important thing to note, as the target variable is of string type, the exploration of the string type column might become important for us. We will discuss why it is important to observe the target column data later after visualizing the data.</p><p>So, let’s visualize the categorical columns against the Target column:</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdQ59TwL_LT1Bqt82Jt7cA.png" /></figure><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY7ZcCTsQj53_INM1DDzqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raMRELuWMEFkf-NFa8NjeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKJsd-t-Am99Xfv2SJ9nDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JNWntjaIzVLDKueLgUDfA.png" /></figure><p>Let’s discuss our findings from above graphs.</p><p>· Private Work class is majorly earning Income &lt;=50K</p><p>· Education qualification of HS-grad have income &lt;=50K</p><p>· Married-civ-spouse have &gt;50K income as compared to other marital status</p><p>· Husbands are the major earning members as compared to other relations</p><p>· Majority of the Income earning race is White</p><p>· Majority of females have income &lt;=50K</p><p>· Data in Income (target variable) is highly unbalanced</p><p>Before visualizing above graphs, we said observing target variable is important, let’s discuss it now.</p><p>From the above findings, we saw data in ‘Income’ column is highly unbalanced. Does this mean anything for us? Will this affect the model building later on?</p><p>Yes, this is the most important observation for us. The data is highly unbalanced because we have more than 25000 records for the income of &lt;=50K and only 8000 records for the income of &gt;=50K. If we train our prediction model for the dataset in this current situation, then it will be highly biased towards income &lt;=50K. We can fix this before building our model using certain python libraries specifically designed for this purpose. So, let’s move forward as we will fix this in the Model Building Section.</p><h3><strong>EDA Concluding Remark:</strong></h3><p>We found that in our dataset we have null values/missing values, after that we also checked that our dataset contains duplicate rows. For numeric values we have lots of outliers which also contributes in making our dataset skewed. Then we found that few columns are not normally distributed and the target variable is highly unbalanced. We will solve all of these to make our dataset clean and increase the model efficiency in the next section. Please note, the more we analyse/clean the dataset the better the predicting models will perform.</p><h3><strong>Pre-Processing Pipeline:</strong></h3><p>Let’s start processing our data to move one step closer for model building. Previously, we found that there are many anomalies which are required to be removed or resolved in the dataset. We will process them one by one.</p><blockquote><strong>Removing Null values:</strong></blockquote><p>There are several methods for solving Null values issue. We can remove them or replace them with Mean/Median/Mode depending upon the data present in the column.</p><p>We will replace the ‘?’ in the columns with mode of that particular column. We can also choose the remove method. But let’s assume that data is very costly and we cannot afford huge data loss. So, best method will be replacement of null or garbage values.</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*yr5wBb6knTtSOLd-SBGKAA.png" /></figure><p>Here, we have used replace method to replace the ‘?’ values with mode.</p><blockquote><strong>Removing the duplicate rows:</strong></blockquote><p>As the duplicate rows will only increase the load on the model while training and it does not help us in any way for improving the prediction models, we will drop them</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvGkz6IcopneGWdY1y8zBg.png" /></figure><blockquote><strong>Outlier treatment:</strong></blockquote><p>We found that in numeric columns there were huge numbers of outliers. Treating them is important for better prediction. There are several ways to treat outliers. Either we can remove them from the dataset or replace them with appropriate values.</p><p>But as we have discussed before we have to keep the data loss as low as possible. So, we will use the replacement method.</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*IACHp_vAuHzQb3HdOg46NA.png" /></figure><p>In the above code, we have replaced the outliers with upper limit and lower limit as per the Bar-plot.</p><blockquote><strong>Scaling the data:</strong></blockquote><p>While visualising the dataset, we observed that few columns are not normally distributed. We can fix this issue by scaling the data. There are several ways to scale the data like using Standard scaler, Min-Max scaler etc. We will use Min-Max scaler in this case:</p><p>The Min-Max scaler is available in ‘sklearn’ library.</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXbo9kXEXMJZASWZC5ihiA.png" /></figure><p>Did you notice that first we dropped few columns? And here the question arises why did we dropped them? Answer to this question is very simple. If we observe that we dropped only categorical columns or we can say string type columns, scaling of the data is only applied on numeric data. Hence, we dropped the non-required columns before scaling the data. We need not worry as we will join them later on to our dataset.</p><blockquote><strong>Removing Skewness:</strong></blockquote><p>The skewness can be removed using several different methods. We can use log, sqrt, cbrt, binning etc methods for this. But here we will use binning method for our dataset. Here, we will again use python library to use the power_tranform the dataset.</p><p>The ‘power_transform’ is available in ‘sklearn.preprocessing’</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rG0nTRLmc9nXroKMow9ahw.png" /></figure><p>Now, the only thing left is joining the categorical strings back to the transformed or we can anomaly free dataset. But are we sure that this is enough? Do we need to focus on anything else? Can we start building the data set yet?</p><p>Well, we have not fully prepared our dataset yet for model training. The models only take numeric values as input/output for the training/testing. But we have categorical/string values present in the dataset. Hence, we will be required to convert the categorical values into numeric values. We can do this using Labels.</p><p>We will again use the ‘sklearn’ library to perform the same using Label Encoders</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgjVWPykRWFM8YVBIfPGJA.png" /></figure><p><em>For target variable:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Yv-s_euZVNaes5a6OH5Ww.png" /></figure><p>Let’s join the converted categorical variables back to the final dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnlwMYxe2doukvPBCGTmYA.png" /></figure><p>Now we are ready to move onto the next phase i.e., model building</p><h3><strong>Building Machine Learning Models:</strong></h3><p>We will build Classification models for the prediction of Census Income.</p><p>First, we need to split the dataset into training set and test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28TNexs1924lWOSJsBW9dA.png" /></figure><p>Here, we are using a model to test on which random state the accuracy will be best, so that we can do the train-test slit on that random state. Below we got random state as 47, so we will perform the train-test split at random state 47.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-jwtOesbockrtTGj3DT-A.png" /></figure><p>Above, we have kept the 70% of data as training data and we will perform testing on the remaining 30% of data.</p><p>So, shall we start building our model? Wait, if we remember correctly, we have observed that our target variable was unbalanced and will affect our model efficiency and make our model biased and till now we have not fixed it. Let’s fix this imbalance now using SMOTE technique:</p><p>For this we will need to import ‘SMOTE’ from ‘imblearn’ library as below:</p><p>from imblearn.over_sampling import SMOTE</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2xvGDIfOpF-9_vdJjHtJw.png" /></figure><p>Now that we have overcome the imbalance, let’s finally move into model building phase.</p><p>We will build many different models. We will not discuss how the model internally works but we will compare different parameters to conclude which model is predicting the best and then perform hyper tuning on the selected model.</p><blockquote><strong>Logistic regression:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w3z35P7YNvf0NRGgu2U5cQ.png" /></figure><blockquote><strong>Decision Tree:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMgNxBW2BuS1aKka4beYjw.png" /></figure><blockquote><strong>Random Forest:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEx2XrA6ht4-Tj-FSdKtiw.png" /></figure><blockquote><strong>Naïve Bayes:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5kPpm479z8_K2ynDeWOVQ.png" /></figure><blockquote><strong>SVM:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dm_PTeBDkuyeI2g7jIAmig.png" /></figure><p>Let’s summarize the data from the above models in a table to get more clear view and compare the different models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*LiOL2hhB5LZn5xLhZ40vZw.png" /></figure><p>We should keep in mind that we should compare all parameters for both 0 &amp; 1. If we observe the above table carefully, we can see that Random Forest model is performing the best by keeping both 0 &amp; 1 parameters into consideration.</p><p>Let’s Cross Validate the score by performing Cross Validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*F6OlBoewXQmVo_tJqoiixw.png" /></figure><p>We have calculated the score by subtracting accuracy from the cross-validation score. As we can observe that Random Forest is having 0 difference and have highest accuracy. It is the best performing algorithm for this dataset.</p><p>Hence, let’s Hyper tune the Random Forest model further.</p><p>We will use ‘GridSearchCV’ from ‘sklearn’ library for the Hyper tuning, It tries different combinations of the parameters that we will pass and check which parameter suits the model best:</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmsyaM7tBHZXvGN2E1A-YA.png" /></figure><p>Now let’s check the best parameters for the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80FJJf6JLJrxYolowmODTA.png" /></figure><p>We have the best parameters now, let’s build our final model i.e., Random Forest model using these parameters:</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZIkvLaA4Bd4zl7SQ6eKew.png" /></figure><p>Let’s compare the old model values and values of the model after hyper tuning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*1vwI7Un66kVTo_Mq2w_P5Q.png" /></figure><p>We can observe that precision for 0 has increased as well as, recall for 1 has also increased.</p><p>Now, the final check to confirm and conclude that Random Forest model is performing the best is by plotting AUC-ROC curve</p><p><em>Code:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*J6K4yZJWqv15AkPg8LKYJg.png" /></figure><p><em>Output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*721KSodPZKozxSLEaAJ_Uw.png" /></figure><p>The AUC-ROC curve takes True-Positive Rate, True-Negative Rate, False-Positive Rate and False-Negative Rate into the consideration</p><p>We can see that AUC value for Random Forest is 0.883 which is the largest in our models. Hence, Random Forest model is the best for making predictions on the available data set of Census income.</p><h3><strong>Concluding Remarks</strong></h3><p>After several iterations of exploring and conditioning on the data, we have built a useful algorithm for predicting the Census Income. The technique applied in this project is an implementation of a simple machine learning model, the Random Forest.</p><p>We can conclude that Random Forest algorithm is performing best among all the algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90bab497ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>