This case study is about apt salary band determination. When an organization decides to hire a new employee and the question is how much salary does this person deserves based on their credentials, demographic/anagraphic details and experience?

Based on the "Census Income" data of 32,561 professionals from around the world. We will try to learn when a candidate deserves a salary greater than $50K and when they does not.

In below case study I will discuss the step by step approach to create a Machine Learning predictive model in such scenarios. You can use this flow as a template to solve any supervised ML classification problem.

The flow of the case study is as below:

  • Reading the data in python
  • Defining the problem statement
  • Identifying the Target variable
  • Looking at the distribution of Target variable
  • Basic Data exploration
  • Rejecting useless columns
  • Visual Exploratory Data Analysis for data distribution (Histogram and Barcharts)
  • Feature Selection based on data distribution
  • Outlier treatment
  • Missing Values treatment
  • Visual correlation analysis
  • Statistical correlation analysis (Feature Selection)
  • Converting data to numeric for ML
  • Sampling and K-fold cross validation
  • Trying multiple classification algorithms
  • Selecting the best Model
  • Deploying the best model in production

I know its a long list!! Take a deep breath... and let us get started!

Reading the data into python

This is one of the most important steps in machine learning! You must understand the data and the domain well before trying to apply any machine learning algorithm.

The data has one file "SalaryData.csv". This file contains the historical census data data of 32,561 working professionals from all over the world indicating whether they earn more than $50K or not.

The goal is to learn from this data and predict if a new candidate can be hired with a salary more than $50K or not?

Data description

The business meaning of each column in the data is as below

  • age: Age of the employee
  • workclass: Which type of organization the employee works in? State-gov/Private etc.
  • fnlwgt: final weight, which is the number of units in the target population that the responding unit represents
  • education: The highest education of the employee
  • education_num: numeric code for the highest education of the employee
  • marital_status: The marital status of the employee
  • occupation: The type of job
  • relationship: Type of relationship in? Husband, wife etc.
  • race: Which race the employee belongs to
  • sex: Gender of the employee
  • capital_gain: How much capital gains does the employee gets in an year
  • capital.loss: How much capital loss does the employee bears in an year
  • hours_per_week: How many hours the employee works in a week?
  • native_country: Which country the employee is working?
  • SalaryGT50K: Is the salary greater than $50,000K or not

More detailed information about this dataset can be found here

In [4]:
# Supressing the warning messages
import warnings
warnings.filterwarnings('ignore')
In [5]:
# Reading the dataset
import pandas as pd
import numpy as np
SalaryData=pd.read_csv('/Users/farukh/Python Case Studies/SalaryData.csv', encoding='latin')
print('Shape before deleting duplicate values:', SalaryData.shape)

# Removing duplicate rows if any
SalaryData=SalaryData.drop_duplicates()
print('Shape After deleting duplicate values:', SalaryData.shape)

# Printing sample data
# Start observing the Quantitative/Categorical/Qualitative variables
SalaryData.head(10)
Shape before deleting duplicate values: (32561, 15)
Shape After deleting duplicate values: (32537, 15)
Out[5]:
age workclass fnlwgt education education_num marital_status occupation relationship race sex capital_gain capital.loss hours_per_week native_country SalaryGT50K
0 39 State-gov 77516 Bachelors 13 Never-married Adm-clerical Not-in-family White Male 2174 0 40 United-States 0
1 50 Self-emp-not-inc 83311 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 0 0 13 United-States 0
2 38 Private 215646 HS-grad 9 Divorced Handlers-cleaners Not-in-family White Male 0 0 40 United-States 0
3 53 Private 234721 11th 7 Married-civ-spouse Handlers-cleaners Husband Black Male 0 0 40 United-States 0
4 28 Private 338409 Bachelors 13 Married-civ-spouse Prof-specialty Wife Black Female 0 0 40 Cuba 0
5 37 Private 284582 Masters 14 Married-civ-spouse Exec-managerial Wife White Female 0 0 40 United-States 0
6 49 Private 160187 9th 5 Married-spouse-absent Other-service Not-in-family Black Female 0 0 16 Jamaica 0
7 52 Self-emp-not-inc 209642 HS-grad 9 Married-civ-spouse Exec-managerial Husband White Male 0 0 45 United-States 1
8 31 Private 45781 Masters 14 Never-married Prof-specialty Not-in-family White Female 14084 0 50 United-States 1
9 42 Private 159449 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 5178 0 40 United-States 1

Defining the problem statement:

Create a Predictive model which can tell if a person deserves a salary greater than 50,000 dollars or not?

  • Target Variable: SalaryGT50K
  • Predictors: age, workclass, education, marital_status, occupation etc.
  • SalaryGT50K=0 The employee earns less than 50,000 dollars in a year
  • SalaryGT50K=1 The employee earns more than 50,000 dollars in a year

Determining the type of Machine Learning

Based on the problem statement you can understand that we need to create a supervised ML classification model, as the target variable is categorical.

Looking at the distribution of Target variable

  • If target variable's distribution is too skewed then the predictive modeling will not be possible.
  • Bell curve is desirable but slightly positive skew or negative skew is also fine
  • When performing Classification, make sure there is a balance in the the distribution of each class otherwise it impacts the Machine Learning algorithms ability to learn all the classes
In [6]:
%matplotlib inline
# Creating Bar chart as the Target variable is Categorical
GroupedData=SalaryData.groupby('SalaryGT50K').size()
GroupedData.plot(kind='bar', figsize=(4,3))
Out[6]:
<matplotlib.axes._subplots.AxesSubplot at 0x11756f590>

The data distribution of the target variable is satisfactory to proceed further. There are sufficient number of rows for each category to learn from.

Basic Data Exploration

This step is performed to guage the overall data. The volume of data, the types of columns present in the data. Initial assessment of the data should be done to identify which columns are Quantitative, Categorical or Qualitative.

This step helps to start the column rejection process. You must look at each column carefully and ask, does this column affect the values of the Target variable? For example in this case study, you will ask, does this column affect the salary earned by the employee? If the answer is a clear "No", then remove the column immediately from the data, otherwise keep the column for further analysis.

There are four commands which are used for Basic data exploration in Python

  • head() : This helps to see a few sample rows of the data
  • info() : This provides the summarized information of the data
  • describe() : This provides the descriptive statistical details of the data
  • nunique(): This helps us to identify if a column is categorical or continuous
