Data Exploration
Data Exploration
Data Exploration
• A complete tutorial on data exploration (EDA)
• We cover several data exploration aspects, including missing value
imputation, outlier removal and the art of feature engineering
There are no shortcuts for data exploration. If you are in a state of mind, that
machine learning can sail you away from every data storm, trust me, it won’t.
After some point of time, you’ll realize that you are struggling at improving
model’s accuracy. In such situation, data exploration techniques will come to
your rescue.
Contents
1. Steps of Data Exploration and Preparation
2. Missing Value Treatment
o Why missing value treatment is required ?
o Why data has missing values?
o Which are the methods to treat missing value ?
3. Techniques of Outlier Detection and Treatment
o What is an outlier?
o What are the types of outliers ?
o What are the causes of outliers ?
o What is the impact of outliers on dataset ?
o How to detect outlier ?
o How to remove outlier ?
4. The Art of Feature Engineering
o What is Feature Engineering ?
o What is the process of Feature Engineering ?
o What is Variable Transformation ?
o When should we use variable transformation ?
o What are the common methods of variable transformation ?
o What is feature variable creation and its benefits ?
Remember the quality of your inputs decide the quality of your output. So, once
you have got your business hypothesis ready, it makes sense to spend lot of time
and efforts here. With my personal estimate, data exploration, cleaning and
preparation can take up to 70% of your total project time.
Below are the steps involved to understand, clean and prepare your data for
building your predictive model:
1. Variable Identification
2. Univariate Analysis
3. Bi-variate Analysis
4. Missing values treatment
5. Outlier treatment
6. Variable transformation
7. Variable creation
Finally, we will need to iterate over steps 4 – 7 multiple times before we come
up with our refined model.
Variable Identification
First, identify Predictor (Input) and Target (output) variables. Next, identify
the data type and category of the variables.
Let’s understand this step more clearly by taking an example.
Example:- Suppose, we want to predict, whether the students will play cricket
or not (refer below data set). Here you need to identify predictor variables,
target variable, data type of variables and category of variables.
Univariate Analysis
Note: Univariate analysis is also used to highlight missing and outlier values. In
the upcoming part of this series, we will look at methods to handle missing and
outlier values. To know more about these methods, you can refer
course descriptive statistics from Udacity.
Bi-variate Analysis
Bi-variate Analysis finds out the relationship between two variables. Here, we
look for association and disassociation between variables at a pre-defined
significance level. We can perform bi-variate analysis for any combination of
categorical and continuous variables. The combination can be: Categorical &
Categorical, Categorical & Continuous and Continuous & Continuous. Different
methods are used to tackle these combinations during analysis process.
• 0: No correlation
Probability less than 0.05: It indicates that the relationship between the variables
is significant at 95% confidence. The chi-square test statistic for a test of
independence of two categorical variables is found by:
From previous two-way table, the expected count for product category 1 to be
of small size is 0.22. It is derived by taking the row total for Size (9) times the
column total for Product category (2) then dividing by the sample size (81).
This is procedure is conducted for each cell. Statistical Measures used to
analyze the power of relationship are:
• Cramer’s V for Nominal Categorical Variable
• Mantel-Haenszed Chi-Square for ordinal categorical variable.
Different data science language and tools have specific methods to perform chi-
square test. In SAS, we can use Chisq as an option with Proc freq to perform
this test.
• Z-Test/ T-Test:- Either test assess whether mean of two groups are statistically
Example: Suppose, we want to test the effect of five different exercises. For
this, we recruit 20 men and assign one type of exercise to 4 men (5 groups).
Their weights are recorded after a few weeks. We need to find out whether the
effect of these exercises on them is significantly different or not. This can be
done by comparing the weights of the 5 groups of 4 men each.
Till here, we have understood the first three stages of Data Exploration,
Variable Identification, Uni-Variate and Bi-Variate analysis. We also looked at
various statistical and visual methods to identify the relationship between
variables.
Missing data in the training data set can reduce the power / fit of a model or can
lead to a biased model because we have not analysed the behavior and
relationship with other variables correctly. It can lead to wrong prediction or
classification.
Notice the missing values in the image shown above: In the left scenario, we
have not treated missing values. The inference from this data set is that the
chances of playing cricket by males is higher than females. On the other hand, if
you look at the second table, which shows data after treatment of missing values
(based on gender), we can see that females have higher chances of playing
cricket compared to males.
1. Deletion: It is of two types: List Wise Deletion and Pair Wise Deletion.
o In list wise deletion, we delete observations where any of the variable is
missing. Simplicity is one of the major advantage of this method, but this
method reduces the power of model because it reduces the sample size.
o In pair wise deletion, we perform analysis with all cases in which the
variables of interest are present. Advantage of this method is, it keeps as
many cases available for analysis. One of the disadvantage of this
method, it uses different sample size for different variables.
o Deletion methods are used when the nature of missing data is “Missing
completely at random” else non random missing values can bias the
model output.
2. Mean/ Mode/ Median Imputation: Imputation is a method to fill in the
missing values with estimated ones. The objective is to employ known
relationships that can be identified in the valid values of the data set to
assist in estimating the missing values. Mean / Mode / Median imputation
is one of the most frequently used methods. It consists of replacing the
missing data for a given attribute by the mean or median (quantitative
attribute) or mode (qualitative attribute) of all known values of that
variable. It can be of two types:-
o Generalized Imputation: In this case, we calculate the mean or median
for all non missing values of that variable then replace missing value with
mean or median. Like in above table, variable “Manpower” is missing so
we take average of all non missing values of “Manpower” (28.33) and
then replace missing value with it.
o Similar case Imputation: In this case, we calculate average for gender
“Male” (29.75) and “Female” (25) individually of non missing values
then replace the missing value based on gender. For “Male“, we will
replace missing values of manpower with 29.75 and for “Female” with
25.
3. Prediction Model: Prediction model is one of the sophisticated
method for handling missing data. Here, we create a predictive model to
estimate values that will substitute the missing data. In this case, we
divide our data set into two sets: One set with no missing values for the
variable and another one with missing values. First data set become
training data set of the model while second data set with missing values is
test data set and variable with missing values is treated as target variable.
Next, we create a model to predict target variable based on other
attributes of the training data set and populate missing values of test data
set.We can use regression, ANOVA, Logistic regression and various
modeling technique to perform this. There are 2 drawbacks for this
approach:
o The model estimated values are usually more well-behaved than
the true values
o If there are no relationships with attributes in the data set and the
attribute with missing values, then the model will not be precise for
estimating missing values.
4. KNN Imputation: In this method of imputation, the missing values of
an attribute are imputed using the given number of attributes that are most
similar to the attribute whose values are missing. The similarity of two
attributes is determined using a distance function. It is also known to have
certain advantage & disadvantages.
o Advantages:
▪ k-nearest neighbour can predict both qualitative & quantitative attributes
▪ Creation of predictive model for each attribute with missing data is not
required
▪ Attributes with multiple missing values can be easily treated
▪ Correlation structure of the data is taken into consideration
o Disadvantage:
▪ KNN algorithm is very time-consuming in analyzing large database. It
searches through all the dataset looking for the most similar instances.
▪ Choice of k-value is very critical. Higher value of k would include
attributes which are significantly different from what we need whereas
lower value of k implies missing out of significant attributes.
After dealing with missing values, the next task is to deal with outliers. Often,
we tend to neglect outliers while building models. This is a discouraging
practice. Outliers tend to make your data skewed and reduces accuracy. Let’s
learn more about outlier treatment.
What is an Outlier?
Let’s take an example, we do customer profiling and find out that the average
annual income of customers is $0.8 million. But, there are two customers
having annual income of $4 and $4.2 million. These two customers annual
income is much higher than rest of the population. These two observations will
be seen as Outliers.
What are the types of Outliers?
Let us understand this with an example. Let us say we are understanding the
relationship between height and weight. Below, we have univariate and
bivariate distribution for Height, Weight. Take a look at the box plot. We do not
have any outlier (above and below 1.5*IQR, most common method). Now look
at the scatter plot. Here, we have two values below and one above the average
in a specific segment of weight and height.
What causes Outliers?
Whenever we come across outliers, the ideal way to tackle them is to find out
the reason of having these outliers. The method to deal with them would then
depend on the reason of their occurrence. Causes of outliers can be classified in
two broad categories:
• Data Entry Errors:- Human errors such as errors caused during data
collection, recording, or entry can cause outliers in data. For example: Annual
income of a customer is $100,000. Accidentally, the data entry operator puts an
additional zero in the figure. Now the income becomes $1,000,000 which is 10
times higher. Evidently, this will be the outlier value when compared with rest
of the population.
• Measurement Error: It is the most common source of outliers. This is caused
when the measurement instrument used turns out to be faulty. For example:
There are 10 weighing machines. 9 of them are correct, 1 is faulty. Weight
measured by people on the faulty machine will be higher / lower than the rest of
people in the group. The weights measured on faulty machine can lead to
outliers.
• Experimental Error: Another cause of outliers is experimental error. For
example: In a 100m sprint of 7 runners, one runner missed out on concentrating
on the ‘Go’ call which caused him to start late. Hence, this caused the runner’s
run time to be more than other runners. His total run time can be an outlier.
• Intentional Outlier: This is commonly found in self-reported measures that
involves sensitive data. For example: Teens would typically under report the
amount of alcohol that they consume. Only a fraction of them would report
actual value. Here actual values might look like outliers because rest of the
teens are under reporting the consumption.
• Data Processing Error: Whenever we perform data mining, we extract data
from multiple sources. It is possible that some manipulation or extraction errors
may lead to outliers in the dataset.
• Sampling error: For instance, we have to measure the height of athletes. By
mistake, we include a few basketball players in the sample. This inclusion is
likely to cause outliers in the dataset.
• Natural Outlier: When an outlier is not artificial (due to error), it is a natural
outlier. For instance: In my last assignment with one of the renowned insurance
company, I noticed that the performance of top 50 financial advisors was far
higher than rest of the population. Surprisingly, it was not due to any error.
Hence, whenever we perform any data mining activity with advisors, we used to
treat this segment separately.
Outliers can drastically change the results of the data analysis and statistical
modeling. There are numerous unfavourable impacts of outliers in the data set:
• It increases the error variance and reduces the power of statistical tests
• If the outliers are non-randomly distributed, they can decrease normality
• They can bias or influence estimates that may be of substantive interest
• They can also impact the basic assumption of Regression, ANOVA and other
statistical model assumptions.
To understand the impact deeply, let’s take an example to check what happens
to a data set with and without outliers in the data set.
Example:
As you can see, data set with outliers has significantly different mean and
standard deviation. In the first scenario, we will say that average is 5.45. But
with the outlier, average soars to 30. This would change the estimate
completely.
• Any value, which is beyond the range of -1.5 x IQR to 1.5 x IQR
• Use capping methods. Any value which out of range of 5th and 95th percentile
can be considered as outlier
• Data points, three or more standard deviation away from mean are considered
outlier
• Outlier detection is merely a special case of the examination of data for
influential data points and it also depends on the business understanding
• Bivariate and multivariate outliers are typically measured using either an index
of influence or leverage, or distance. Popular indices such as Mahalanobis’
distance and Cook’s D are frequently used to detect outliers.
• In SAS, we can use PROC Univariate, PROC SGPLOT. To identify outliers and
influential observation, we also look at statistical measure like STUDENT,
COOKD, RSTUDENT and others.
Till here, we have learnt about steps of data exploration, missing value
treatment and techniques of outlier detection and treatment. These 3 stages will
make your raw data better in terms of information availability and accuracy.
Let’s now proceed to the final stage of data exploration. It is Feature
Engineering.
Feature engineering is the science (and art) of extracting more information from
existing data. You are not adding any new data here, but you are actually
making the data you already have more useful.
For example, let’s say you are trying to predict foot fall in a shopping mall
based on dates. If you try and use the dates directly, you may not be able to
extract meaningful insights from the data. This is because the foot fall is less
affected by the day of the month than it is by the day of the week. Now this
information about day of week is implicit in your data. You need to bring it out
to make your model better.
You perform feature engineering once you have completed the first 5 steps in
data exploration – Variable Identification, Univariate, Bivariate
Analysis, Missing Values Imputation and Outliers Treatment. Feature
engineering itself can be divided in 2 steps:
• Variable transformation.
• Variable / Feature creation.
These two techniques are vital in data exploration and have a remarkable impact
on the power of prediction. Let’s understand each of this step in more details.
• Symmetric
distribution is preferred over skewed distribution as it is easier to interpret
and generate inferences. Some modeling techniques requires normal distribution
of variables. So, whenever we have a skewed distribution, we can
use transformations which reduce skewness. For right skewed distribution, we
take square / cube root or logarithm of variable and for left skewed, we take
square / cube or exponential of variables.
• Square / Cube root: The square and cube root of a variable has a sound effect
on variable distribution. However, it is not as significant as logarithmic
transformation. Cube root has its own advantage. It can be applied to negative
values including zero. Square root can be applied to positive values including
zero.
• Creating derived variables: This refers to creating new variables from existing
variable(s) using set of functions or different methods. Let’s look at it through
“Titanic – Kaggle competition”. In this data set, variable age has missing
values. To predict missing values, we used the salutation (Master, Mr, Miss,
Mrs) of name as a new variable. How do we decide which variable to create?
Honestly, this depends on business understanding of the analyst, his curiosity
and the set of hypothesis he might have about the problem. Methods such as
taking log of variables, binning variables and other methods of variable
transformation can also be used to create new variables.
For further read, here is a list of transformation / creation ideas which can be
applied to your data.