In [7]:
# Looking at sample rows in the data
SalaryData.head()
Out[7]:
age workclass fnlwgt education education_num marital_status occupation relationship race sex capital_gain capital.loss hours_per_week native_country SalaryGT50K
0 39 State-gov 77516 Bachelors 13 Never-married Adm-clerical Not-in-family White Male 2174 0 40 United-States 0
1 50 Self-emp-not-inc 83311 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 0 0 13 United-States 0
2 38 Private 215646 HS-grad 9 Divorced Handlers-cleaners Not-in-family White Male 0 0 40 United-States 0
3 53 Private 234721 11th 7 Married-civ-spouse Handlers-cleaners Husband Black Male 0 0 40 United-States 0
4 28 Private 338409 Bachelors 13 Married-civ-spouse Prof-specialty Wife Black Female 0 0 40 Cuba 0
In [8]:
# Observing the summarized information of data
# Data types, Missing values based on number of non-null values Vs total rows etc.
# Remove those variables from data which have too many missing values (Missing Values > 30%)
# Remove Qualitative variables which cannot be used in Machine Learning
SalaryData.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 32537 entries, 0 to 32560
Data columns (total 15 columns):
age               32537 non-null int64
workclass         32537 non-null object
fnlwgt            32537 non-null int64
education         32537 non-null object
education_num     32537 non-null int64
marital_status    32537 non-null object
occupation        32537 non-null object
relationship      32537 non-null object
race              32537 non-null object
sex               32537 non-null object
capital_gain      32537 non-null int64
capital.loss      32537 non-null int64
hours_per_week    32537 non-null int64
native_country    32537 non-null object
SalaryGT50K       32537 non-null int64
dtypes: int64(7), object(8)
memory usage: 4.0+ MB
In [9]:
# Looking at the descriptive statistics of the data
SalaryData.describe(include='all')
Out[9]:
age workclass fnlwgt education education_num marital_status occupation relationship race sex capital_gain capital.loss hours_per_week native_country SalaryGT50K
count 32537.000000 32537 3.253700e+04 32537 32537.000000 32537 32537 32537 32537 32537 32537.000000 32537.000000 32537.000000 32537 32537.000000
unique NaN 9 NaN 16 NaN 7 15 6 5 2 NaN NaN NaN 42 NaN
top NaN Private NaN HS-grad NaN Married-civ-spouse Prof-specialty Husband White Male NaN NaN NaN United-States NaN
freq NaN 22673 NaN 10494 NaN 14970 4136 13187 27795 21815 NaN NaN NaN 29153 NaN
mean 38.585887 NaN 1.897808e+05 NaN 10.081815 NaN NaN NaN NaN NaN 1078.443741 87.368227 40.440329 NaN 0.240926
std 13.625962 NaN 1.055565e+05 NaN 2.571633 NaN NaN NaN NaN NaN 7387.957424 403.101833 12.346889 NaN 0.427652
min 17.000000 NaN 1.228500e+04 NaN 1.000000 NaN NaN NaN NaN NaN 0.000000 0.000000 1.000000 NaN 0.000000
25% 28.000000 NaN 1.178270e+05 NaN 9.000000 NaN NaN NaN NaN NaN 0.000000 0.000000 40.000000 NaN 0.000000
50% 37.000000 NaN 1.783560e+05 NaN 10.000000 NaN NaN NaN NaN NaN 0.000000 0.000000 40.000000 NaN 0.000000
75% 48.000000 NaN 2.369930e+05 NaN 12.000000 NaN NaN NaN NaN NaN 0.000000 0.000000 45.000000 NaN 0.000000
max 90.000000 NaN 1.484705e+06 NaN 16.000000 NaN NaN NaN NaN NaN 99999.000000 4356.000000 99.000000 NaN 1.000000
In [10]:
# Finging unique values for each column
# TO understand which column is categorical and which one is Continuous
# Typically if the numer of unique values are < 20 then the variable is likely to be a category otherwise continuous
SalaryData.nunique()
Out[10]:
age                  73
workclass             9
fnlwgt            21648
education            16
education_num        16
marital_status        7
occupation           15
relationship          6
race                  5
sex                   2
capital_gain        119
capital.loss         92
hours_per_week       94
native_country       42
SalaryGT50K           2
dtype: int64

Basic Data Exploration Results

Based on the basic exploration above, you can now create a simple report of the data, noting down your observations regaring each column. Hence, creating a initial roadmap for further analysis.

The selected columns in this step are not final, further study will be done and then a final list will be created

  • age: Continuous. Selected.
  • workclass: Categorical. Selected.
  • fnlwgt: Continuous. Selected.
  • education: Categorical. Selected.
  • education_num: Categorical. Selected.
  • marital_status: Categorical. Selected.
  • occupation: Categorical. Selected.
  • relationship: Categorical. Selected.
  • race: Categorical. Selected.
  • sex: Categorical. Selected.
  • capital_gain: Continuous. Selected.
  • capital.loss: Continuous. Selected.
  • hours_per_week: Continuous. Selected.
  • native_country: Categorical. Selected.
  • SalaryGT50K: Categorical. Selected. This is the Target Variable!
In [ ]:
 

Visual Exploratory Data Analysis

  • Categorical variables: Bar plot
  • Continuous variables: Histogram

Visualize distribution of all the Categorical Predictor variables in the data using bar plots

We can spot a categorical variable in the data by looking at the unique values in them. Typically a categorical variable contains less than 20 Unique values AND there is repetition of values, which means the data can be grouped by those unique values.

Based on the Basic Data Exploration above, we have spotted eight categorical predictors in the data

Categorical Predictors: 'relationship', 'race', 'sex', 'native_country', workclass', 'education', 'marital_status',and 'occupation'

We use bar charts to see how the data is distributed for these categorical columns.

In [11]:
# Plotting multiple bar charts at once for categorical variables
# Since there is no default function which can plot bar charts for multiple columns at once
# we are defining our own function for the same

def PlotBarCharts(inpData, colsToPlot):
    %matplotlib inline
    
    import matplotlib.pyplot as plt
    
    # Generating multiple subplots
    fig, subPlot=plt.subplots(nrows=1, ncols=len(colsToPlot), figsize=(40,6))
    fig.suptitle('Bar charts of: '+ str(colsToPlot))

    for colName, plotNumber in zip(colsToPlot, range(len(colsToPlot))):
        inpData.groupby(colName).size().plot(kind='bar',ax=subPlot[plotNumber])
In [12]:
#####################################################################
# Calling the function
PlotBarCharts(inpData=SalaryData, colsToPlot=['workclass', 'education', 'marital_status','occupation'])
In [13]:
#####################################################################
# Calling the function
PlotBarCharts(inpData=SalaryData, colsToPlot=['relationship', 'race', 'sex', 'native_country'])

Bar Charts Interpretation

These bar charts represent the frequencies of each category in the Y-axis and the category names in the X-axis.

The ideal bar chart looks like the chart of "occupation" column. Where each category has comparable frequency. Hence, there are enough rows for each category in the data for the ML algorithm to learn.

If there is a column which shows too skewed distribution like "native_country" where there is only one dominant bar and the other categories are present in very low numbers. These kind of columns may not be very helpful in machine learning. We confirm this in the correlation analysis section and take a final call to select or reject the column.

In this data, all the categorical columns except "native_country" have satisfactory distribution to be considered for machine learning.

Selected Categorical Variables: All the categorical variables are selected except "native_country".

'workclass', 'education', 'marital_status','occupation', 'relationship', 'race', 'sex'

Visualize distribution of all the Continuous Predictor variables in the data using histograms

Based on the Basic Data Exploration, There are five continuous predictor variables 'age', 'fnlwgt','capital_gain','capital.loss', and 'hours_per_week'

In [14]:
# Plotting histograms of multiple columns together
# Observe that ApplicantIncome and CoapplicantIncome has outliers
SalaryData.hist(['age', 'fnlwgt','capital_gain','capital.loss','hours_per_week'], figsize=(18,10))
Out[14]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x1220b50d0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1220dbf90>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x122255810>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x122287f90>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x1222c9850>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x122308bd0>]],
      dtype=object)

Histogram Interpretation

Histograms shows us the data distribution for a single continuous variable.

The X-axis shows the range of values and Y-axis represent the number of values in that range. For example, in the above histogram of "age", there are around 6200 rows in data that has a age between 40 to 45.

The ideal outcome for histogram is a bell curve or slightly skewed bell curve. If there is too much skewness, then outlier treatment should be done and the column should be re-examined, if that also does not solve the problem then only reject the column.

Selected Continuous Variables:

  • age : Selected.
  • fnlwgt: Selected. Outliers seen beyond 600000, need to treat them.
  • capital_gain: Selected. Outliers seen beyond 40000, need to treat them.
  • capital.loss: Selected. Outliers seen beyond 1000, need to treat them.
  • hours_per_week: Selected. Distribution looks good.
In [ ]:
 

Outlier treatment

Outliers are extreme values in the data which are far away from most of the values. You can see them as the tails in the histogram.

Outlier must be treated one column at a time. As the treatment will be slightly different for each column.

Why I should treat the outliers?

Outliers bias the training of machine learning models. As the algorithm tries to fit the extreme value, it goes away from majority of the data.

There are below two options to treat outliers in the data.

  • Option-1: Delete the outlier Records. Only if there are just few rows lost.
  • Option-2: Impute the outlier values with a logical business value

Below we are finding out the most logical value to be replaced in place of outliers by looking at the histogram.

Replacing outliers for 'fnlwgt'

In [15]:
# Finding nearest values to 600000 mark
SalaryData['fnlwgt'][SalaryData['fnlwgt']>599000].sort_values()
Out[15]:
23600     599629
22570     602513
28641     604045
29347     604380
6852      604506
          ...   
8258     1226583
15569    1268339
16739    1366120
18138    1455435
14449    1484705
Name: fnlwgt, Length: 143, dtype: int64

Above result shows the nearest logical value is 599629, hence, replacing any value above 600000 with it.

In [16]:
# Replacing outliers with nearest possibe value
SalaryData['fnlwgt'][SalaryData['fnlwgt']>600000] = 599629

Replacing outliers for 'capital_gain'

In [17]:
# Finding nearest values to 40000 mark
SalaryData['capital_gain'][SalaryData['capital_gain']>40000].sort_values()
Out[17]:
6433     41310
20176    41310
20987    99999
21188    99999
21489    99999
         ...  
12062    99999
12093    99999
12141    99999
32238    99999
32518    99999
Name: capital_gain, Length: 161, dtype: int64

Above result shows the nearest logical value is 41310, hence, replacing any value above 40000 with it.

In [18]:
# Replacing outliers with nearest possibe value
SalaryData['capital_gain'][SalaryData['capital_gain']>40000] = 41310

Replacing outliers for 'capital.loss'

In [19]:
# Finding nearest values to 1000 mark
SalaryData['capital.loss'][SalaryData['capital.loss']<1000].sort_values(ascending=False)
Out[19]:
7032     974
11043    974
15585    880
11442    880
15610    880
        ... 
21711      0
21712      0
21713      0
21714      0
0          0
Name: capital.loss, Length: 31054, dtype: int64

The nearest value is 974, hence updating all outliers beyond 1000 with 974

In [20]:
# Replacing outliers with nearest possibe value
SalaryData['capital.loss'][SalaryData['capital.loss']>1000] = 974
In [ ]:
 

Visualizing distribution after outlier treatment

The distribution has improved after the outlier treatment. There is still a tail but it is thick, that means there are many values in that range, hence, it is acceptable.

In [21]:
SalaryData.hist(['fnlwgt','capital_gain','capital.loss'], figsize=(18,5))
Out[21]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x122452d90>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1225c3d50>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x1225fb550>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x122722d50>]],
      dtype=object)
In [ ]:
 

Missing values treatment

Missing values are treated for each column separately.

If a column has more than 30% data missing, then missing value treatment cannot be done. That column must be rejected because too much information is missing.

There are below options for treating missing values in data.

  • Delete the missing value rows if there are only few records
  • Impute the missing values with MEDIAN value for continuous variables
  • Impute the missing values with MODE value for categorical variables
  • Interpolate the values based on nearby values
  • Interpolate the values based on business logic
In [22]:
# Finding how many missing values are there for each column
SalaryData.isnull().sum()
Out[22]:
age               0
workclass         0
fnlwgt            0
education         0
education_num     0
marital_status    0
occupation        0
relationship      0
race              0
sex               0
capital_gain      0
capital.loss      0
hours_per_week    0
native_country    0
SalaryGT50K       0
dtype: int64

There are no missing values in the data!

In [ ]:
 

Feature Selection

Now its time to finally choose the best columns(Features) which are correlated to the Target variable. This can be done directly by measuring the correlation values or ANOVA/Chi-Square tests. However, it is always helpful to visualize the relation between the Target variable and each of the predictors to get a better sense of data.

I have listed below the techniques used for visualizing relationship between two variables as well as measuring the strength statistically.

Visual exploration of relationship between variables

  • Continuous Vs Continuous ---- Scatter Plot
  • Categorical Vs Continuous---- Box Plot
  • Categorical Vs Categorical---- Grouped Bar Plots

Statistical measurement of relationship strength between variables

  • Continuous Vs Continuous ---- Correlation matrix
  • Categorical Vs Continuous---- ANOVA test
  • Categorical Vs Categorical--- Chi-Square test

In this case study the Target variable is categorical, hence below two scenarios will be present

  • Categorical Target Variable Vs Continuous Predictor
  • Categorical Target Variable Vs Categorical Predictor
In [ ]:
 

Relationship exploration: Categorical Vs Continuous -- Box Plots

When the target variable is Categorical and the predictor variable is Continuous we analyze the relation using bar plots/Boxplots and measure the strength of relation using Anova test

In [23]:
# Box plots for Categorical Target Variable "SalaryGT50K" and continuous predictors
ContinuousColsList=['age','hours_per_week','fnlwgt','capital_gain','capital.loss']

import matplotlib.pyplot as plt
fig, PlotCanvas=plt.subplots(nrows=1, ncols=len(ContinuousColsList), figsize=(18,5))

# Creating box plots for each continuous predictor against the Target Variable "SalaryGT50K"
for PredictorCol , i in zip(ContinuousColsList, range(len(ContinuousColsList))):
    SalaryData.boxplot(column=PredictorCol, by='SalaryGT50K', figsize=(5,5), vert=True, ax=PlotCanvas[i])

Box-Plots interpretation

What should you look for in these box plots?

These plots gives an idea about the data distribution of continuous predictor in the Y-axis for each of the category in the X-Axis.

If the distribution looks similar for each category(Boxes are in the same line), that means the the continuous variable has NO effect on the target variable. Hence, the variables are not correlated to each other.

For example, look at the first chart "fnlwgt" Vs "SalaryGT50K". The boxes are in the same line! It means that people who have income greater than 50K have no dependency on the final weight given to the population in their area. Hence, I cannot distinguish between approval and rejection based on the fnlwht. So this column is NOT correlated with the SalaryGT50K.

The other three charts exhibit opposite characteristics. Means the the data distribution is different(the boxes are not in same line!) for each category of salary. It hints that these variables might be correlated with SalaryGT50K.

We confirm this by looking at the results of ANOVA test below

In [ ]:
 

Statistical Feature Selection (Categorical Vs Continuous) using ANOVA test

Analysis of variance(ANOVA) is performed to check if there is any relationship between the given continuous and categorical variable

  • Assumption(H0): There is NO relation between the given variables (i.e. The average(mean) values of the numeric Predictor variable is same for all the groups in the categorical Target variable)
  • ANOVA Test result: Probability of H0 being true
In [24]:
# Defining a function to find the statistical relationship with all the categorical variables
def FunctionAnova(inpData, TargetVariable, ContinuousPredictorList):
    from scipy.stats import f_oneway

    # Creating an empty list of final selected predictors
    SelectedPredictors=[]
    
    print('##### ANOVA Results ##### \n')
    for predictor in ContinuousPredictorList:
        CategoryGroupLists=inpData.groupby(TargetVariable)[predictor].apply(list)
        AnovaResults = f_oneway(*CategoryGroupLists)
        
        # If the ANOVA P-Value is <0.05, that means we reject H0
        if (AnovaResults[1] < 0.05):
            print(predictor, 'is correlated with', TargetVariable, '| P-Value:', AnovaResults[1])
            SelectedPredictors.append(predictor)
        else:
            print(predictor, 'is NOT correlated with', TargetVariable, '| P-Value:', AnovaResults[1])
    
    return(SelectedPredictors)
In [25]:
# Calling the function to check which categorical variables are correlated with target
ContinuousVariables=['age','hours_per_week','fnlwgt','capital_gain','capital.loss']
FunctionAnova(inpData=SalaryData, TargetVariable='SalaryGT50K', ContinuousPredictorList=ContinuousVariables)
##### ANOVA Results ##### 

age is correlated with SalaryGT50K | P-Value: 0.0
hours_per_week is correlated with SalaryGT50K | P-Value: 0.0
fnlwgt is NOT correlated with SalaryGT50K | P-Value: 0.10034099994119691
capital_gain is correlated with SalaryGT50K | P-Value: 0.0
capital.loss is correlated with SalaryGT50K | P-Value: 4.266838502495211e-143
Out[25]:
['age', 'hours_per_week', 'capital_gain', 'capital.loss']

The results of ANOVA confirm our visual analysis using box plots above.

Final selected Continuous columns:

'age', 'hours_per_week', 'capital_gain', 'capital.loss'

In [ ]:
 

Relationship exploration: Categorical Vs Categorical -- Grouped Bar Charts

When the target variable is Categorical and the predictor is also Categorical then we explore the correlation between them visually using barplots and statistically using Chi-square test

In [26]:
# Cross tablulation between two categorical variables
CrossTabResult=pd.crosstab(index=SalaryData['marital_status'], columns=SalaryData['SalaryGT50K'])
CrossTabResult
Out[26]:
SalaryGT50K 0 1
marital_status
Divorced 3978 463
Married-AF-spouse 13 10
Married-civ-spouse 8280 6690
Married-spouse-absent 384 34
Never-married 10176 491
Separated 959 66
Widowed 908 85
In [27]:
# Visual Inference using Grouped Bar charts
CategoricalColsList=['workclass', 'education', 'marital_status','occupation',
                    'relationship', 'race', 'sex']

import matplotlib.pyplot as plt
fig, PlotCanvas=plt.subplots(nrows=len(CategoricalColsList), ncols=1, figsize=(10,70))

# Creating Grouped bar plots for each categorical predictor against the Target Variable "SalaryGT50K"
for CategoricalCol , i in zip(CategoricalColsList, range(len(CategoricalColsList))):
    CrossTabResult=pd.crosstab(index=SalaryData[CategoricalCol], columns=SalaryData['SalaryGT50K'])
    CrossTabResult.plot.bar(color=['lightblue','green'], ax=PlotCanvas[i], title=CategoricalCol+' Vs '+'SalaryGT50K')

Grouped Bar charts Interpretation

What to look for in these grouped bar charts?

These grouped bar charts show the frequency in the Y-Axis and the category in the X-Axis. If the ratio of bars is similar across all categories, then the two columns are not correlated.

On the other hand, look at the marital_status vs SalaryGT50K plot. The bars are different for each category, Hence, two columns are correlated with each other.

We confirm this analysis in below section by using Chi-Square Tests.

In [ ]:
 

Statistical Feature Selection (Categorical Vs Categorical) using Chi-Square Test

Chi-Square test is conducted to check the correlation between two categorical variables

In [28]:
# Writing a function to find the correlation of all categorical variables with the Target variable
def FunctionChisq(inpData, TargetVariable, CategoricalVariablesList):
    from scipy.stats import chi2_contingency
    
    # Creating an empty list of final selected predictors
    SelectedPredictors=[]

    for predictor in CategoricalVariablesList:
        CrossTabResult=pd.crosstab(index=inpData[TargetVariable], columns=inpData[predictor])
        ChiSqResult = chi2_contingency(CrossTabResult)
        
        # If the ChiSq P-Value is <0.05, that means we reject H0
        if (ChiSqResult[1] < 0.05):
            print(predictor, 'is correlated with', TargetVariable, '| P-Value:', ChiSqResult[1])
            SelectedPredictors.append(predictor)
        else:
            print(predictor, 'is NOT correlated with', TargetVariable, '| P-Value:', ChiSqResult[1])        
            
    return(SelectedPredictors)
In [29]:
CategoricalVariables=['workclass', 'education', 'marital_status','occupation',
                    'relationship', 'race', 'sex']

# Calling the function
FunctionChisq(inpData=SalaryData, 
              TargetVariable='SalaryGT50K',
              CategoricalVariablesList= CategoricalVariables)
workclass is correlated with SalaryGT50K | P-Value: 3.352256069028484e-220
education is correlated with SalaryGT50K | P-Value: 0.0
marital_status is correlated with SalaryGT50K | P-Value: 0.0
occupation is correlated with SalaryGT50K | P-Value: 0.0
relationship is correlated with SalaryGT50K | P-Value: 0.0
race is correlated with SalaryGT50K | P-Value: 2.2797874171824478e-70
sex is correlated with SalaryGT50K | P-Value: 0.0
Out[29]:
['workclass',
 'education',
 'marital_status',
 'occupation',
 'relationship',
 'race',
 'sex']

Finally selected Categorical variables:

'workclass', 'education', 'marital_status', 'occupation', 'relationship', 'race', 'sex'

In [ ]:
 

Selecting final predictors for Machine Learning

Based on the above tests, selecting the final columns for machine learning

Instead of original "education" column, I am selecting the "education_num". Which represents the ordinal property of the data.

In [30]:
SelectedColumns=['workclass', 'education_num', 'marital_status', 'occupation', 
                 'relationship', 'race', 'sex','age', 'hours_per_week',
                 'capital_gain', 'capital.loss']

# Selecting final columns
DataForML=SalaryData[SelectedColumns]
DataForML.head()
Out[30]:
workclass education_num marital_status occupation relationship race sex age hours_per_week capital_gain capital.loss
0 State-gov 13 Never-married Adm-clerical Not-in-family White Male 39 40 2174 0
1 Self-emp-not-inc 13 Married-civ-spouse Exec-managerial Husband White Male 50 13 0 0
2 Private 9 Divorced Handlers-cleaners Not-in-family White Male 38 40 0 0
3 Private 7 Married-civ-spouse Handlers-cleaners Husband Black Male 53 40 0 0
4 Private 13 Married-civ-spouse Prof-specialty Wife Black Female 28 40 0 0
In [31]:
# Saving this final data for reference during deployment
DataForML.to_pickle('DataForML.pkl')

Data Pre-processing for Machine Learning

List of steps performed on predictor variables before data can be used for machine learning

  1. Converting each Ordinal Categorical columns to numeric
  2. Converting Binary nominal Categorical columns to numeric using 1/0 mapping
  3. Converting all other nominal categorical columns to numeric using pd.get_dummies()
  4. Data Transformation (Optional): Standardization/Normalization/log/sqrt. Important if you are using distance based algorithms like KNN, or Neural Networks

In this data there is no Ordinal categorical variable.

Converting the binary nominal variable to numeric using 1/0 mapping

In [32]:
DataForML['sex'].unique()
Out[32]:
array([' Male', ' Female'], dtype=object)
In [33]:
# Converting the binary nominal variable sex to numeric
# Notice the space in the values!! The data was like that
DataForML['sex'].replace({' Female':0, ' Male':1}, inplace=True)

Converting the nominal variable to numeric using get_dummies()

In [34]:
# Treating all the nominal variables at once using dummy variables
DataForML_Numeric=pd.get_dummies(DataForML)

# Adding Target Variable to the data
DataForML_Numeric['SalaryGT50K']=SalaryData['SalaryGT50K']

# Printing sample rows
DataForML_Numeric.head()
Out[34]:
education_num sex age hours_per_week capital_gain capital.loss workclass_ ? workclass_ Federal-gov workclass_ Local-gov workclass_ Never-worked ... relationship_ Other-relative relationship_ Own-child relationship_ Unmarried relationship_ Wife race_ Amer-Indian-Eskimo race_ Asian-Pac-Islander race_ Black race_ Other race_ White SalaryGT50K
0 13 1 39 40 2174 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 1 0
1 13 1 50 13 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 1 0
2 9 1 38 40 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 1 0
3 7 1 53 40 0 0 0 0 0 0 ... 0 0 0 0 0 0 1 0 0 0
4 13 0 28 40 0 0 0 0 0 0 ... 0 0 0 1 0 0 1 0 0 0

5 rows × 49 columns

In [ ]:
 

Machine Learning: Splitting the data into Training and Testing sample

We dont use the full data for creating the model. Some data is randomly selected and kept aside for checking how good the model is. This is known as Testing Data and the remaining data is called Training data on which the model is built. Typically 70% of data is used as Training data and the rest 30% is used as Tesing data.

In [35]:
# Printing all the column names for our reference
DataForML_Numeric.columns
Out[35]:
Index(['education_num', 'sex', 'age', 'hours_per_week', 'capital_gain',
       'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
       'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
       'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
       'workclass_ State-gov', 'workclass_ Without-pay',
       'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
       'marital_status_ Married-civ-spouse',
       'marital_status_ Married-spouse-absent',
       'marital_status_ Never-married', 'marital_status_ Separated',
       'marital_status_ Widowed', 'occupation_ ?', 'occupation_ Adm-clerical',
       'occupation_ Armed-Forces', 'occupation_ Craft-repair',
       'occupation_ Exec-managerial', 'occupation_ Farming-fishing',
       'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct',
       'occupation_ Other-service', 'occupation_ Priv-house-serv',
       'occupation_ Prof-specialty', 'occupation_ Protective-serv',
       'occupation_ Sales', 'occupation_ Tech-support',
       'occupation_ Transport-moving', 'relationship_ Husband',
       'relationship_ Not-in-family', 'relationship_ Other-relative',
       'relationship_ Own-child', 'relationship_ Unmarried',
       'relationship_ Wife', 'race_ Amer-Indian-Eskimo',
       'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White',
       'SalaryGT50K'],
      dtype='object')
In [36]:
# Separate Target Variable and Predictor Variables
TargetVariable='SalaryGT50K'
Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
       'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
       'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
       'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
       'workclass_ State-gov', 'workclass_ Without-pay',
       'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
       'marital_status_ Married-civ-spouse',
       'marital_status_ Married-spouse-absent',
       'marital_status_ Never-married', 'marital_status_ Separated',
       'marital_status_ Widowed', 'occupation_ ?', 'occupation_ Adm-clerical',
       'occupation_ Armed-Forces', 'occupation_ Craft-repair',
       'occupation_ Exec-managerial', 'occupation_ Farming-fishing',
       'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct',
       'occupation_ Other-service', 'occupation_ Priv-house-serv',
       'occupation_ Prof-specialty', 'occupation_ Protective-serv',
       'occupation_ Sales', 'occupation_ Tech-support',
       'occupation_ Transport-moving', 'relationship_ Husband',
       'relationship_ Not-in-family', 'relationship_ Other-relative',
       'relationship_ Own-child', 'relationship_ Unmarried',
       'relationship_ Wife', 'race_ Amer-Indian-Eskimo',
       'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White',
       'sex']

X=DataForML_Numeric[Predictors].values
y=DataForML_Numeric[TargetVariable].values

# Split the data into training and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=428)
In [ ]:
 

Standardization/Normalization of data

You can choose not to run this step if you want to compare the resultant accuracy of this transformation with the accuracy of raw data.

However, if you are using KNN or Neural Networks, then this step becomes necessary.

In [37]:
### Sandardization of data ###
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Choose either standardization or Normalization
# On this data Min Max Normalization produced better results

# Choose between standardization and MinMAx normalization
#PredictorScaler=StandardScaler()
PredictorScaler=MinMaxScaler()

# Storing the fit object for later reference
PredictorScalerFit=PredictorScaler.fit(X)

# Generating the standardized values of X
X=PredictorScalerFit.transform(X)

# Split the data into training and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
In [38]:
# Sanity check for the sampled data
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(22775, 48)
(22775,)
(9762, 48)
(9762,)
In [ ]:
 

Logistic Regression

In [39]:
# Logistic Regression
from sklearn.linear_model import LogisticRegression
# choose parameter Penalty='l1' or C=1
# choose different values for solver 'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'
clf = LogisticRegression(C=1,penalty='l2', solver='newton-cg')

# Printing all the parameters of logistic regression
# print(clf)

# Creating the model on Training Data
LOG=clf.fit(X_train,y_train)
prediction=LOG.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(LOG, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
              precision    recall  f1-score   support

           0       0.88      0.93      0.90      7405
           1       0.73      0.61      0.66      2357

    accuracy                           0.85      9762
   macro avg       0.81      0.77      0.78      9762
weighted avg       0.84      0.85      0.85      9762

[[6871  534]
 [ 923 1434]]
Accuracy of the model on Testing Sample Data: 0.85

Accuracy values for 10-fold Cross Validation:
 [0.84064533 0.84349705 0.84786099 0.83629089 0.85168839 0.84589346
 0.84651952 0.85154112 0.84917656 0.84406447]

Final Average Accuracy of the model: 0.85
In [ ]:
 

Decision Trees

In [40]:
#Decision Trees
from sklearn import tree
#choose from different tunable hyper parameters
clf = tree.DecisionTreeClassifier(max_depth=6,criterion='entropy')

# Printing all the parameters of Decision Trees
print(clf)

# Creating the model on Training Data
DTree=clf.fit(X_train,y_train)
prediction=DTree.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(DTree.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(DTree, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=6,
                       max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=1, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort=False,
                       random_state=None, splitter='best')
              precision    recall  f1-score   support

           0       0.86      0.96      0.91      7405
           1       0.79      0.51      0.62      2357

    accuracy                           0.85      9762
   macro avg       0.83      0.73      0.76      9762
weighted avg       0.84      0.85      0.84      9762

[[7085  320]
 [1151 1206]]
Accuracy of the model on Testing Sample Data: 0.84

Accuracy values for 10-fold Cross Validation:
 [0.82584983 0.8314983  0.84011881 0.82063983 0.83438495 0.83595917
 0.83390393 0.84296047 0.84346451 0.83012104]

Final Average Accuracy of the model: 0.83

Plotting a Decision Tree

In [41]:
# Installing the required library for plotting the decision tree
#!pip install dtreeplt
In [43]:
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf, feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
currentFigure=plt.gcf()
currentFigure.set_size_inches(100,20)
# Double click on the graph to zoom in

image.png

In [ ]:
 

Random Forest

In [100]:
# Random Forest (Bagging of multiple Decision Trees)
from sklearn.ensemble import RandomForestClassifier
# Choose different hyperparameter values of max_depth, n_estimators and criterion to tune the model
clf = RandomForestClassifier(max_depth=5, n_estimators=100,criterion='gini')

# Printing all the parameters of Random Forest
print(clf)

# Creating the model on Training Data
RF=clf.fit(X_train,y_train)
prediction=RF.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(RF, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))


# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(RF.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
                       max_depth=5, max_features='auto', max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=1, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, n_estimators=100,
                       n_jobs=None, oob_score=False, random_state=None,
                       verbose=0, warm_start=False)
              precision    recall  f1-score   support

           0       0.85      0.97      0.90      7405
           1       0.82      0.46      0.59      2357

    accuracy                           0.84      9762
   macro avg       0.83      0.71      0.74      9762
weighted avg       0.84      0.84      0.83      9762

[[7163  242]
 [1282 1075]]
Accuracy of the model on Testing Sample Data: 0.83

Accuracy values for 10-fold Cross Validation:
 [0.81668896 0.82683828 0.82808993 0.82172756 0.82476449 0.82971026
 0.81800756 0.83416117 0.82984257 0.81649819]

Final Average Accuracy of the model: 0.82
Out[100]:
<matplotlib.axes._subplots.AxesSubplot at 0x129aaad10>
In [ ]:
 

Plotting one of the Decision Trees in Random Forest

In [1]:
# PLotting a single Decision Tree from Random Forest
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf.estimators_[4], feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
currentFigure=plt.gcf()
currentFigure.set_size_inches(100,20)
# Double click on the graph to zoom in

image.png

AdaBoost

In [102]:
# Adaboost 
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier

# Choosing Decision Tree with 1 level as the weak learner
DTC=DecisionTreeClassifier(max_depth=1)
clf = AdaBoostClassifier(n_estimators=100, base_estimator=DTC ,learning_rate=0.1)

# Printing all the parameters of Adaboost
print(clf)

# Creating the model on Training Data
AB=clf.fit(X_train,y_train)
prediction=AB.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(AB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))

# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(AB.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
AdaBoostClassifier(algorithm='SAMME.R',
                   base_estimator=DecisionTreeClassifier(class_weight=None,
                                                         criterion='gini',
                                                         max_depth=1,
                                                         max_features=None,
                                                         max_leaf_nodes=None,
                                                         min_impurity_decrease=0.0,
                                                         min_impurity_split=None,
                                                         min_samples_leaf=1,
                                                         min_samples_split=2,
                                                         min_weight_fraction_leaf=0.0,
                                                         presort=False,
                                                         random_state=None,
                                                         splitter='best'),
                   learning_rate=0.1, n_estimators=100, random_state=None)
              precision    recall  f1-score   support

           0       0.87      0.96      0.91      7405
           1       0.80      0.54      0.64      2357

    accuracy                           0.86      9762
   macro avg       0.83      0.75      0.78      9762
weighted avg       0.85      0.86      0.84      9762

[[7090  315]
 [1095 1262]]
Accuracy of the model on Testing Sample Data: 0.84

Accuracy values for 10-fold Cross Validation:
 [0.83153652 0.83642676 0.84323762 0.82877025 0.84057499 0.84124016
 0.83540702 0.84637703 0.84583968 0.83814889]

Final Average Accuracy of the model: 0.84
Out[102]:
<matplotlib.axes._subplots.AxesSubplot at 0x12a316e90>

Plotting one of the Decision trees from Adaboost

In [103]:
# PLotting 5th single Decision Tree from Adaboost
from dtreeplt import dtreeplt
dtree = dtreeplt(model=clf.estimators_[5], feature_names=Predictors, target_names=TargetVariable)
fig = dtree.view()
In [ ]:
 

XGBoost

In [104]:
# Xtreme Gradient Boosting (XGBoost)
from xgboost import XGBClassifier
clf=XGBClassifier(max_depth=2, learning_rate=0.1, n_estimators=200, objective='binary:logistic', booster='gbtree')

# Printing all the parameters of XGBoost
print(clf)

# Creating the model on Training Data
XGB=clf.fit(X_train,y_train)
prediction=XGB.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(XGB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))

# Plotting the feature importance for Top 10 most important columns
%matplotlib inline
feature_importances = pd.Series(XGB.feature_importances_, index=Predictors)
feature_importances.nlargest(10).plot(kind='barh')
XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,
              colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0,
              max_depth=2, min_child_weight=1, missing=None, n_estimators=200,
              n_jobs=1, nthread=None, objective='binary:logistic',
              random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1,
              seed=None, silent=True, subsample=1)
              precision    recall  f1-score   support

           0       0.88      0.94      0.91      7405
           1       0.77      0.61      0.68      2357

    accuracy                           0.86      9762
   macro avg       0.83      0.78      0.80      9762
weighted avg       0.86      0.86      0.86      9762

[[6988  417]
 [ 925 1432]]
Accuracy of the model on Testing Sample Data: 0.86

Accuracy values for 10-fold Cross Validation:
 [0.84917056 0.85197294 0.85474826 0.84827773 0.85596388 0.8563503
 0.85058864 0.86133939 0.86005103 0.85546711]

Final Average Accuracy of the model: 0.85
Out[104]:
<matplotlib.axes._subplots.AxesSubplot at 0x12d1f2590>

Plotting a single Decision tree out of XGBoost

In [105]:
from xgboost import plot_tree
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(20, 8))
plot_tree(XGB, num_trees=10, ax=ax)
Out[105]:
<matplotlib.axes._subplots.AxesSubplot at 0x129c3aad0>
In [ ]:
 

KNN

In [106]:
# K-Nearest Neighbor(KNN)
from sklearn.neighbors import KNeighborsClassifier
clf = KNeighborsClassifier(n_neighbors=3)

# Printing all the parameters of KNN
print(clf)

# Creating the model on Training Data
KNN=clf.fit(X_train,y_train)
prediction=KNN.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(KNN, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))


# Plotting the feature importance for Top 10 most important columns
# There is no built-in method to get feature importance in KNN
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
                     metric_params=None, n_jobs=None, n_neighbors=3, p=2,
                     weights='uniform')
              precision    recall  f1-score   support

           0       0.87      0.90      0.88      7405
           1       0.64      0.57      0.61      2357

    accuracy                           0.82      9762
   macro avg       0.76      0.74      0.75      9762
weighted avg       0.81      0.82      0.82      9762

[[6651  754]
 [1002 1355]]
Accuracy of the model on Testing Sample Data: 0.82

Accuracy values for 10-fold Cross Validation:
 [0.81229539 0.81481537 0.82429376 0.8102334  0.8288768  0.81883763
 0.82168564 0.82712976 0.83033305 0.81337187]

Final Average Accuracy of the model: 0.82
In [ ]:
 

SVM

In [107]:
# Support Vector Machines(SVM)
from sklearn import svm
clf = svm.SVC(C=3, kernel='rbf', gamma=0.1)

# Printing all the parameters of KNN
print(clf)

# Creating the model on Training Data
SVM=clf.fit(X_train,y_train)
prediction=SVM.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(SVM, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))

# Plotting the feature importance for Top 10 most important columns
# The built in attribute SVM.coef_ works only for linear kernel

%matplotlib inline
#feature_importances = pd.Series(SVM.coef_[0], index=Predictors)
#feature_importances.nlargest(10).plot(kind='barh')
SVC(C=3, cache_size=200, class_weight=None, coef0=0.0,
    decision_function_shape='ovr', degree=3, gamma=0.1, kernel='rbf',
    max_iter=-1, probability=False, random_state=None, shrinking=True,
    tol=0.001, verbose=False)
              precision    recall  f1-score   support

           0       0.88      0.93      0.90      7405
           1       0.72      0.61      0.66      2357

    accuracy                           0.85      9762
   macro avg       0.80      0.77      0.78      9762
weighted avg       0.84      0.85      0.84      9762

[[6852  553]
 [ 920 1437]]
Accuracy of the model on Testing Sample Data: 0.84

Accuracy values for 10-fold Cross Validation:
 [0.84529566 0.85196537 0.84075375 0.83956587 0.8496435  0.84001824
 0.84432395 0.8470493  0.84828994 0.84380073]

Final Average Accuracy of the model: 0.85
In [ ]:
 

Naive Bayes

In [108]:
# Naive Bays
from sklearn.naive_bayes import GaussianNB, MultinomialNB

# GaussianNB is used in Binomial Classification
# MultinomialNB is used in multi-class classification
clf = GaussianNB()
#clf = MultinomialNB()

# Printing all the parameters of Naive Bayes
print(clf)

NB=clf.fit(X_train,y_train)
prediction=NB.predict(X_test)

# Measuring accuracy on Testing Data
from sklearn import metrics
print(metrics.classification_report(y_test, prediction))
print(metrics.confusion_matrix(y_test, prediction))

# Printing the Overall Accuracy of the model
F1_Score=metrics.f1_score(y_test, prediction, average='weighted')
print('Accuracy of the model on Testing Sample Data:', round(F1_Score,2))

# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(NB, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
GaussianNB(priors=None, var_smoothing=1e-09)
              precision    recall  f1-score   support

           0       0.96      0.51      0.67      7405
           1       0.38      0.94      0.54      2357

    accuracy                           0.62      9762
   macro avg       0.67      0.73      0.61      9762
weighted avg       0.82      0.62      0.64      9762

[[3805 3600]
 [ 144 2213]]
Accuracy of the model on Testing Sample Data: 0.64

Accuracy values for 10-fold Cross Validation:
 [0.64342311 0.64260659 0.63757507 0.64130457 0.6294625  0.64808544
 0.64587054 0.60843301 0.61180025 0.63465454]

Final Average Accuracy of the model: 0.63
In [ ]:
 

Deployment of the Model

Based on the above trials you select that algorithm which produces the best average accuracy. In this case, multiple algorithms have produced similar kind of average accuracy. Hence, we can choose any one of them.

I am choosing Logistic Regression as the final model since it is very fast for this data!

In order to deploy the model we follow below steps

  1. Train the model using 100% data available
  2. Save the model as a serialized file which can be stored anywhere
  3. Create a python function which gets integrated with front-end(Tableau/Java Website etc.) to take all the inputs and returns the prediction

Choosing only the most important variables

Its beneficial to keep lesser number of predictors for the model while deploying it in production. The lesser predictors you keep, the better because, the model will be less dependent hence, more stable.

This is important specially when the data is high dimensional(too many predictor columns).

In this data, the most important predictor variables are 'age', 'education_num', 'hours_per_week','capital_gain', 'capital.loss', 'workclass', and 'marital_status'. As these are consistently on top of the variable importance chart for every algorithm. Hence choosing these as final set of predictor variables.

In [109]:
# Separate Target Variable and Predictor Variables
TargetVariable='SalaryGT50K'

# Selecting the final set of predictors for the deployment
# Based on the variable importance charts of multiple algorithms above
Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
       'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
       'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
       'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
       'workclass_ State-gov', 'workclass_ Without-pay',
       'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
       'marital_status_ Married-civ-spouse',
       'marital_status_ Married-spouse-absent',
       'marital_status_ Never-married', 'marital_status_ Separated',
       'marital_status_ Widowed']

X=DataForML_Numeric[Predictors].values
y=DataForML_Numeric[TargetVariable].values

### Sandardization of data ###
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Choose either standardization or Normalization
# On this data Min Max Normalization produced better results

# Choose between standardization and MinMAx normalization
#PredictorScaler=StandardScaler()
PredictorScaler=MinMaxScaler()

# Storing the fit object for later reference
PredictorScalerFit=PredictorScaler.fit(X)

# Generating the standardized values of X
X=PredictorScalerFit.transform(X)

print(X.shape)
print(y.shape)
(32537, 21)
(32537,)
In [ ]:
 

Step 1. Retraining the model using 100% data

In [110]:
# Logistic Regression
from sklearn.linear_model import LogisticRegression
# choose parameter Penalty='l1' or C=1
# choose different values for solver 'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'
# Using the Logistic Regression algorithm with final hyperparamters
clf = LogisticRegression(C=1,penalty='l2', solver='newton-cg')

# Training the model on 100% Data available
FinalLogisticModel=clf.fit(X,y)

Cross validating the final model accuracy with less predictors

In [111]:
# Importing cross validation function from sklearn
from sklearn.model_selection import cross_val_score

# Running 10-Fold Cross validation on a given algorithm
# Passing full data X and y because the K-fold will split the data and automatically choose train/test
Accuracy_Values=cross_val_score(FinalLogisticModel, X , y, cv=10, scoring='f1_weighted')
print('\nAccuracy values for 10-fold Cross Validation:\n',Accuracy_Values)
print('\nFinal Average Accuracy of the model:', round(Accuracy_Values.mean(),2))
Accuracy values for 10-fold Cross Validation:
 [0.83504417 0.82895006 0.84055788 0.82601273 0.83581592 0.84193733
 0.83824319 0.8458835  0.83922368 0.84093693]

Final Average Accuracy of the model: 0.84

Step 2. Save the model as a serialized file which can be stored anywhere

In [112]:
import pickle
import os

# Saving the Python objects as serialized files can be done using pickle library
# Here let us save the Final model
with open('FinalLogisticModel.pkl', 'wb') as fileWriteStream:
    pickle.dump(FinalLogisticModel, fileWriteStream)
    # Don't forget to close the filestream!
    fileWriteStream.close()
    
print('pickle file of Predictive Model is saved at Location:',os.getcwd())
pickle file of Predictive Model is saved at Location: /Users/farukh/Python Case Studies

Step 3. Create a python function

In [113]:
# This Function can be called from any from any front end tool/website
def PredictSalaryBand(InputData):
    import pandas as pd
    Num_Inputs=InputData.shape[0]
    
    # Making sure the input data has same columns as it was used for training the model
    # Also, if standardization/normalization was done, then same must be done for new input
    
    # Appending the new data with the Training data
    DataForML=pd.read_pickle('DataForML.pkl')
    InputData=InputData.append(DataForML)
    
    # Generating dummy variables for rest of the nominal variables
    InputData=pd.get_dummies(InputData)
            
    # Maintaining the same order of columns as it was during the model training
    Predictors=['education_num', 'age', 'hours_per_week', 'capital_gain',
       'capital.loss', 'workclass_ ?', 'workclass_ Federal-gov',
       'workclass_ Local-gov', 'workclass_ Never-worked', 'workclass_ Private',
       'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc',
       'workclass_ State-gov', 'workclass_ Without-pay',
       'marital_status_ Divorced', 'marital_status_ Married-AF-spouse',
       'marital_status_ Married-civ-spouse',
       'marital_status_ Married-spouse-absent',
       'marital_status_ Never-married', 'marital_status_ Separated',
       'marital_status_ Widowed']
    
    # Generating the input values to the model
    X=InputData[Predictors].values[0:Num_Inputs]
    
    # Generating the standardized values of X since it was done while model training also
    X=PredictorScalerFit.transform(X)
    
    # Loading the Function from pickle file
    import pickle
    with open('FinalLogisticModel.pkl', 'rb') as fileReadStream:
        LogisticModel=pickle.load(fileReadStream)
        # Don't forget to close the filestream!
        fileReadStream.close()
            
    # Genrating Predictions
    Prediction=LogisticModel.predict(X)
    PredictedStatus=pd.DataFrame(Prediction, columns=['Predicted Status'])
    return(PredictedStatus)
In [114]:
# Calling the function for some loan applications
NewEmployeeDetails=pd.DataFrame(
data=[[39,13,40,15024,0,'State-gov','Never-married'],
     [39,13,40,2174,0,'Private','Never-married']],
columns=['age', 'education_num', 'hours_per_week','capital_gain', 
         'capital.loss', 'workclass', 'marital_status'])

print(NewEmployeeDetails)

# Calling the Function for prediction
PredictSalaryBand(InputData= NewEmployeeDetails)
   age  education_num  hours_per_week  capital_gain  capital.loss  workclass  \
0   39             13              40         15024             0  State-gov   
1   39             13              40          2174             0    Private   

  marital_status  
0  Never-married  
1  Never-married  
Out[114]:
Predicted Status
0 1
1 0

The Function PredictSalaryBand can be used to produce the predictions for one or more loan applications at a time. Hence, it can be scheduled using a batch job or cron job to run every night and generate predictions for all the loan applications available in the system.

In [ ]:
 

Deploying a predictive model as an API

  • Django and flask are two popular ways to deploy predictive models as a web service
  • You can call your predictive models using a URL from any front end like tableau, java or angular js

Creating the model with few parameters

Function for predictions API

In [115]:
# Creating the function which can take inputs and return predictions
def FunctionSalaryBandPrediction(inp_age, inp_education_num , inp_hours_per_week, inp_capital_gain,
                               inp_capital_loss, inp_workclass, inp_marital_status):
    
    # Creating a data frame for the model input
    SampleInputData=pd.DataFrame(
     data=[[inp_age, inp_education_num , inp_hours_per_week, inp_capital_gain,
           inp_capital_loss, inp_workclass, inp_marital_status]],
     columns=['age', 'education_num', 'hours_per_week','capital_gain', 
         'capital.loss', 'workclass', 'marital_status'])

    # Calling the function defined above using the input parameters
    Predictions=PredictSalaryBand(InputData= SampleInputData)

    # Returning the predictions
    return(Predictions.to_json())

# Function call
FunctionSalaryBandPrediction(inp_age=39,
                             inp_education_num =13,
                             inp_hours_per_week=40,
                             inp_capital_gain=15024,
                             inp_capital_loss=0,
                             inp_workclass='State-gov',
                             inp_marital_status='Never-married',
                             )
Out[115]:
'{"Predicted Status":{"0":1}}'
In [ ]:
 
In [116]:
# Installing the flask library required to create the API
#!pip install flask

Creating Flask API

In [117]:
from flask import Flask, request, jsonify
import pickle
import pandas as pd
import numpy
In [118]:
app = Flask(__name__)

@app.route('/get_salary_band_prediction', methods=["GET"])
def get_salary_band_prediction():
    try:
        # Getting the paramters from API call
        age_value = float(request.args.get('age'))
        education_num_value = float(request.args.get('education_num'))
        hours_per_week_value=float(request.args.get('hours_per_week'))
        capital_gain_value=float(request.args.get('capital_gain'))
        capital_loss_value = float(request.args.get('capital_loss'))
        workclass_value = request.args.get('workclass')
        marital_status_value = request.args.get('marital_status')
                
        # Calling the funtion to get predictions
        prediction_from_api=FunctionSalaryBandPrediction(
                             inp_age=age_value,
                             inp_education_num =education_num_value,
                             inp_hours_per_week=hours_per_week_value,
                             inp_capital_gain=capital_gain_value,
                             inp_capital_loss=capital_loss_value,
                             inp_workclass=workclass_value,
                             inp_marital_status=marital_status_value,
                             )

        return (prediction_from_api)
    
    except Exception as e:
        return('Something is not right!:'+str(e))

Starting the API engine

In [119]:
import os
if __name__ =="__main__":
    
    # Hosting the API in localhost
    app.run(host='127.0.0.1', port=8080, threaded=True, debug=True, use_reloader=False)
    # Interrupt kernel to stop the API
 * Serving Flask app "__main__" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Sep/2020 22:45:06] "GET /get_salary_band_prediction?age=39&education_num=13&hours_per_week=40&capital_gain=15024&capital_loss=0&workclass=%27State-gov%27&marital_status=%27Never-married%27 HTTP/1.1" 200 -

Sample URL to call the API

This URL can be called by any front end application like Java, Tableau etc. Once the parameters are passed to it, the predictions will be generated.