<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
<title type="text">Stories Data Speak</title>
<generator uri="https://github.com/jekyll/jekyll">Jekyll</generator>
<link rel="self" type="application/atom+xml" href="https://duttashi.github.io/feed.xml" />
<link rel="alternate" type="text/html" href="https://duttashi.github.io" />
<updated>2025-04-19T05:04:05+00:00</updated>
<id>https://duttashi.github.io/</id>
<author>
  <name>Ashish Dutt</name>
  <uri>https://duttashi.github.io/</uri>
  <email>ashishdutt@yahoo.com.my</email>
</author>


<entry>
  <title type="html"><![CDATA[]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/2019-08-11-how-to-upload-external-data-in-aws-s3-read-and-analyze-it/" />
  <id>https://duttashi.github.io/2019-08-11-how-to-upload-external-data-in-aws-s3-read-and-analyze-it</id>
  <published>2025-04-19T05:04:05+00:00</published>
  <updated>2025-04-19T05:04:05+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
  <content type="html">&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;

&lt;p&gt;Recently, I stepped into the AWS ecosystem to learn and explore its capabilities. I’m documenting my experiences in these series of posts. Hopefully, they will serve as a reference point to me in future or for anyone else following this path. The objective of this post is, to understand how to create a data pipeline. Read on to see how I did it. Certainly, there can be much more efficient ways, and I hope to find them too. If you know such better method’s, please suggest them in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;comments&lt;/code&gt; section.&lt;/p&gt;

&lt;h4 id=&quot;how-to-upload-external-data-in-amazon-aws-s3&quot;&gt;How to upload external data in Amazon AWS S3&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt;: In the AWS S3 user management console, click on your bucket name.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/s3-1.PNG&quot; alt=&quot;plot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Use the upload tab to upload external data into your bucket.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/s3-2.PNG&quot; alt=&quot;plot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Once the data is uploaded, click on it. In the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Overview&lt;/code&gt; tab, at the bottom of the page you’ll see, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Object Url&lt;/code&gt;. Copy this url and paste it in notepad.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/s3-3.PNG&quot; alt=&quot;plot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now click on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Permissions&lt;/code&gt; tab.&lt;/p&gt;

&lt;p&gt;Under the section, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Public access&lt;/code&gt;, click on the radio button &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Everyone&lt;/code&gt;. It will open up a window.&lt;/p&gt;

&lt;p&gt;Put a checkmark on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Read object permissions&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Access to this objects ACL&lt;/code&gt;. This will give access to reading the data from the given object url.&lt;/p&gt;

&lt;p&gt;Note: Do not give &lt;em&gt;write object permission access&lt;/em&gt;. Also, if read access is not given then the data cannot be read by Sagemaker&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/s3-4.PNG&quot; alt=&quot;plot4&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;aws-sagemaker-for-consuming-s3-data&quot;&gt;AWS Sagemaker for consuming S3 data&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Step 5&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Open &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AWS Sagemaker&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;From the Sagemaker dashboard, click on the button &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;create a notebook instance&lt;/code&gt;. I have already created one as shown below.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/s3-5.PNG&quot; alt=&quot;plot5&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;click on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Open Jupyter&lt;/code&gt; tab&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 6&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;In Sagemaker Jupyter notebook interface, click on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;New&lt;/code&gt; tab (see screenshot) and choose the programming environment of your choice.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/sagemaker-1.PNG&quot; alt=&quot;plot6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Read the data in the programming environment. I have chosen &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;R&lt;/code&gt; in step 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/sagemaker-2.PNG&quot; alt=&quot;plot7&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;accessing-data-in-s3-bucket-with-python&quot;&gt;Accessing data in S3 bucket with python&lt;/h3&gt;

&lt;p&gt;There are two methods to access the data file;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The Client method&lt;/li&gt;
  &lt;li&gt;The Object URL method&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;See this &lt;a href=&quot;https://github.com/duttashi/functions/blob/master/scripts/python/accessing%20data%20in%20s3%20bucket%20with%20python.ipynb&quot;&gt;IPython notebook&lt;/a&gt; for details.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AWS Data pipeline&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To build an AWS Data pipeline, following steps need to be followed;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ensure the user has the required &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;IAM Roles&lt;/code&gt;. See this &lt;a href=&quot;https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-get-setup.html&quot;&gt;AWS documentation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;To use AWS Data Pipeline, you create a pipeline definition that specifies the business logic for your data processing. A typical pipeline definition consists of &lt;a href=&quot;https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-concepts-activities.html&quot;&gt;activities&lt;/a&gt; that define the work to perform, &lt;a href=&quot;https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-concepts-datanodes.html&quot;&gt;data nodes&lt;/a&gt; that define the location and type of input and output data, and a &lt;a href=&quot;https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-concepts-schedules.html&quot;&gt;schedule&lt;/a&gt; that determines when the activities are performed.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;/li&gt;
&lt;/ul&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Risky loan applicants data analysis case study]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/to_lend_funds_or_not/" />
  <id>https://duttashi.github.io/blog/to_lend_funds_or_not</id>
  <published>2023-05-02T00:00:00+00:00</published>
  <updated>2023-05-02T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;The following data analysis is based on a publicly available dataset hosted at &lt;a href=&quot;https://www.kaggle.com/search?q=lending+club+loan+data+in%3Adatasets&quot;&gt;Kaggle&lt;/a&gt;. The complete code is located on my &lt;a href=&quot;https://github.com/duttashi/scrapers/blob/master/AT%26T_round2_data_analysis.py&quot;&gt;github&lt;/a&gt;&lt;/p&gt;

&lt;h5 id=&quot;exploratory-data-analysis&quot;&gt;EXPLORATORY DATA ANALYSIS&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;The dataset is a single csv file. It has a shape of 42,542 observations in 144 variables.
    &lt;ul&gt;
      &lt;li&gt;The response or dependent variable is “loan_status” and is categorical in nature.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Off the 144 variables, majority of them (~110) are continuous in nature and rest are categorical data types.&lt;/li&gt;
  &lt;li&gt;All 144 variables have missing values.
    - Variables with 80% missing data were removed. The dataset size reduced to 54 variables.&lt;/li&gt;
  &lt;li&gt;Correlation treatment helped reduce dataset size to 45 variables. Turns out, independent variables such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;funded amount&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;funded amount inv&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;installment&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total payment&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total payment inv&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total rec prncp&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;total rec int&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collection recovery fee&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pub rec bankruptcies&lt;/code&gt; are strongly correlated (&amp;gt;=80%) with the dependent variable.&lt;/li&gt;
  &lt;li&gt;By this stage, the dataset shape is 42,542 observations in 45 variables (25 continuous, 3 datetime, and 17 categorical).&lt;/li&gt;
  &lt;li&gt;The dependent variable has 4 factor levels. I recoded the 4 factor levels to 2 as asked by the assignment.
    &lt;ul&gt;
      &lt;li&gt;34116 observations for loans that were fully paid&lt;/li&gt;
      &lt;li&gt;8426 observations for loans that were charged off&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;The dependent variable was label encoded to make it suitable for model building. As earlier stated, it’s now a binary categorical variable with two levels. Label &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; refers to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Fully Paid&lt;/code&gt; and Label &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; refers to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Charged Off&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;It should be noted, the dependent variable is imbalanced in nature. This means, data balancing method need to be applied for building a robust model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5 id=&quot;visuals&quot;&gt;VISUALS&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;A histogram comparing the annual income of applicants from the states of West Virginia (WV) and New Mexico (NM). Is there any relationship here?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_2023_april_1.png&quot; alt=&quot;hist1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Average annual income of applicants from WV and NM&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The top Top 3 states with highest number of loan defaults are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;California (CA)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;New York (NY)&lt;/code&gt;and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Texas (TX)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_2023_april_2.png&quot; alt=&quot;bar1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Top 3 states with highest loan defaults&lt;/p&gt;

&lt;h5 id=&quot;data-sampling&quot;&gt;DATA SAMPLING&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;To build a classifier model, I took following steps,
    &lt;ul&gt;
      &lt;li&gt;Data shape at this stage was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(42542, 45)&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;Took a 0.05% random sample of the dataset for further analysis.&lt;/li&gt;
      &lt;li&gt;Data shape of sample size was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2127, 45)&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;The reason I took a sample of the original dataset was the presence of several categorical variables with factor levels greater than 5. Label encoding such categorical variables yielded meaningless information in model building and one-hot encoding blew up the dataset size to more than 3GB!&lt;/li&gt;
      &lt;li&gt;Did label encoding for categorical variables with factor levels less than or equal to 2 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(term, pymnt_plan&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;initial_list_status&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;application_type&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hardship_flag&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;debt_settlement_flag&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;target)&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;Did one-hot encoding for rest of categorical variables with factor levels greater than 2. Dataset shape becomes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2127, 6965)&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h5 id=&quot;model-building&quot;&gt;MODEL BUILDING&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;Null Hypothesis: From Fig-1, its apparent there is no relationship between the average annual income of applicants from WV and NM. To verify this claim further, a significance test is conducted using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ttest_1samp()&lt;/code&gt; function from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scipy.stats&lt;/code&gt; library.&lt;/li&gt;
  &lt;li&gt;Used label encoded data.&lt;/li&gt;
  &lt;li&gt;Performed a stratified random sampling to split the dataset into 80% train and 20% test parts (in code, see lines 124 to line 154).
    &lt;ul&gt;
      &lt;li&gt;Chose logistic regression algorithm&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Building a classification model on imbalanced dependent variable
    &lt;ul&gt;
      &lt;li&gt;F1 score for loan status with value Charged Off (0) is 90%&lt;/li&gt;
      &lt;li&gt;F1 score for loan status with value Fully Paid (1) is 98%&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Applied synthetic minority over sampling (SMOTE) method for data balancing
    &lt;ul&gt;
      &lt;li&gt;F1 score for loan status with value Charged Off (0) is 99%&lt;/li&gt;
      &lt;li&gt;F1 score for loan status with value Fully Paid (1) is 100%&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Model Summary statistics as follows;&lt;/p&gt;

&lt;h4 id=&quot;imbalanced-data-classification&quot;&gt;Imbalanced data classification&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;          precision    recall  f1-score   support
       0       1.00      0.74      0.85        68
       1       0.95      1.00      0.98       358

    accuracy                        0.96       426
   macro avg       0.98      0.87   0.91       426
weighted avg       0.96      0.96   0.96       426

Resampled data shape:  (2856, 6975)
Balanced target
0    1428
1    1428
Name: target, dtype: int64
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;balanced-data-using-smote&quot;&gt;Balanced data using SMOTE&lt;/h4&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;       precision    recall  f1-score   support

       0       0.98      0.90      0.94        68
       1       0.98      1.00      0.99       358

accuracy                                0.98       426
macro avg       	0.98      0.95      0.96       426
weighted avg        0.98      0.98      0.98       426
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;end-notes&quot;&gt;End notes&lt;/h4&gt;

&lt;p&gt;To develop a strategy for risk averse customers, the following points may be considered;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;We should target semi-urban or rural locations. Reason, such areas are replete with middle-economic class and/or lower economic class groups of people. In such sections of society, the penetration of information on Peer to Peer (P2P) lending is low. Our priority should be to educate such masses of people on the benefits and pitfalls of P2P lending as compared to other lending methods.&lt;/li&gt;
  &lt;li&gt;Next, such customers can be educated about the Mutual Fund (MF) investment options, in particular the debt MF growth option. This strategy may help to maintain low default rates because the debt MF expense ratio charged by MF companies are comparatively less as compared to equity MF expense ratios.&lt;/li&gt;
&lt;/ul&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Predicting the misclassification cost incurred in air pressure system failure in heavy vehicles]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/air-pressure-heavy-vehicle/" />
  <id>https://duttashi.github.io/blog/air-pressure-heavy-vehicle</id>
  <published>2020-03-01T00:00:00+00:00</published>
  <updated>2020-03-01T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;abstract&quot;&gt;Abstract&lt;/h3&gt;

&lt;p&gt;The Air Pressure System (APS) is a type of function used in heavy vehicles to assist braking and gear changing. The APS failure dataset consists of the daily operational sensor data from failed Scania trucks. The dataset is crucial to the manufacturer as it allows to isolate components which caused the failure. However, missing values and imbalanced class problems are the two most challenging limitations of this dataset to predict the cause of the failure. The prediction results can be affected by the way of handling these missing values and imbalanced class problem. In this report, I have examined and presented the impact of three data balancing techniques, namely: under sampling, over sampling and Synthetic Minority Over Sampling Technique in producing significantly better results. I have also performed an empirical comparison of their performance by applying three different classifiers namely: Logistic Regression, Gradient Boosting Machines, and Linear Discriminant Analysis on this highly imbalanced dataset. The primary aim of this study is to observe the impact of the aforementioned data balancing techniques in the enhancement of the prediction results and performing an empirical comparison to determine the best classification model. I found that the logistic regression over-sampling technique is the highest influential method for improving the prediction performance and false negative rate.&lt;/p&gt;

&lt;h3 id=&quot;1-introduction&quot;&gt;1.	Introduction&lt;/h3&gt;
&lt;p&gt;This data set is created by Scania CV AB Company to analyze APS failures and operational data for Scania Trucks. The dataset’s positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS.&lt;/p&gt;

&lt;h3 id=&quot;2-objective&quot;&gt;2.	Objective&lt;/h3&gt;
&lt;p&gt;The objective of this report are two fold, namely;&lt;/p&gt;

&lt;p&gt;a.	To develop a Predictive Model (PM) to determine the class of failure&lt;/p&gt;

&lt;p&gt;b.	To determine the cost incurred by the company for misclassification.&lt;/p&gt;

&lt;h3 id=&quot;3-data-analysis&quot;&gt;3.	Data Analysis&lt;/h3&gt;
&lt;p&gt;A systematic data analysis was undertaken to answer the objectives.&lt;/p&gt;

&lt;h4 id=&quot;a-data-source&quot;&gt;A.	Data source&lt;/h4&gt;
&lt;p&gt;For this analysis, I have used the dataset hosted on &lt;a href=&quot;https://archive.ics.uci.edu/ml/datasets/APS+Failure+at+Scania+Trucks&quot;&gt;UCI ML Repository&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;b-exploratory-data-analysis&quot;&gt;B.	Exploratory Data Analysis&lt;/h4&gt;
&lt;p&gt;There were two sets of data, the training set and the test set.&lt;/p&gt;

&lt;h5 id=&quot;i-observations&quot;&gt;i.	Observations&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;The training set consisted of 60,000 observations in 171 variables and&lt;/li&gt;
  &lt;li&gt;The test set consist of 16,000 observations in 171 variables.&lt;/li&gt;
  &lt;li&gt;The missing values were coded as “na”&lt;/li&gt;
  &lt;li&gt;The training set had 850015 missing values&lt;/li&gt;
  &lt;li&gt;The test set had 228680 missing values&lt;/li&gt;
  &lt;li&gt;The outcome or the dependent variable was highly skewed or imbalanced as shown in Figure 1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2_1.png&quot; alt=&quot;plot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 1: Imbalanced class distribution&lt;/p&gt;

&lt;h5 id=&quot;ii-dimensionality-reduction-steps-for-training-data&quot;&gt;ii.	Dimensionality reduction steps for training data&lt;/h5&gt;
&lt;p&gt;The training set contained 60,000 observations in 171 variables of which the dependent variable was binary in nature called, “class”. I had to find the variables that accounted for maximum variance. I took the following measures for dimensionality reduction:&lt;/p&gt;

&lt;p&gt;a)	Check for variables with more than 75% missing data&lt;/p&gt;

&lt;p&gt;I found 6 independent variables that satisfied this property. I removed them from subsequent analysis. The count of independent variables decreased to 165.&lt;/p&gt;

&lt;p&gt;b)	Check for variables with more than 80% zero values&lt;/p&gt;

&lt;p&gt;I found 33 independent variables that satisfied this property. I removed them from subsequent analysis. The count of independent variables decreased to 132.&lt;/p&gt;

&lt;p&gt;c)	Check for variables where standard deviation is zero&lt;/p&gt;

&lt;p&gt;I found 1 independent variable that satisfied this property. I removed it from subsequent analysis. The count of independent variables decreased to 131.&lt;/p&gt;

&lt;p&gt;d)	Check for variables with near zero variance property&lt;/p&gt;

&lt;p&gt;I found 10 independent variables that satisfied this property. I removed them from subsequent analysis. The count of independent variables decreased to 121.&lt;/p&gt;

&lt;p&gt;e)	Missing data detection and treatment&lt;/p&gt;

&lt;p&gt;Since all independent variables were continuous in nature, I used median to impute the missing values in them. In Figure 2, I’ve shown the missing data pattern visualization.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2_2.png&quot; alt=&quot;plot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 2: Missing data visualization for training dataset&lt;/p&gt;

&lt;p&gt;In Figure 2, the black colored histogram actually shows the missing data pattern. As the number of independent variables was huge, not all of them are shown and hence the color is black.&lt;/p&gt;

&lt;p&gt;f)	Correlation detection and treatment&lt;/p&gt;

&lt;p&gt;I found several continuous variables to be highly correlated. I applied an unsupervised approach, the Principal Component Analysis (PCA) to extract non-correlated variables. PCA also helps in dimensionality reduction and provides variables with maximum variance. In Figure 3, I have shown the important principal components.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2_3.png&quot; alt=&quot;plot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 3: Important principal components for training dataset&lt;/p&gt;

&lt;h4 id=&quot;c-predictive-modeling&quot;&gt;C.	Predictive modeling&lt;/h4&gt;

&lt;p&gt;As noted above (see sub-section B-i), this dataset was severely imbalanced. If left untreated, the predictions will be incorrect. I will now show the predictions on the original imbalanced dataset followed by the predictions on the balanced dataset. Thereafter, I’ve provided a discussion on the same.&lt;/p&gt;

&lt;h5 id=&quot;i-assumption&quot;&gt;i. Assumption&lt;/h5&gt;
&lt;p&gt;In this analysis, my focus is on correctly predicting the positive class, i.e., the trucks with component failures for a specific component of the APS system.&lt;/p&gt;

&lt;h5 id=&quot;ii-data-splitting&quot;&gt;ii. Data splitting&lt;/h5&gt;
&lt;p&gt;I created a control function based on 3-fold cross validation. Then I split the training set into 70% training and 30% test set. The training dataset contained 42,000 observations in 51 variables. The test set contained 18,000 observations in 51 variables.&lt;/p&gt;

&lt;h5 id=&quot;iii-justification-on-classifier-metric-choice&quot;&gt;iii. Justification on classifier metric choice&lt;/h5&gt;
&lt;p&gt;Note, I chose Precision Recall Area Under Curve (PR AUC) as a classification metric over Receiver Operating Curve Area Under Curve (ROC AUC).&lt;/p&gt;

&lt;p&gt;The key difference is that ROC AUC will be the same no matter what the baseline probability is, but PR AUC may be more useful in practice for needle-in-haystack type problems or problems where the “positive” class is more interesting than the negative class. And this is my fundamental justification to why I chose PR AUC over ROC AUC, because I’m interested in predicting the positive class. This also answers the challenge metric on reducing the type 1 and type II errors.&lt;/p&gt;

&lt;h5 id=&quot;iv-predictive-modeling-on-imbalanced-training-dataset&quot;&gt;iv. Predictive modeling on imbalanced training dataset&lt;/h5&gt;

&lt;p&gt;I chose 3 classifiers namely logistic regression (logreg), linear discriminant analysis (lda) and gradient boosting machine (gbm) algorithms for prediction comparative analysis. I also chose three sampling techniques for data balancing, namely, under sampling, over sampling and synthetic minority over sampling technique (SMOTE). The logistic regression model gave the highest sensitivity.&lt;/p&gt;

&lt;p&gt;And in Figure 4, I’ve shown the dot plot which depicts the PR-AUC scores visualization on the imbalanced dataset.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2_4.png&quot; alt=&quot;plot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 4: Dot plot on imbalanced training dataset&lt;/p&gt;

&lt;h5 id=&quot;v-challenge-metric-computation-on-imbalanced-training-dataset&quot;&gt;v. Challenge metric computation on imbalanced training dataset&lt;/h5&gt;

&lt;p&gt;Challenge metric is the cost metric of misclassification. Where cost 1 = 10 and cost 2 = 500&lt;/p&gt;

&lt;p&gt;Total cost = 10 * CM.FP + 500 * CM.FN&lt;/p&gt;

&lt;p&gt;Total cost = 10&lt;em&gt;55+500&lt;/em&gt;149 = $75, 050&lt;/p&gt;

&lt;p&gt;The company will incur $75, 050 in misclassification cost on the imbalanced dataset.&lt;/p&gt;

&lt;h5 id=&quot;vi-predictive-modelling-on-balanced-training-dataset&quot;&gt;vi.	Predictive modelling on balanced training dataset&lt;/h5&gt;

&lt;p&gt;For data balancing, I chose 3 different methods, namely under-sampling, over-sampling and Synthetic Minority Over Sampling Technique (SMOTE). I found the over sampling technique to be most effective for logistic regression model.  So I applied this technique on the balanced training dataset&lt;/p&gt;

&lt;p&gt;I’ll now show the predictive modelling on the balanced training dataset. As shown earlier, I split the dataset into 70-30 ratio and applied a 3-fold cross validation. Then, I applied the logistic regression algorithm by up-sampling, down-sampling and synthetic minority over sampling methods shown in Figure 5.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2_5.png&quot; alt=&quot;plot5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 5: Dot plot on balanced training dataset&lt;/p&gt;

&lt;h5 id=&quot;vii-challenge-metric-computation-on-balanced-training-dataset&quot;&gt;vii.	Challenge metric computation on balanced training dataset&lt;/h5&gt;

&lt;p&gt;Challenge metric is the cost metric of misclassification. Where cost 1 = 10 and cost 2 = 500&lt;/p&gt;

&lt;p&gt;Over sampling based logistic regression&lt;/p&gt;

&lt;p&gt;Total cost = 10 * CM.FP + 500 * CM.FN&lt;/p&gt;

&lt;p&gt;Total cost = 10&lt;em&gt;540+500&lt;/em&gt;33 = $21,900&lt;/p&gt;

&lt;p&gt;The benefit of data balancing is evident. By extracting the independent variables with variance and balancing, I was able to reduce the misclassification cost from the initial $75,050 to $21,900 on the balanced training dataset.&lt;/p&gt;

&lt;h5 id=&quot;viii-challenge-metric-computation-on-balanced-test-dataset&quot;&gt;viii.	Challenge metric computation on balanced test dataset&lt;/h5&gt;
&lt;p&gt;Next, I’ll apply the logistic regression over sampled method to the clean test dataset.&lt;/p&gt;

&lt;p&gt;Challenge metric is the cost metric of misclassification. Where cost 1 = 10 and cost 2 = 500&lt;/p&gt;

&lt;p&gt;Over sampling based logistic regression on test data&lt;/p&gt;

&lt;p&gt;Total cost = 10 * CM.FP + 500 * CM.FN&lt;/p&gt;

&lt;p&gt;Total cost = 10&lt;em&gt;359+500&lt;/em&gt;8 = $7,590&lt;/p&gt;

&lt;p&gt;The predicted misclassification cost is found to be $7,590.&lt;/p&gt;

&lt;h4 id=&quot;discussion&quot;&gt;Discussion&lt;/h4&gt;
&lt;p&gt;Oversampling and under sampling can be used to alter the class distribution of the training data and both methods have been used to deal with class imbalance. The reason that altering the class distribution of the training data aids learning with highly-skewed data sets is that it effectively imposes non-uniform misclassification costs. There are known disadvantages associated with the use of sampling to implement cost-sensitive learning. The disadvantage with under sampling is that it discards potentially useful data. The main disadvantage with oversampling, from my perspective, is that by making exact copies of existing examples, it makes over fitting likely. 
Traditionally, the most frequently used metrics are accuracy and error rate. Considering a basic two-class classification problem, let {p,n} be the true positive and negative class label and {Y,N} be the predicted positive and negative class labels. Then, a representation of classification performance can be formulated by a confusion matrix (contingency table), as illustrated in Table 3. These metrics provide a simple way of describing a classifier’s performance on a given data set. However, they can be deceiving in certain situations and are highly sensitive to changes in data. In the simplest situation, if a given data set includes 5 percent of minority class examples and 95 percent of majority examples, a naive approach of classifying every example to be a majority class example would provide an accuracy of 95 percent. Taken at face value, 95 percent accuracy across the entire data set appears superb; however, on the same token, this description fails to reflect the fact that 0 percent of minority examples are identified. That is to say, the accuracy metric in this case does not provide adequate information on a classifier’s functionality with respect to the type of classification required. 
Although ROC curves provide powerful methods to visualize performance evaluation, they also have their own limitations. In the case of highly skewed data sets, it is observed that the ROC curve may provide an overly optimistic view of an algorithm’s performance. Under such situations, the PR curves can provide a more informative representation of performance assessment. To see why the PR curve can provide more informative representations of performance assessment under highly imbalanced data, let’s consider a distribution where negative examples significantly exceed the number of positive examples (i.e. N_c&amp;gt;P_c). In this case, if a classifier performance has a large change in the number of false positives, it will not significantly change the FP rate since the denominator N_c is very large. Hence, the ROC graph will fail to capture this phenomenon. The precision metric, on the other hand considers the ratio of TP with respect to TP+FP; hence it can correctly capture the classifiers performance when the number of false positives drastically change. Hence, as evident by this example the PR AUC is an advantageous technique for performance assessment in the presence of highly skewed data. Another shortcoming of ROC curves is that they lack the ability to provide confidence intervals on a classifier’s performance and are unable to infer the statistical significance of different classifiers’ performance. They also have difficulties providing insights on a classifier’s performance over varying class probabilities or misclassification costs. In order to provide a more comprehensive evaluation metric to address these issues, cost curves or PR AUC is suggested.&lt;/p&gt;

&lt;h5 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h5&gt;
&lt;p&gt;In this dataset, there were several problems notably the major one was the class imbalance issue, which was followed by missing values and other issues that I’ve highlighted in sub-section 3iii. However, the challenge was not the class imbalance issue per se but the choice of an appropriate metric that could correctly answer the assumption I had formulated in sub-section Ci. The tradeoff between PR AUC and AUC is discussed in sub-section 3iii. Furthermore, I was able to reduce the misclassification cost to &lt;strong&gt;$7,590&lt;/strong&gt; by over sampling the data.&lt;/p&gt;

&lt;h4 id=&quot;appendix-a&quot;&gt;Appendix A&lt;/h4&gt;

&lt;h5 id=&quot;explanation-of-statistical-terms-used-in-this-study&quot;&gt;Explanation of statistical terms used in this study&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;Variable: is any characteristic, number or quantity that is measurable. Example, age, sex, income are variables.&lt;/li&gt;
  &lt;li&gt;Continuous variable:  is a numeric or a quantitative variable. Observations can take any value between a set of real numbers. Example, age, time, distance.&lt;/li&gt;
  &lt;li&gt;Independent variable: also known as the predictor variable. It is a variable that is being manipulated in an experiment in order to observe an effect on the dependent variable. Generally in an experiment, the independent variable is the “cause”.&lt;/li&gt;
  &lt;li&gt;Dependent variable: also known as the response or outcome variable. It is the variable that is needs to be measured and is affected by the manipulation of independent variables. Generally, in an experiment it is the “effect”.&lt;/li&gt;
  &lt;li&gt;Variance: explains the distribution of data, i.e. how far a set of random numbers are spread out from their original values.&lt;/li&gt;
  &lt;li&gt;Regression analysis: It is a set of statistical methods used for the estimation of relationships between a dependent variable and one or more independent variables. It can be utilized to assess the strength of the relationship between variables and for modeling the future relationship between them.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;appendix-b&quot;&gt;Appendix B&lt;/h4&gt;

&lt;p&gt;The R code for this study can be downloaded from &lt;a href=&quot;https://github.com/duttashi/duttashi.github.io/blob/master/scripts/CaseStudy-air_pressure_system_failure.R&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[A classification approach to predicting air crash survival]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/aircraft-crash-survival/" />
  <id>https://duttashi.github.io/blog/aircraft-crash-survival</id>
  <published>2020-02-21T00:00:00+00:00</published>
  <updated>2020-02-21T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;

&lt;p&gt;Historically there have been several instance of air plane crashes. This study is an attempt to explore the possible causes of such air crashes, and to determine if air travel is a safe option.&lt;/p&gt;

&lt;h3 id=&quot;objective&quot;&gt;Objective&lt;/h3&gt;

&lt;p&gt;The objective of this study are two fold, namely;&lt;/p&gt;

&lt;p&gt;a. To perform an Exploratory Data Analysis (EDA) to determine the common cause/reason of airplane crash, countries with maximum/minimum airplane crashes, fatalities vs survived ratio and any other interesting trend.&lt;/p&gt;

&lt;p&gt;b.	To develop a Predictive Model (PM) to determine the following;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Is traveling by air a safe option?&lt;/li&gt;
  &lt;li&gt;In particular analyze the historical data to determine the accuracy of air crash survival.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;data-analysis&quot;&gt;Data Analysis&lt;/h3&gt;

&lt;p&gt;A systematic data analysis was undertaken to answer the objectives.&lt;/p&gt;

&lt;h4 id=&quot;a-data-source&quot;&gt;A.	Data source&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;For this analysis, I have used two data sources. The primary data source was Kaggle and the secondary source was &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;www.planecrashinfo.com&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;The dataset hosted on Kaggle was from 1908 till 2009.&lt;/li&gt;
  &lt;li&gt;The secondary data source was required because I needed plane crash data from 2010 until 2020. This would help in both EDA and PM.&lt;/li&gt;
  &lt;li&gt;So for this analysis, I wrote a custom scrapper to extract the air crash data from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;www.planecrashinfo.com&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;b-exploratory-data-analysis&quot;&gt;B.	Exploratory Data Analysis&lt;/h4&gt;

&lt;p&gt;Both datasets were dirty. Several data management tasks were carried out to clean the data. As per a researcher Wickham, H. (2014), tidy data is a dataset where each variable is a column and each observation (or case) is a row.&lt;/p&gt;

&lt;h5 id=&quot;1-data-management-decisions&quot;&gt;1. Data management decisions&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;The Kaggle dataset consisted of 5,268 observations in 13 variables. It had 10,198 missing values&lt;/li&gt;
  &lt;li&gt;The external dataset consisted of 237 observation in 13 variables.&lt;/li&gt;
  &lt;li&gt;The missing values in external dataset were coded as “?”. These were re-coded to NA. There were 222 missing values.&lt;/li&gt;
  &lt;li&gt;The Kaggle dataset and the external data were then merged into a composite dataframe, hereafter referred to as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df&lt;/code&gt; consisted of 5,505 observations in 13 variables.&lt;/li&gt;
  &lt;li&gt;The range of aircraft crash years was from 1908 till 2020.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5 id=&quot;ii-feature-engineering&quot;&gt;ii.	Feature engineering&lt;/h5&gt;

&lt;p&gt;The variable summary contained free form text related to plane crash details. It contained important information. But it needed cleaning. So I created some derived variables like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_reason&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_date, crash_month, crash_year&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_hour, crash_minute, crash_second&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_area, crash_country&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_route_start, crash_route_mid, crash_route_end&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash_operator_type&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;survived&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alive_dead_ratio&lt;/code&gt;.&lt;/p&gt;

&lt;h4 id=&quot;c-data-visualization&quot;&gt;C.	Data Visualization&lt;/h4&gt;

&lt;p&gt;As the common adage goes, “a picture is worth a thousand words”. Once the data was cleaned and composed in a tidy format, it was ready for visualizations. Data visualization helps in determining possible relationship between variables. In Fig-1 &amp;amp; Fig-2, I show the common reasons for air crash sorted by descriptions and words. In particular, air crash during take offs are maximum, see Fig-1.&lt;/p&gt;

&lt;h5 id=&quot;i-visualizing-the-common-reasons-attributed-to-air-plane-crash&quot;&gt;i.	Visualizing the common reasons attributed to air plane crash&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_1.png&quot; alt=&quot;plot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Common air crash descriptions&lt;/p&gt;

&lt;h5 id=&quot;ii-visualizing-the-common-words-used-for-air-plane-crash&quot;&gt;ii.	Visualizing the common words used for air plane crash&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_2.png&quot; alt=&quot;plot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Common air crash words&lt;/p&gt;

&lt;h5 id=&quot;iii-visualizing-the-crashed-flight-operators&quot;&gt;iii.	Visualizing the crashed flight operators&lt;/h5&gt;

&lt;p&gt;A majority of the flight operators are US-military, AirForce, Aeroflot, Air France and Luftansa, as seen from Fig-3.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_3.png&quot; alt=&quot;plot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Air crash flight operators&lt;/p&gt;

&lt;p&gt;The peak of air crash survivors was in year 2000, see Fig-4. Probably the reason could be because of better aircraft’s compared to yesteryear’s.&lt;/p&gt;

&lt;h5 id=&quot;iv-visualizing-the-air-crash-survivors&quot;&gt;iv.	Visualizing the air crash survivors&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_4.png&quot; alt=&quot;plot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-4: Air crash survivors by year&lt;/p&gt;

&lt;p&gt;It was found that there were more civilian air crashes as compared to military crashes. Moreover, 3,198 fatalities are observed in air crashes since 1908, including both civilian and military air crashes. So, I took a subset of the civilian air crashes data and plotted it. I present them below in the form of some hypothesis.&lt;/p&gt;

&lt;h5 id=&quot;v-visualizing-the-civilian-air-crash-fatalities&quot;&gt;v.	Visualizing the civilian air crash fatalities&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_5.png&quot; alt=&quot;plot5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Civilian air crash survivors by year&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;The peak of air crashes lay between the years 1970-1980s.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Off these 58 aircraft’s crashed in Alaska, followed by 45 in Russia, 32 and 30 in Colombia and California respectively.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;I then filtered data for crash year after year 2010 and found that Russia recorded maximum civilian fatalities in year 2011 (dead=5), followed by Indonesia in year 2015 (dead=4) and Russia in year 2012 (dead=4). See Fig-5.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h5 id=&quot;vi-is-there-a-relationship-between-civilian-air-crash-year-and-crash-reason&quot;&gt;vi.	Is there a relationship between civilian air crash year and crash reason&lt;/h5&gt;

&lt;p&gt;I plotted this relationship and found the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There were 4,692 civilian air crashes since 1908 and 813 military induced air crashes. See Fig-6.&lt;/li&gt;
  &lt;li&gt;Off these 4,692 civilian air crashes, 644 occurred after year 2000.&lt;/li&gt;
  &lt;li&gt;Off the 644 civil air crashes, 301 were technical failures, 86 by natural cause, 52 crashed in mountains and 7 were shot down by military. There are 198 uncategorized crashes.&lt;/li&gt;
  &lt;li&gt;The civilian aircrafts shot down by military crashed in countries like Congo (year 2003), Iran (year 2020), Laos (year 2014), Kedarnath, India (year 2013), Rapua (year 2016), Russia (year 2001) and Zabul province (year 2010).&lt;/li&gt;
  &lt;li&gt;Majority of civil air crashes were due to technical failure. At least 4 aircrafts crashed in Russia in 2011 because of technical failure. This was followed by Sudan, where 3 planes were lost in 2008 because of technical failure. Since the year 2010, there were 20 civilian aircraft crashes for Russia, 10 for Nepal, followed by Congo and Indonesia at 9 each.&lt;/li&gt;
  &lt;li&gt;The median for military action related air crash was around year 1951&lt;/li&gt;
  &lt;li&gt;The median for mountain and natural caused crashes was around year 1976&lt;/li&gt;
  &lt;li&gt;The median for technical failure related crashes was around 1977.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_6.png&quot; alt=&quot;plot6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-6: Reasons for civilian air crashes sorted by year&lt;/p&gt;

&lt;h5 id=&quot;vii-is-there-a-relationship-between-civilian-air-crash-month-and-crash-reason&quot;&gt;vii.	Is there a relationship between civilian air crash month and crash reason&lt;/h5&gt;

&lt;p&gt;I plotted this relationship and found the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A majority of air crashes took place around the month of July. These crashes were related to mountain, natural, miscellaneous and natural reasons. See Fig-7.&lt;/li&gt;
  &lt;li&gt;Russia tops this list with 7 air crafts crashing in July month because of technical failure. Off these 7 air crafts, 4 were of Antonov An series.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_7.png&quot; alt=&quot;plot7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Reasons for civilian air crashes sorted by month&lt;/p&gt;

&lt;h5 id=&quot;viii-is-there-a-relationship-between-civilian-air-crash-fatalities-and-crash-reason&quot;&gt;viii.	Is there a relationship between civilian air crash fatalities and crash reason&lt;/h5&gt;

&lt;p&gt;Although the median for civilian air crash fatalities normally centered around 1-5 people, but there were several outlier values too. For instance in one military action induced civil aircraft crash took the life of all 290 people aboard. This incident occurred in 1988 at 10:55pm over the Persian Gulf, near Bandar Abbas in Iran. The Airbus A300B2-203 bearing registration number EPIBU was shot down by an US Navy vessel USS Vincennes by a SAM (surface to air) missile. See Fig-8.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_8.png&quot; alt=&quot;plot8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-8: Reasons for civilian air crashes sorted by fatalities&lt;/p&gt;

&lt;h4 id=&quot;d-data-sub-setting&quot;&gt;D.	Data sub setting&lt;/h4&gt;

&lt;p&gt;Looking at the data distribution, I found maximum observation were related to civilian aircraft crashes (n=4692) while the observations for military aircraft crashes were less (n=813). Furthermore, I subset the civilian air craft crashes since the year 2010. The reasoning is, to answer the first objective, “is travelling by air a safe option”, I needed to analyze the data for the last one decade. The data dimension for civilian air craft crash since year 2010 was 205 observations in 24 variables (includes both original &amp;amp; derived variables).&lt;/p&gt;

&lt;h4 id=&quot;e-detecting-near-zero-variance-nzv&quot;&gt;E.	Detecting Near Zero Variance (NZV)&lt;/h4&gt;

&lt;p&gt;NZV is a property wherein a given variable has almost zero trend, i.e. all its values are identical. I found two such variables in civilian aircraft crashes. They were, “ground” &amp;amp; “crash operator type”. I removed them from further analysis. I also removed the summary variable. At this stage, the data dimension for civilian air craft crash since year 2010, was 205 observations in 21 variables (includes both original &amp;amp; derived variables)&lt;/p&gt;

&lt;h4 id=&quot;f-missing-data-analysis&quot;&gt;F.	Missing data analysis&lt;/h4&gt;

&lt;p&gt;There are two types of missing data:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Missing Completely At Random (MCAR): is a desirable scenario&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Missing Not At Random: is a serious issue and it would be best to check the data gathering process.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For this analysis, I’m assuming the data is MCAR. Usually a safe minimal threshold is 5% of the total for a dataset. For a given variable, if the data is missing for more than 5% then it’s safe to leave that variable out of analysis. Basis of this assumption, I found the following variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Crash_hour, Crash_minute, Flight, Crash_route_start, Crash_route_mid, Crash_route_end, Fuselage_number&lt;/code&gt;, with more than 5% missing data.&lt;/p&gt;

&lt;p&gt;It should be noted that for civilian aircraft crashes since 1908, in all there were 16051 observations with missing data. Furthermore, for civilian aircraft crashes since 2010, there were 370 missing values. Since the sample size was small (n=205), I imputed the missing values as Zero.&lt;/p&gt;

&lt;h4 id=&quot;g-correlation-detection&quot;&gt;G.	Correlation detection&lt;/h4&gt;
&lt;p&gt;In building a predictive model, it’s always advisable to account for correlation. It is a statistical term that measures the degree of linear dependency between variables. So variables that are highly correlated to each other are deemed to be non-contributors to a given predictive model. In Fig 9, I show the correlation plot for continuous variables. For instance, the variable aboard and fatalities have a strong negative correlation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_9.png&quot; alt=&quot;plot9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-9: Correlation detection for continuous variables&lt;/p&gt;

&lt;h5 id=&quot;i-correlation-treatment&quot;&gt;i.	Correlation treatment&lt;/h5&gt;

&lt;p&gt;To treat the correlation, I have applied an unsupervised dimensionality reduction and feature selection approach called the Principal Component Analysis (PCA) for continuous variables, and the Multiple Correspondence Analysis (MCA) for the categorical variables.
In Fig-10, I have shown relevant principal components (PCs). Notice the red horizontal line in Fig 10 (B). This red line indicates the cut-off point. Therefore the continuous variables namely, “aboard, fatalities, crash minute, crash month, crash date, crash year” are deemed relevant for further analysis.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_10.png&quot; alt=&quot;plot10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-10: Principal Component Analysis for dimensionality reduction &amp;amp; feature selection&lt;/p&gt;

&lt;p&gt;Next, In Fig-11, I have shown the MCA for categorical variables. Notice the red horizontal line in Fig-11 (B). This red line indicates the cut-off point. As we can see from this plot that none off the categorical variables are deemed relevant for further analysis.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_11.png&quot; alt=&quot;plot11&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-11: Multiple Correspondence Analysis for dimensionality reduction &amp;amp; feature selection&lt;/p&gt;

&lt;p&gt;By this stage, the data dimension for air craft crashes since 2010 was reduced to 205 observation in 7 variables.&lt;/p&gt;

&lt;h4 id=&quot;h-predictive-analytics&quot;&gt;H.	Predictive analytics&lt;/h4&gt;

&lt;p&gt;The derived variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;survived&lt;/code&gt; was continuous in nature. For a classification task, I coerced it into categorical with two levels. If there were 0 survivors, then I coded it as “dead” and if there were more than 1 survivor, it was coded as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alive&lt;/code&gt; and saved it as a variable called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash survivor&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I found that in 205 complete clean observations, the proportion of dead was 63% and that of alive was 37%. This indicated that the outcome/dependent variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash survivor&lt;/code&gt; was imbalanced. If this anomaly is left untreated, then any model based on this variable will give erroneous results. An imbalanced dataset refers to the disparity encountered in the dependent (response) variable.&lt;/p&gt;

&lt;p&gt;Therefore, an imbalanced classification problem is one in which the dependent variable has imbalanced proportion of classes. In other words, a data set that exhibits an unequal distribution between its classes is considered to be imbalanced. I split the clean dataset into a 70/30 % split by 10-fold cross validation. The training set contained 145 observations in 7 variables. The test set contained 60 observations in 7 variables. The 7 independent variables are, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash year, crash month, crash date, crash minute, aboard, fatalities and crash survivor&lt;/code&gt;.&lt;/p&gt;

&lt;h5 id=&quot;i-methods-to-deal-with-imbalanced-classification&quot;&gt;i.	Methods to deal with imbalanced classification&lt;/h5&gt;

&lt;ol&gt;
  &lt;li&gt;Under Sampling&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With under-sampling, we randomly select a subset of samples from the class with more instances to match the number of samples coming from each class. The main disadvantage of under-sampling is that we lose potentially relevant information from the left-out samples.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Over Sampling&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With oversampling, we randomly duplicate samples from the class with fewer instances or we generate additional instances based on the data that we have, so as to match the number of samples in each class. While we avoid losing information with this approach, we also run the risk of over fitting our model as we are more likely to get the same samples in the training and in the test data, i.e. the test data is no longer independent from training data. This would lead to an overestimation of our model’s performance and generalization.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;ROSE and SMOTE&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Besides over- and under-sampling, there are hybrid methods that combine under-sampling with the generation of additional data. Two of the most popular are ROSE and SMOTE.&lt;/p&gt;

&lt;p&gt;The ideal solution is, we should not simply perform over- or under-sampling on our training data and then run the model. We need to account for cross-validation and perform over or under-sampling on each fold independently to get an honest estimate of model performance.&lt;/p&gt;

&lt;h5 id=&quot;ii-prediction-on-imbalanced-dataset&quot;&gt;ii.	Prediction on imbalanced dataset&lt;/h5&gt;

&lt;p&gt;To test the accuracy of air crash survivors, I applied three classification algorithms namely Classification and Regression Trees (CART), K-Nearest Neighbors (KNN) and Logistic Regression (GLM) to the clean imbalanced dataset. The CART and GLM model give 100% accuracy. See Fig-12.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_12.png&quot; alt=&quot;plot12&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-12: Accuracy plot of predictive models on imbalanced data&lt;/p&gt;

&lt;p&gt;I have shown below the predictive modelling results on imbalanced dataset.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Call:
summary.resamples(object = models)

Models: cart, knn, glm 
Number of resamples: 100 

ROC 
  Min.   1st Qu.Median  Mean   3rd Qu. Max. NA&apos;s
cart 0.4907407 0.7666667 0.8605556 0.8390667 0.933796310
knn  0.3444444 0.6472222 0.7527778 0.7460315 0.845833310
glm  0.9000000 1.0000000 1.0000000 0.9977593 1.000000010

Sens 
  Min. 1st Qu. Median  Mean   3rd Qu. Max. NA&apos;s
cart 0.1666667 0.60.8 0.7310000 0.833333310
knn  0.0000000 0.40.5 0.5406667 0.666666710
glm  0.6000000 1.01.0 0.9723333 1.000000010

Spec 
  Min.   1st Qu.Median  Mean   3rd Qu. Max. NA&apos;s
cart 0.6666667 0.8000000 0.8888889 0.8846667 1.000000010
knn  0.5555556 0.7777778 0.8888889 0.8461111 0.888888910
glm  0.8888889 1.0000000 1.0000000 0.9801111 1.000000010
Confusion Matrix and Statistics

  Reference
Prediction alive dead
 alive220
 dead  0   38
 
   Accuracy : 1  
 95% CI : (0.9404, 1)
No Information Rate : 0.6333 
P-Value [Acc NIR] : 1.253e-12  
 
  Kappa : 1  
 Mcnemar&apos;s Test P-Value : NA 
 
Sensitivity : 1.0000 
Specificity : 1.0000 
 Pos Pred Value : 1.0000 
 Neg Pred Value : 1.0000 
 Prevalence : 0.3667 
 Detection Rate : 0.3667 
   Detection Prevalence : 0.3667 
  Balanced Accuracy : 1.0000 
 
   &apos;Positive&apos; Class : alive   
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;From the result above, its evident the sensitivity of CART and GLM model is maximum.&lt;/p&gt;

&lt;h5 id=&quot;iii-prediction-on-balanced-dataset&quot;&gt;iii.	Prediction on balanced dataset&lt;/h5&gt;

&lt;p&gt;I balanced the dataset by applying under, over sampling method as well as the ROSE method. From the results shown in above, I picked the logistic regression model to train on the balanced data.  As we can see now, the sensitivity for over and under-sampling is maximum when applied the logistic regression algorithm. So I chose, under sampling for testing the model. See Fig-13 and the confusion matrix results are shown below.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/CS_DSI_13.png&quot; alt=&quot;plot13&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-13: Accuracy plot of predictive models on balanced data&lt;/p&gt;

&lt;p&gt;After balancing the data and reapplying a logistic regression algorithm, the accuracy to predict the air crash survivor accuracy reduced to 98%, as shown in confusion matrix below.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Call:
summary.resamples(object = models)

Models: glm_under, glm_over, glm_rose 
Number of resamples: 100 

ROC 
   Min.   1st Qu.Median  Mean   3rd Qu.  Max.
glm_under 0.8240741 1.0000000 1.0000000 0.9920185 1.0000000 1.0000000
glm_over  0.9000000 1.0000000 1.0000000 0.9977593 1.0000000 1.0000000
glm_rose  0.0000000 0.1638889 0.2722222 0.2787333 0.3555556 0.7777778
  NA&apos;s
glm_under0
glm_over 0
glm_rose 0

Sens 
  Min. 1st Qu.Median  Mean 3rd Qu. Max. NA&apos;s
glm_under  0.6 1.0 1.0000000 0.9746667 1.010
glm_over   0.6 1.0 1.0000000 0.9723333 1.010
glm_rose   0.0 0.2 0.3666667 0.3533333 0.510

Spec 
   Min.   1st Qu.Median  Mean   3rd Qu.  Max.
glm_under 0.7777778 1.0000000 1.0000000 0.9745556 1.0000000 1.0000000
glm_over  0.8888889 1.0000000 1.0000000 0.9801111 1.0000000 1.0000000
glm_rose  0.0000000 0.2222222 0.3333333 0.3538889 0.4444444 0.8888889
  NA&apos;s
glm_under0
glm_over 0
glm_rose 0
 Confusion Matrix and Statistics

  Reference
Prediction alive dead
 alive221
 dead  0   37
  
   Accuracy : 0.9833  
 95% CI : (0.9106, 0.9996)
No Information Rate : 0.6333  
P-Value [Acc &amp;gt; NIR] : 4.478e-11   
  
  Kappa : 0.9645  
 Mcnemar&apos;s Test P-Value : 1   
  
Sensitivity : 1.0000  
Specificity : 0.9737  
 Pos Pred Value : 0.9565  
 Neg Pred Value : 1.0000  
 Prevalence : 0.3667  
 Detection Rate : 0.3667  
   Detection Prevalence : 0.3833  
  Balanced Accuracy : 0.9868  
  
   &apos;Positive&apos; Class : alive       
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h5 id=&quot;iv-results-interpretation&quot;&gt;iv.	Results interpretation&lt;/h5&gt;

&lt;p&gt;In answering the second objective of this analysis, it’s been found that the logistic regression model gives 98% accuracy in determining the accuracy of an air crash survival. This explains the need for balancing the dataset before modeling.&lt;/p&gt;

&lt;h4 id=&quot;i-limitations&quot;&gt;I.	Limitations&lt;/h4&gt;

&lt;p&gt;Perhaps, one of the challenges on working on this dataset was the higher number of categorical variables. And each such variable having more than 10 distinct levels. Decomposing them into a smaller number of meaningful levels would require help from a subject matter expert. Besides this, the dataset contained a huge number of missing values in categorical variables. Imputing them would be bottleneck to the primary memory. I replaced the missing values with Zero.&lt;/p&gt;

&lt;h4 id=&quot;j-discussion&quot;&gt;J.	Discussion&lt;/h4&gt;

&lt;p&gt;There can be an argument on the necessity of data balancing. For instance, in this analysis I have shown that imbalanced data give 100% accuracy, in contrast the balanced data accuracy reduces to 98%. The reasoning here is, balanced or imbalanced data is dependent on distribution of data points. By balancing the data, the analyst is absolutely certain about the robustness of the model, which would not be possible with an imbalanced dataset.&lt;/p&gt;

&lt;p&gt;Traveling by air is certainly a safe option in present times. I have proved this claim by conducting a systematic rigorous data analysis. Moreover, the logistic regression model trained on balanced under-sampled data yield the maximum sensitivity.&lt;/p&gt;

&lt;h4 id=&quot;k-conclusion-and-future-work&quot;&gt;K.	Conclusion and Future Work&lt;/h4&gt;

&lt;p&gt;In this study, I have analyzed the last 101 years data on air craft crashes. I have shown in my detailed analysis that given certain factors like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;crash year, crash month, crash date, crash minute, aboard, fatalities and survived&lt;/code&gt;, it’s possible to predict the accuracy of air crash survivors. I have tested several hypothesis in this work, see section C. It would be interesting to see trends between aircraft type and air crash fatalities which I leave as a future work.&lt;/p&gt;

&lt;h4 id=&quot;reference&quot;&gt;Reference&lt;/h4&gt;

&lt;p&gt;Wickham, H. (2014). Tidy data. Journal of Statistical Software, 59(10), 1-23.&lt;/p&gt;

&lt;h4 id=&quot;appendix-a&quot;&gt;Appendix A&lt;/h4&gt;

&lt;h5 id=&quot;explanation-of-statistical-terms-used-in-this-study&quot;&gt;Explanation of statistical terms used in this study&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;Variable: is any characteristic, number or quantity that is measurable. Example, age, sex, income are variables.&lt;/li&gt;
  &lt;li&gt;Continuous variable:  is a numeric or a quantitative variable. Observations can take any value between a set of real numbers. Example, age, time, distance.&lt;/li&gt;
  &lt;li&gt;Categorical variable: describes quality or characteristic of a data unit. Typically it contains text values. They are qualitative variables.&lt;/li&gt;
  &lt;li&gt;Categorical-nominal: is a categorical variable where the observation can take a value that cannot be organized into a logical sequence. Example, religion, product brand.&lt;/li&gt;
  &lt;li&gt;Independent variable: also known as the predictor variable. It is a variable that is being manipulated in an experiment in order to observe an effect on the dependent variable. Generally in an experiment, the independent variable is the “cause”.&lt;/li&gt;
  &lt;li&gt;Dependent variable: also known as the response or outcome variable. It is the variable that is needs to be measured and is affected by the manipulation of independent variables. Generally, in an experiment it is the “effect”.&lt;/li&gt;
  &lt;li&gt;Variance: explains the distribution of data, i.e. how far a set of random numbers are spread out from their original values.&lt;/li&gt;
  &lt;li&gt;Sensitivity: is the ability of a test to correctly identify, the occurrence of a value in the dependent or the response variable. Also known as the true positive rate.&lt;/li&gt;
  &lt;li&gt;Specificity: is the ability of a test to correctly identify, the non-occurrence of a value in the dependent or the response variable. Also known as the true negative rate.&lt;/li&gt;
  &lt;li&gt;Cohen’s Kappa: is a statistic to measure the inter-rate reliability of a categorical variable. It ranges from -1 to +1.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;appendix-b&quot;&gt;Appendix B&lt;/h4&gt;

&lt;p&gt;The R code for this study can be downloaded from &lt;a href=&quot;https://duttashi.github.io/scripts/CaseStudy-aircrash_survival.R&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Employee flight risk modeling behavior]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/employee-flight-risk-prediction-behaviour/" />
  <id>https://duttashi.github.io/blog/employee-flight-risk-prediction-behaviour</id>
  <published>2019-05-29T00:00:00+00:00</published>
  <updated>2019-05-29T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;an-analytical-model-for-predicting-employee-flight-risk-behaviour&quot;&gt;An analytical model for predicting employee flight risk behaviour&lt;/h3&gt;

&lt;p&gt;“People are the nucleus of any organization. So, how can you find, engage and retain top performers who’ll contribute to your goals, your future?”&lt;/p&gt;

&lt;p&gt;There is no dearth of Enterprise Resource Planning (ERP) systems utilized by human resource companies, however, the inclusion of machine learning to such ERP systems can be very useful. This leads one to ask the following question.&lt;/p&gt;

&lt;h5 id=&quot;a-question&quot;&gt;A. Question&lt;/h5&gt;

&lt;p&gt;To develop a predictive model to understand the reasons why employees leave the organization.&lt;/p&gt;

&lt;h5 id=&quot;b-objectives&quot;&gt;B. Objectives&lt;/h5&gt;

&lt;p&gt;This report has two objectives, namely;&lt;/p&gt;

&lt;p&gt;i.	To conduct an exploratory data analysis for determining any possible relationship between the variables&lt;/p&gt;

&lt;p&gt;ii.	To develop a predictive model for identifying the potential employee attrition reasons.&lt;/p&gt;

&lt;h5 id=&quot;c-data-analysis&quot;&gt;C. Data Analysis&lt;/h5&gt;

&lt;p&gt;A systematic data analysis was undertaken to answer the business question and objective.&lt;/p&gt;

&lt;p&gt;i.	&lt;strong&gt;Exploratory Data Analysis (EDA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The training set had &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;13000&lt;/code&gt; observations in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;11&lt;/code&gt; columns. The test set had &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1999&lt;/code&gt; observations in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10&lt;/code&gt; columns. There were zero missing values. I now provide the following observations;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt1.png&quot; alt=&quot;plot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Correlation plot&lt;/p&gt;

&lt;p&gt;a.	I renamed some variables like “sales” was renamed to “role”, “time_spend_company” was renamed to “exp_in_company”.&lt;/p&gt;

&lt;p&gt;b.	The employee attrition rate was 21.41%&lt;/p&gt;

&lt;p&gt;c.	The company had an employee attrition rate of 24%&lt;/p&gt;

&lt;p&gt;d.	The mean satisfaction of employees was 0.61&lt;/p&gt;

&lt;p&gt;e.	From the correlation plot shown in Fig-1, there is a positive (+) correlation between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;projectCount&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;averageMonthlyHours&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;evaluation&lt;/code&gt;. Which could mean that the employees who spent more hours and did more projects were evaluated highly.&lt;/p&gt;

&lt;p&gt;f.	For the negative (-) relationships, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;employee attrition&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;satisfaction&lt;/code&gt; are highly correlated. Probably people tend to leave a company more when they are less satisfied.&lt;/p&gt;

&lt;p&gt;g.	A one-sample t-test was conducted to measure the satisfaction level.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Hypothesis Testing: Is there significant difference in the means of satisfaction level between attrition and the entire employee population?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;1.1.	&lt;em&gt;Null Hypothesis&lt;/em&gt;: (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H0: pEmployeeLeft = pEmployeePop&lt;/code&gt;) The null hypothesis would be that there is no difference in satisfaction level between attrition and the entire employee population.&lt;/p&gt;

&lt;p&gt;1.2.	&lt;em&gt;Alternate Hypothesis&lt;/em&gt;: (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;HA: pEmployeeLeft!= pEmployeePop&lt;/code&gt;) The alternative hypothesis would be that there is a difference in satisfaction level between attrition and the entire employee population.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Findings&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The mean for the employee population is 0.618&lt;/li&gt;
  &lt;li&gt;The mean for attrition is 0.439&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I then conducted a t-test at 95% confidence level to see if it correctly rejects the null hypothesis that the sample comes from the same distribution as the employee population.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Findings&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I rejected the null hypothesis because the t-distribution left and right quartile ranges are -1.960. The T-score lies outside the quantiles and the p-value is lower than the confidence level of 5%.&lt;/li&gt;
  &lt;li&gt;The test result shows the test statistic “t” is equal to 0.36. This test statistic tells us how much the sample mean deviates from the null hypothesis. The alternative hypothesis is True as the mean is not equal to 0.61.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Inference&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From the above findings does not necessarily mean the findings are of practical significance because of two reasons, namely; collect more data or conduct more experiments.&lt;/p&gt;

&lt;p&gt;h.	Now let’s look at some distribution plots using some of the employee features like “Satisfaction”, “Evaluation” and “Average monthly hours”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;: Let’s examine the distribution on some of the employee’s features.&lt;/p&gt;

&lt;p&gt;Here’s what I found:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Satisfaction&lt;/strong&gt; There is a huge spike for employees with low satisfaction and high satisfaction.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluation&lt;/strong&gt; There is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bimodal&lt;/code&gt; distribution of employees for low evaluations (less than 0.6) and high evaluations (more than 0.8)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AverageMonthlyHours&lt;/strong&gt; There is another bimodal distribution of employees with lower and higher average monthly hours (less than 150 hours &amp;amp; more than 250 hours)&lt;/li&gt;
  &lt;li&gt;The evaluation and average monthly hour graphs both share a similar distribution.&lt;/li&gt;
  &lt;li&gt;Employees with lower average monthly hours were evaluated less and vice versa.&lt;/li&gt;
  &lt;li&gt;If you look back at the correlation matrix, the high correlation between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;evaluation&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;averageMonthlyHours&lt;/code&gt; does support this finding.
Note: Employee attrition is coded as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; and no attrition is coded as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;i.	The relationship between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Salary&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Attrition&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Majority of employees who left either had low or medium salary.&lt;/li&gt;
  &lt;li&gt;Barely any employees left with high salary&lt;/li&gt;
  &lt;li&gt;Employees with low to average salaries tend to leave the company.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt2.png&quot; alt=&quot;plot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Salary vs Attrition plot&lt;/p&gt;

&lt;p&gt;j.	The relationship between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Department&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Attrition&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The &lt;strong&gt;sales&lt;/strong&gt;, &lt;strong&gt;technical&lt;/strong&gt;, and &lt;strong&gt;support&lt;/strong&gt; department were the top 3 departments to have employee attrition.&lt;/li&gt;
  &lt;li&gt;The management department had the least count of attrition.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt3.png&quot; alt=&quot;plot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Department vs Attrition plot&lt;/p&gt;

&lt;p&gt;k.	The relationship between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Attrition&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProjectCount&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;More than half of the employees with &lt;strong&gt;2,6, and 7&lt;/strong&gt; projects left the company.&lt;/li&gt;
  &lt;li&gt;Majority of the employees who did not leave the company had &lt;strong&gt;3, 4, and 5&lt;/strong&gt; projects.&lt;/li&gt;
  &lt;li&gt;All of the employees with 7 projects left the company.&lt;/li&gt;
  &lt;li&gt;There is an increase in employee attrition rate as project count increases.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt4.png&quot; alt=&quot;plot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-4: Project count vs Attrition plot&lt;/p&gt;

&lt;p&gt;l.	The relationship between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Attrition&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Evaluation&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There is a bimodal distribution for attrition.&lt;/li&gt;
  &lt;li&gt;Employees with &lt;strong&gt;low&lt;/strong&gt; performance tend to leave the company more.&lt;/li&gt;
  &lt;li&gt;Employees with &lt;strong&gt;high&lt;/strong&gt; performance tend to leave the company more.&lt;/li&gt;
  &lt;li&gt;The &lt;strong&gt;sweet spot&lt;/strong&gt; for employees that stayed is within &lt;strong&gt;0.6-0.8&lt;/strong&gt; evaluation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt5.png&quot; alt=&quot;plot5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Employee evaluation vs Attrition plot&lt;/p&gt;

&lt;p&gt;m.	The relationship between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Attrition&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AverageMonthlyHours&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Another bi-modal distribution for attrition.&lt;/li&gt;
  &lt;li&gt;Employees who had less hours of work &lt;strong&gt;(~150hours or less)&lt;/strong&gt; left the company more.&lt;/li&gt;
  &lt;li&gt;Employees who had too many hours of work &lt;strong&gt;(~250 or more)&lt;/strong&gt; left the company.&lt;/li&gt;
  &lt;li&gt;Employees who left generally were &lt;strong&gt;underworked&lt;/strong&gt; or &lt;strong&gt;overworked&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt6.png&quot; alt=&quot;plot6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-6: Average monthly hour worked vs Attrition plot&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Observations&lt;/strong&gt;: The Fig-7, clearly represents the factors which serve as the top reasons for attrition in a company:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Satisfaction level: it already had a negative correlation with the outcome. People with low satisfaction were most likely to leave even when compared with evaluations.&lt;/li&gt;
  &lt;li&gt;Salary and the role they played has one of the least impact on attrition.&lt;/li&gt;
  &lt;li&gt;Pressure due to the number of projects and how they were evaluated also holds key significance in determining attrition.&lt;/li&gt;
  &lt;li&gt;All features were deemed important.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt7.png&quot; alt=&quot;plot7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Feature importance plot&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data modeling&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Base model rate: recall back to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Part 4.1: Exploring the Data&lt;/code&gt;, 24% of the dataset contained 1’s (employee who left the company) and the remaining 76% contained 0’s (employee who did not leave the company). The Base Rate Model would simply predict every 0’s and ignore all the 1’s. The base rate accuracy for this data set, when classifying everything as 0’s, would be 76% because 76% of the dataset are labeled as 0’s (employees not leaving the company).
The training data was split into 75% train set and 25% validation set. An initial logistic regression model based on all 10 independent variables (or features) was built on the train set. The model was tested on the validation set. An initial predictive accuracy of 78% was obtained.&lt;/p&gt;

&lt;p&gt;Thereafter, I built four models based on the following classifiers, namely:&lt;/p&gt;

&lt;p&gt;a.	Classification And Regression Trees (CART),&lt;/p&gt;

&lt;p&gt;b.	Support Vector Machine (SVM),&lt;/p&gt;

&lt;p&gt;c.	k-nearest neighbor (knn) and&lt;/p&gt;

&lt;p&gt;d.	logistic regression&lt;/p&gt;

&lt;p&gt;The CART, SVM and the KNN model gave an accuracy of over 98% on the training set. I chose the CART and the SVM model for testing. Both models yield an accuracy of 95.5% on the validation set, as shown in Fig-8.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-hr-attrition-plt8.png&quot; alt=&quot;plot8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-8: Predictive modeling results&lt;/p&gt;

&lt;p&gt;From Fig-8, I chose the cart model as the final model. Thereafter, I tested this model on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hr_attrition_test data&lt;/code&gt;. Finally to conclude using the cart modeling technique, we can predict the employee attrition at an accuracy of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;95.5%&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Employees generally left when they are &lt;strong&gt;underworked&lt;/strong&gt; (less than 150hr/month or 6hr/day)&lt;/li&gt;
  &lt;li&gt;Employees generally left when they are &lt;strong&gt;overworked&lt;/strong&gt; (more than 250hr/month or 10hr/day)&lt;/li&gt;
  &lt;li&gt;Employees with either &lt;strong&gt;really high or low evaluations&lt;/strong&gt; should be taken into consideration for high attrition rate&lt;/li&gt;
  &lt;li&gt;Employees with &lt;strong&gt;low to medium salaries&lt;/strong&gt; are the bulk of employee attrition&lt;/li&gt;
  &lt;li&gt;Employees that had &lt;strong&gt;2,6, or 7 project count&lt;/strong&gt; was at risk of leaving the company&lt;/li&gt;
  &lt;li&gt;Employee &lt;strong&gt;satisfaction&lt;/strong&gt; is the highest indicator for employee attrition.&lt;/li&gt;
  &lt;li&gt;Employee that had &lt;strong&gt;4 and 5 years at the company&lt;/strong&gt; should be taken into consideration for high attrition rate&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code and Dataset&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;R code - &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/scripts/Full%20Case%20Studies/CaseStudy-hr_attrition-EDA.R&quot;&gt;Exploratory Data Analysis&lt;/a&gt;, &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/scripts/Full%20Case%20Studies/CaseStudy-hr_attrition-Predictive_Modelling.R&quot;&gt;Predictive Modeling&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Data - &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/data/hr_attrition_train.csv&quot;&gt;train data&lt;/a&gt;, &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/data/hr_attrition_test.csv&quot;&gt;test data&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Scraping twitter data to visualize trending tweets in Kuala Lumpur]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/scraping-twitter-data-to-analyse-trends-in-KL/" />
  <id>https://duttashi.github.io/blog/scraping-twitter-data-to-analyse-trends-in-KL</id>
  <published>2018-10-01T00:00:00+00:00</published>
  <updated>2018-10-01T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;&lt;em&gt;(Disclaimer: I’ve no grudge against python programming language per se. I think its equally great. In the following post, I’m merely recounting my experience.)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;It’s been quite a while since I last posted. The reasons are numerous, notable being, unable to decide which programming language to choose for web data scraping. The contenders were data analytic maestro, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;R&lt;/code&gt; and data scraping guru, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;python&lt;/code&gt;. So, I decided to give myself some time to figure out which language will be best for my use case. My use case was, &lt;em&gt;Given some search keywords, scrape twitter for related posts and visualize the result&lt;/em&gt;. First, I needed the &lt;em&gt;live data&lt;/em&gt;. Again, I was at the cross-roads, “R or Python”. Apparently python has some great packages for twitter data streaming like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;twython&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;python-twitter&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tweepy&lt;/code&gt; and &lt;a href=&quot;https://github.com/twintproject/twint&quot;&gt;twint&lt;/a&gt; (&lt;em&gt;Acknowledgment: The library twint was suggested by a reader. See comments section&lt;/em&gt;). Equivalent R libraries are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;twitteR&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rwteet&lt;/code&gt;. I chose the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rtweet&lt;/code&gt; package for data collection over python for following reasons;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I do not have to create a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;credential file&lt;/code&gt; (unlike in python) to log in to my twitter account. However, you do need to authenticate the twitter account when using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rtweet&lt;/code&gt; package. This authentication is done just once if using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rtweet&lt;/code&gt; package. Your twitter credentials will be stored locally.&lt;/li&gt;
  &lt;li&gt;Coding and code readability is far more easier as compared to python.&lt;/li&gt;
  &lt;li&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rtweet&lt;/code&gt; package allows for multiple hash tags to be searched for.&lt;/li&gt;
  &lt;li&gt;To localize the data, the package also allows for specifying geographic coordinates.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, using the following code snippet, I was able to scrape data. The code has following parts;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;A custom search for tweets function which will accept the search string. If search string is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NULL&lt;/code&gt;, it will throw a message and stop, else it will search for hash tags specified in search string and return a data frame as output.&lt;/p&gt;

    &lt;p&gt;library(rtweet)
 library(tidytext)
 library(tidyverse)
 library(stringr)
 library(stopwords)
 library(rtweet) # for search_tweets()&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;A data frame containing the search terms. Note, here my search hash-tags are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;KTM&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MRT&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monorail&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Create a function that will accept multiple hashtags and will search the twitter api for related tweets&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;search_tweets_queries &amp;lt;- function(x, n = 100, ...) {
  ## check inputs
  stopifnot(is.atomic(x), is.numeric(n))
  if (length(x) == 0L) {
    stop(&quot;No query found&quot;, call. = FALSE)
  }  
  ## search for each string in column of queries
  rt &amp;lt;- lapply(x, search_tweets, n = n, ...)
  ## add query variable to data frames
  rt &amp;lt;- Map(cbind, rt, query = x, stringsAsFactors = FALSE)
  ## merge users data into one data frame
  rt_users &amp;lt;- do.call(&quot;rbind&quot;, lapply(rt, users_data))
  ## merge tweets data into one data frame
  rt &amp;lt;- do.call(&quot;rbind&quot;, rt)
  ## set users attribute
  attr(rt, &quot;users&quot;) &amp;lt;- rt_users
  ## return tibble (validate = FALSE makes it a bit faster)
  tibble::as_tibble(rt, validate = FALSE)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;search_tweets_queries&lt;/code&gt; defined in step 1, to search for tweets. Note, the usage of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;retryonratelimit=TRUE&lt;/code&gt; indicates if search rate limit reached, then the crawler will sleep for a while and start again. Refer to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rtweet&lt;/code&gt; &lt;a href=&quot;https://rtweet.info/&quot;&gt;documentation&lt;/a&gt; for more information.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; df_query &amp;lt;- data.frame(query = c(&quot;KTM&quot;, &quot;monorail&quot;,&quot;MRT&quot;),
   	  n = rnorm(3), # change this number according to the number of searchwords in parameter query. As of now, the parameter got 3 keywords, therefore this nuber is set to 3.
   stringsAsFactors = FALSE  )

 df_collect_tweets &amp;lt;- search_tweets_queries(df_query$query, include_rts = FALSE,retryonratelimit = TRUE, 
 #geocode for Kuala Lumpur
 geocode = &quot;3.14032,101.69466,93.5mi&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Once the data is collected, I’ll keep some selected columns only.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; df_select_tweets&amp;lt;- df_collect_tweets %&amp;gt;%
   select(c(user_id,created_at,screen_name, !is.na(hashtags),text,
    source,display_text_width&amp;gt;0,lang,!is.na(place_name),
    !is.na(place_full_name),
    !is.na(geo_coords), !is.na(country), !is.na(location),
    retweet_count,account_created_at, account_lang, query)
  )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Text mining&lt;/strong&gt;: The collected data need to be cleaned. Therefore, I’ve used the basic &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gsub()&lt;/code&gt; function and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str_replace_all()&lt;/code&gt; from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stringr&lt;/code&gt; library.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; # Saving the selected columns data
 &amp;gt; df_select_tweets_1 = data.frame(lapply(df_select_tweets, as.character), stringsAsFactors=FALSE)
 ### Text preprocessing
    
 # 1. Remove URL from text
 # collapse to long format
 &amp;gt; clean_tweet&amp;lt;- df_select_tweets_1
    
 #clean_tweet&amp;lt;- paste(df_select_tweets_1, collapse=&quot; &quot;)
 &amp;gt; clean_tweet$text = gsub(&quot;&amp;amp;amp&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;(RT|via)((?:\\b\\W*@\\w+)+)&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;@\\w+&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;[[:punct:]]&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;[[:digit:]]&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;http\\w+&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;[ \t]{2,}&quot;, &quot;&quot;, clean_tweet$text)
 &amp;gt; clean_tweet$text = gsub(&quot;^\\s+|\\s+$&quot;, &quot;&quot;, clean_tweet$text)

 #get rid of unnecessary spaces
 &amp;gt; clean_tweet$text &amp;lt;- str_replace_all(clean_tweet$text,&quot; &quot;,&quot; &quot;)
 # Get rid of URLs
 &amp;gt; clean_tweet$text&amp;lt;- str_replace_all(clean_tweet$text, &quot;https://t.co/[a-z,A-Z,0-9]*&quot;,&quot;&quot;)
 &amp;gt; clean_tweet$text&amp;lt;- str_replace_all(clean_tweet$text, &quot;http://t.co/[a-z,A-Z,0-9]*&quot;,&quot;&quot;)
 # Take out retweet header, there is only one
 &amp;gt; clean_tweet$text &amp;lt;- str_replace(clean_tweet$text,&quot;RT @[a-z,A-Z]*: &quot;,&quot;&quot;)
 # Get rid of hashtags
 &amp;gt; clean_tweet$text &amp;lt;- str_replace_all(clean_tweet$text,&quot;#[a-z,A-Z]*&quot;,&quot;&quot;)
 # Get rid of references to other screennames
 &amp;gt; clean_tweet$text &amp;lt;- str_replace_all(clean_tweet$text,&quot;@[a-z,A-Z]*&quot;,&quot;&quot;) 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;

    &lt;p&gt;a. Next, I’ll use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tidytext&lt;/code&gt; library for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;token&lt;/code&gt; extraction&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; # Unnest the tokens
 &amp;gt; df.clean&amp;lt;- clean_tweet %&amp;gt;%
   unnest_tokens(word, text)
    
 &amp;gt; clean_tweets&amp;lt;- tibble()
 &amp;gt; clean_tweets&amp;lt;- rbind(clean_tweets, df.clean)
    
 # Basic calculations
 # calculate word frequency
 &amp;gt; word_freq &amp;lt;- clean_tweets %&amp;gt;%
   count(word, sort=TRUE)
 &amp;gt; word_freq 

 # A tibble: 5,291 x 2
    wordn
    &amp;lt;chr&amp;gt;   &amp;lt;int&amp;gt;
  1 mrt   596
  2 ktm   582
  3 ke455
  4 kl259
  5 ni251
  6 naik  221
  7 the   214
  8 at208
  9 sentral   195
 10 nak   193
 # ... with 5,281 more rows
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;

    &lt;p&gt;b. It should be noted, the national language of Malaysia is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Bahasa Melayu (BM)&lt;/code&gt;. To remove the stop words in BM, I’ve used the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stopwords&lt;/code&gt; library. lots of stop words like the, and, to, a etc. Let’s remove the stop words. We can remove the stop words from our tibble with anti_join and the built-in stop_words data set provided by tidytext.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &amp;gt; clean_tweets %&amp;gt;%
   # remove the stopwords in Bahasa Melayu (BM). Use `ms` for BM. See this reference for other language codes: https://en.wikipedia.org/wiki/ISO_639-1
   anti_join(get_stopwords(language=&quot;ms&quot;, source=&quot;stopwords-iso&quot;)) %&amp;gt;%
   # remove the stopwords in english
   anti_join(get_stopwords(language=&quot;en&quot;, source=&quot;stopwords-iso&quot;)) %&amp;gt;%
   count(word, sort=TRUE) %&amp;gt;%
   top_n(10) %&amp;gt;%
   ggplot(aes(word,n, fill=word))+
   geom_bar(stat = &quot;identity&quot;)+
   xlab(NULL)+
   ylab(paste(&apos;Word count&apos;))+
   ggtitle(paste(&apos;Most common words in tweets&apos;)) +
   theme(legend.position=&quot;none&quot;) +
   theme_minimal()+
   coord_flip()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Finally, I present a basic bar plot to show the trending words.&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://i.imgur.com/TpBec4E.png&quot; alt=&quot;kl_tweets&quot; /&gt;
 Barplot: Trending twitter words in kuala lumpur, malaysia&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;areas-of-further-improvement&quot;&gt;Area’s of further improvement&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;How to extract tweets within a given time range?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See the code on my &lt;a href=&quot;https://github.com/duttashi/scrapers/blob/master/src/R/twitter_data_scraping_00.R&quot;&gt;Github account&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[To eat or not to eat! That's the question? Measuring the association between categorical variables]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/to-eat-or-not-to-eat/" />
  <id>https://duttashi.github.io/blog/to-eat-or-not-to-eat</id>
  <published>2017-06-03T00:00:00+00:00</published>
  <updated>2017-06-03T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h3&gt;

&lt;p&gt;I serve as a reviewer to several ISI and Scopus indexed journals in Information Technology. Recently, I was reviewing an article, wherein the researchers had made a critical mistake in data analysis. They converted the original &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;categorical&lt;/code&gt; data to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;continuous&lt;/code&gt; without providing a rigorous statistical treatment, nor, any justification to the loss of information if any. Thus, my motivation to develop this study, is borne out of their error.&lt;/p&gt;

&lt;p&gt;We know the standard association measure between continuous variables is the product-moment correlation coefficient introduced by Karl Pearson. This measure determines the degree of linear association between continuous variables and is both normalized to lie between -1 and +1 and symmetric: the correlation between variables x and y is the same as that between y and x. &lt;em&gt;the best-known association measure between two categorical variables is probably the chi-square measure, also introduced by Karl Pearson. Like the product-moment correlation coefficient, this association measure is symmetric, but it is not normalized. This lack of normalization provides one motivation for Cramer’s V, defined as the square root of a normalized chi-square value; the resulting association measure varies between 0 and 1 and is conveniently available via the assocstats function in the vcd package. An interesting alternative to Cramer’s V is Goodman and Kruskal’s tau, which is not nearly as well known and is asymmetric. This asymmetry arises because the tau measure is based on the fraction of variability in the categorical variable y that can be explained by the categorical variable x.&lt;/em&gt; &lt;a href=&quot;https://cran.r-project.org/web/packages/GoodmanKruskal/vignettes/GoodmanKruskal.html&quot;&gt;1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The data for this study is sourced from UCI Machine Learning &lt;a href=&quot;http://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data&quot;&gt;repository&lt;/a&gt;. As it states in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;data information&lt;/code&gt; section, “This data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family (pp. 500-525). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. This latter class was combined with the poisonous one. The guide clearly states that there is no simple rule for determining the edibility of a mushroom;&lt;/p&gt;

&lt;p&gt;Furthermore, the possible research questions, I want to explore are;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Is significance test enough to justify a hypothesis?&lt;/li&gt;
  &lt;li&gt;How to measure associations between categorical predictors?&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;2-making-data-management-decisions&quot;&gt;2. Making data management decisions&lt;/h4&gt;
&lt;p&gt;As a first step, I imported the data in R environment as;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Import data from UCI ML repo
&amp;gt; theURL&amp;lt;- &quot;http://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data&quot;
# Explicitly adding the column headers from the data dictionary
&amp;gt; mushroom.data&amp;lt;- read.csv(file = theURL, header = FALSE, sep = &quot;,&quot;,strip.white = TRUE,
                     stringsAsFactors = TRUE, 
                     col.names = c(&quot;class&quot;,&quot;cap-shape&quot;,&quot;cap-surface&quot;,&quot;cap-color&quot;,&quot;bruises&quot;,
                                   &quot;odor&quot;,&quot;gill-attachment&quot;,&quot;gill-spacing&quot;,&quot;gill-size&quot;,
                                   &quot;gill-color&quot;,&quot;stalk-shape&quot;,&quot;stalk-root&quot;,&quot;stalk-surface-above-ring&quot;,
                                   &quot;stalk-surface-below-ring&quot;,&quot;stalk-color-above-ring&quot;,&quot;stalk-color-below-ring&quot;,
                                   &quot;veil-type&quot;,&quot;veil-color&quot;,&quot;ring-number&quot;,&quot;ring-type&quot;,&quot;spore-print-color&quot;,
                                   &quot;population&quot;,&quot;habitat&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next, I quickly summarize the dataset to get a brief glimpse. The reader’s should note that the data has no missing values. (&lt;em&gt;Thanks to Junhewk Kim for pointing out the earlier error in data levels&lt;/em&gt;)&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Calculate number of levels for each variable
&amp;gt; mushroom.data.levels&amp;lt;-cbind.data.frame(Variable=names(mushroom.data), Total_Levels=sapply(mushroom.data,function(x){as.numeric(length(levels(x)))}))
&amp;gt; print(mushroom.data.levels)
                                     Variable Total_Levels
class                                       class            2
cap.shape                               cap.shape            6
cap.surface                           cap.surface            4
cap.color                               cap.color           10
bruises                                   bruises            2
odor                                         odor            9
gill.attachment                   gill.attachment            2
gill.spacing                         gill.spacing            2
gill.size                               gill.size            2
gill.color                             gill.color           12
stalk.shape                           stalk.shape            2
stalk.root                             stalk.root            5
stalk.surface.above.ring stalk.surface.above.ring            4
stalk.surface.below.ring stalk.surface.below.ring            4
stalk.color.above.ring     stalk.color.above.ring            9
stalk.color.below.ring     stalk.color.below.ring            9
veil.type                               veil.type            1
veil.color                             veil.color            4
ring.number                           ring.number            3
ring.type                               ring.type            5
spore.print.color               spore.print.color            9
population                             population            6
habitat                                   habitat            7
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As we can see, the variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gill.attachement&lt;/code&gt; has two levels (&lt;em&gt;Thanks to Prof. Antony Unwin for pointing out the earlier error in gill.attachment&lt;/em&gt;). The variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;veil.type&lt;/code&gt; has one level.&lt;/p&gt;

&lt;p&gt;The different levels are uninterpretable in their current format. I will use the data dictionary and recode the levels into meaningful names.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; levels(mushroom.data$class)&amp;lt;- c(&quot;edible&quot;,&quot;poisonous&quot;)
&amp;gt; levels(mushroom.data$cap.shape)&amp;lt;-c(&quot;bell&quot;,&quot;conical&quot;,&quot;flat&quot;,&quot;knobbed&quot;,&quot;sunken&quot;,&quot;convex&quot;) 
&amp;gt; levels(mushroom.data$cap.surface)&amp;lt;- c(&quot;fibrous&quot;,&quot;grooves&quot;,&quot;smooth&quot;,&quot;scaly&quot;)
&amp;gt; levels(mushroom.data$cap.color)&amp;lt;- c(&quot;buff&quot;,&quot;cinnamon&quot;,&quot;red&quot;,&quot;gray&quot;,&quot;brown&quot;,&quot;pink&quot;,&quot;green&quot;,&quot;purple&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$bruises)&amp;lt;- c(&quot;bruisesno&quot;,&quot;bruisesyes&quot;)
&amp;gt; levels(mushroom.data$odor)&amp;lt;-c(&quot;almond&quot;,&quot;creosote&quot;,&quot;foul&quot;,&quot;anise&quot;,&quot;musty&quot;,&quot;nosmell&quot;,&quot;pungent&quot;,&quot;spicy&quot;,&quot;fishy&quot;)
&amp;gt; levels(mushroom.data$gill.attachment)&amp;lt;- c(&quot;attached&quot;,&quot;free&quot;)
&amp;gt; levels(mushroom.data$gill.spacing)&amp;lt;- c(&quot;close&quot;,&quot;crowded&quot;)
&amp;gt; levels(mushroom.data$gill.size)&amp;lt;-c(&quot;broad&quot;,&quot;narrow&quot;)
&amp;gt; levels(mushroom.data$gill.color)&amp;lt;- c(&quot;buff&quot;,&quot;red&quot;,&quot;gray&quot;,&quot;chocolate&quot;,&quot;black&quot;,&quot;brown&quot;,&quot;orange&quot;,&quot;pink&quot;,&quot;green&quot;,&quot;purple&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$stalk.shape)&amp;lt;- c(&quot;enlarging&quot;,&quot;tapering&quot;)
&amp;gt; table(mushroom.data$stalk.root) # has a missing level coded as ?
   	?    b    c    e    r 
2480 3776  556 1120  192 
&amp;gt; levels(mushroom.data$stalk.root)&amp;lt;- c(&quot;missing&quot;,&quot;bulbous&quot;,&quot;club&quot;,&quot;equal&quot;,&quot;rooted&quot;)
&amp;gt; levels(mushroom.data$stalk.surface.above.ring)&amp;lt;-c(&quot;fibrous&quot;,&quot;silky&quot;,&quot;smooth&quot;,&quot;scaly&quot;)
&amp;gt; levels(mushroom.data$stalk.surface.below.ring)&amp;lt;-c(&quot;fibrous&quot;,&quot;silky&quot;,&quot;smooth&quot;,&quot;scaly&quot;)
&amp;gt; levels(mushroom.data$stalk.color.above.ring)&amp;lt;- c(&quot;buff&quot;,&quot;cinnamon&quot;,&quot;red&quot;,&quot;gray&quot;,&quot;brown&quot;,                &quot;orange&quot;,&quot;pink&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$stalk.color.below.ring)&amp;lt;- c(&quot;buff&quot;,&quot;cinnamon&quot;,&quot;red&quot;,&quot;gray&quot;,&quot;brown&quot;,      &quot;orange&quot;,&quot;pink&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$veil.type)&amp;lt;-c(&quot;partial&quot;)
&amp;gt; levels(mushroom.data$veil.color)&amp;lt;- c(&quot;brown&quot;,&quot;orange&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$ring.number)&amp;lt;-c(&quot;none&quot;,&quot;one&quot;,&quot;two&quot;)
&amp;gt; levels(mushroom.data$ring.type)&amp;lt;- c(&quot;evanescent&quot;,&quot;flaring&quot;,&quot;large&quot;,&quot;none&quot;,&quot;pendant&quot;)
&amp;gt; levels(mushroom.data$spore.print.color)&amp;lt;- c(&quot;buff&quot;,&quot;chocolate&quot;,&quot;black&quot;,&quot;brown&quot;,&quot;orange&quot;,&quot;green&quot;,&quot;purple&quot;,&quot;white&quot;,&quot;yellow&quot;)
&amp;gt; levels(mushroom.data$population)&amp;lt;- c(&quot;abundant&quot;,&quot;clustered&quot;,&quot;numerous&quot;,&quot;scattered&quot;,&quot;several&quot;,&quot;solitary&quot;)
&amp;gt; levels(mushroom.data$habitat)&amp;lt;-c(&quot;woods&quot;,&quot;grasses&quot;,&quot;leaves&quot;,&quot;meadows&quot;,&quot;paths&quot;,&quot;urban&quot;,&quot;waste&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;3-initial-data-visualization&quot;&gt;3. Initial data visualization&lt;/h4&gt;

&lt;p&gt;Since, we are dealing with categorical data, plotting it is slightly different. Here we use bar charts/plots or mosaic plots rather than dot plots or scatter plots. (&lt;em&gt;Thanks to Prof. Antony Unwin for pointing it out&lt;/em&gt;). The dot plot is useful for plotting continuous variables. It can be used, to plot categorical variables, but then such a visualization will be confusing.&lt;/p&gt;

&lt;h5 id=&quot;a-univariate-data-visualization-stacked-bar-plot&quot;&gt;a. Univariate data visualization (Stacked Bar plot)&lt;/h5&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p&amp;lt;- ggplot(data = mushroom.data)
&amp;gt; p+geom_bar(mapping = aes(x = cap.shape, fill=class), position = position_dodge())+ theme(legend.position = &quot;top&quot;)
&amp;gt; table(mushroom.data$cap.shape, mushroom.data$class)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_mushrooms_plot1.png&quot; alt=&quot;plot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Mushroom cap-shape and class&lt;/p&gt;

&lt;p&gt;From Fig-1, we can easily notice, the mushrooms with a, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flat&lt;/code&gt; cap-shape are mostly edible (&lt;em&gt;n=1596&lt;/em&gt;) and an equally similar number are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;poisonous&lt;/code&gt; (&lt;em&gt;n=1556&lt;/em&gt;). A majority of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bell&lt;/code&gt;shaped mushrooms (&lt;em&gt;n=404&lt;/em&gt;) are &lt;em&gt;edible&lt;/em&gt;. All &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conical&lt;/code&gt; cap-shaped mushrooms are poisonous (&lt;em&gt;n=4&lt;/em&gt;). And, all &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sunken&lt;/code&gt; cap-shaped mushrooms are edible (&lt;em&gt;n=32&lt;/em&gt;).&lt;/p&gt;

&lt;h5 id=&quot;b-how-is-habitat-related-to-class-mosaic-plot&quot;&gt;b. How is habitat related to class? (Mosaic Plot)&lt;/h5&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(vcd) # for mosaicplot()
&amp;gt; table(mushroom.data$habitat, mushroom.data$class) # creates a contingency table
    
          edible poisonous
  	woods     1880      1268
  	grasses   1408       740
  	leaves     240       592
  	meadows    256        36
  	paths      136      1008
  	urban       96       272
  	waste      192         0
&amp;gt; mosaicplot(~ habitat+class, data = mushroom.data,cex.axis = 0.9, shade = TRUE, 
       main=&quot;Bivariate data visualization&quot;,
       sub = &quot;Relationship between mushroom habitat and class&quot;,
       las=2, off=10,border=&quot;chocolate&quot;,xlab=&quot;habitat&quot;, ylab=&quot;class&quot; )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_mushrooms_plot2.png&quot; alt=&quot;plot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Mushroom habitat and class&lt;/p&gt;

&lt;p&gt;From Fig-2, we see a majority of mushrooms that live in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;woods&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grasses&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;leaves&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;meadows&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;paths&lt;/code&gt; are edible. Surprisingly, the one’s living in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;waste&lt;/code&gt; areas are entirely edible.&lt;/p&gt;

&lt;h5 id=&quot;c-how-is-population-related-with-class&quot;&gt;c. How is population related with class?&lt;/h5&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; table(mushroom.data$population, mushroom.data$class)
       
        edible poisonous
  abundant     384         0
  clustered    288        52
  numerous     400         0
  scattered    880       368
  several     1192      2848
  solitary    1064       648

&amp;gt; mosaicplot(~ population+class, data = mushroom.data,
       cex.axis = 0.9, shade = TRUE, 
       main=&quot;Bivariate data visualization&quot;,
       sub = &quot;Relationship between mushroom population and class&quot;,
       las=2, off=10,border=&quot;chocolate&quot;,xlab=&quot;population&quot;, ylab=&quot;class&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_mushrooms_plot3.png&quot; alt=&quot;plot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Mushroom population and class&lt;/p&gt;

&lt;p&gt;From Fig-3, we can see a majority of mushroom population that is either, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clustered&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scattered&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;several&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;solitary&lt;/code&gt; are edible. The mushrooms that are either &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;abundant&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;numerous&lt;/code&gt; in population are completely edible.&lt;/p&gt;

&lt;p&gt;Although, there could be many other pretty visualizations but I will leave that as a future work.&lt;/p&gt;

&lt;p&gt;I will now focus on exploratory data analysis.&lt;/p&gt;

&lt;h4 id=&quot;4-exploratory-data-analysis&quot;&gt;4. Exploratory data analysis&lt;/h4&gt;

&lt;h5 id=&quot;a-correlation-detection--treatment-for-categorical-predictors&quot;&gt;a. Correlation detection &amp;amp; treatment for categorical predictors&lt;/h5&gt;

&lt;p&gt;If we look at the structure of the dataset, we notice that each variable has several factor levels. Moreover, these levels are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unordered&lt;/code&gt;. Such unordered categorical  variables are termed as &lt;strong&gt;nominal variables&lt;/strong&gt;. The opposite of unordered is ordered, we all know that. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ordered&lt;/code&gt; categorical variables are called, &lt;strong&gt;ordinal variables&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;“In the measurement hierarchy, interval variables are highest, ordinal variables are next, and nominal variables are lowest. Statistical methods for variables of one type can also be used with variables at higher levels but not at lower levels.”, see the book, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Categorical Data Analysis&lt;/code&gt; by &lt;a href=&quot;https://www.wiley.com/en-us/Categorical+Data+Analysis%2C+3rd+Edition-p-9780470463635&quot;&gt;Alan Agresti&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I found this &lt;a href=&quot;https://stats.idre.ucla.edu/other/mult-pkg/whatstat/&quot;&gt;cheat-sheet&lt;/a&gt; that can aid in determining the right kind of test to perform on categorical predictors (independent/explanatory variables). Also, this &lt;a href=&quot;https://stats.stackexchange.com/questions/108007/correlations-with-categorical-variables&quot;&gt;SO post&lt;/a&gt; is very helpful. See the answer by user &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gung&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For categorical variables, the concept of correlation can be understood in terms of &lt;strong&gt;significance test&lt;/strong&gt; and &lt;strong&gt;effect size (strength of association)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Pearson’s chi-squared test of independence&lt;/strong&gt; is one of the most basic and common hypothesis tests in the statistical analysis of categorical data. It is a &lt;strong&gt;significance test&lt;/strong&gt;.  Given two categorical random variables, X and Y, the chi-squared test of independence determines whether or not there exists a statistical dependence between them.  Formally, it is a hypothesis test. The chi-squared test assumes a null hypothesis and an alternate hypothesis. The general practice is, if the p-value that comes out in the result is less than a pre-determined significance level, which is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt; usually, then we reject the null hypothesis.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;H0: The The two variables are independent&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;H1: The The two variables are dependent&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The null hypothesis of the chi-squared test is that the two variables are independent and the alternate hypothesis is that they are related.&lt;/p&gt;

&lt;p&gt;To establish that two categorical variables (or predictors) are dependent, the chi-squared statistic must have a certain cutoff. This cutoff increases as the number of classes within the variable (or predictor) increases.&lt;/p&gt;

&lt;p&gt;In section 3a, 3b and 3c, I detected possible indications of dependency between variables by visualizing the predictors of interest. In this section, I will test to prove how well those dependencies are associated. First, I will apply the chi-squared test of independence to measure if the dependency is significant or not. Thereafter, I will apply the &lt;strong&gt;Goodman’s Kruskal Tau&lt;/strong&gt; test to check for &lt;strong&gt;effect size (strength of association)&lt;/strong&gt;.&lt;/p&gt;

&lt;h6 id=&quot;i-pearsons-chi-squared-test-of-independence-significance-test&quot;&gt;i. Pearson’s chi-squared test of independence (significance test)&lt;/h6&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; chisq.test(mushroom.data$cap.shape, mushroom.data$cap.surface, correct = FALSE)

Pearson&apos;s Chi-squared test

data:  mushroom.data$cap.shape and mushroom.data$cap.surface
X-squared = 1011.5, df = 15, p-value &amp;lt; 2.2e-16
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;since the p-value is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 2.2e-16&lt;/code&gt; is less than the cut-off value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt;, we can reject the null hypothesis in favor of alternative hypothesis and conclude, that the variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cap.shape&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cap.surface&lt;/code&gt; are dependent to each other.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; chisq.test(mushroom.data$habitat, mushroom.data$odor, correct = FALSE)

Pearson&apos;s Chi-squared test

data:  mushroom.data$habitat and mushroom.data$odor
X-squared = 6675.1, df = 48, p-value &amp;lt; 2.2e-16    
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Similarly, the variables &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;habitat&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;odor&lt;/code&gt; are dependent to each other as the p-value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 2.2e-16&lt;/code&gt; is less than the cut-off value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt;.&lt;/p&gt;

&lt;h6 id=&quot;ii-effect-size-strength-of-association&quot;&gt;ii. Effect size (strength of association)&lt;/h6&gt;

&lt;p&gt;The measure of association does not indicate causality, but association–that is, whether a variable is associated with another variable. This measure of association also indicates the strength of the relationship, whether, weak or strong.&lt;/p&gt;

&lt;p&gt;Since, I’m dealing with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nominal&lt;/code&gt; categorical predictor’s, the &lt;strong&gt;Goodman and Kruskal’s tau&lt;/strong&gt; measure is appropriate. Interested readers are invited to see pages 68 and 69 of the &lt;a href=&quot;https://mathdept.iut.ac.ir/sites/mathdept.iut.ac.ir/files/AGRESTI.PDF&quot;&gt;Agresti book&lt;/a&gt;. More information on this test can be seen &lt;a href=&quot;https://cran.r-project.org/web/packages/GoodmanKruskal/vignettes/GoodmanKruskal.html&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(GoodmanKruskal)
&amp;gt; varset1&amp;lt;- c(&quot;cap.shape&quot;,&quot;cap.surface&quot;,&quot;habitat&quot;,&quot;odor&quot;,&quot;class&quot;)
&amp;gt; mushroomFrame1&amp;lt;- subset(mushroom.data, select = varset1)
&amp;gt; GKmatrix1&amp;lt;- GKtauDataframe(mushroomFrame1)
&amp;gt; plot(GKmatrix1, corrColors = &quot;blue&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy_mushrooms_plot4.png&quot; alt=&quot;plot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In Fig-4, I have shown the association plot. This plot is based on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;corrplot&lt;/code&gt; library. In this plot the diagonal element &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K&lt;/code&gt; refers to number of unique levels for each variable. The off-diagonal elements contain the forward and backward tau measures for each variable pair. Specifically, the numerical values appearing in each row represent the association measure τ(x,y)τ(x,y) from the variable xx indicated in the row name to the variable yy indicated in the column name.&lt;/p&gt;

&lt;p&gt;The most obvious feature from this plot is the fact that the variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;odor&lt;/code&gt; is almost perfectly predictable (i.e. τ(x,y)=0.94) from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class&lt;/code&gt; and this forward association is quite strong. The forward association suggest that &lt;em&gt;x=&lt;/em&gt;&lt;strong&gt;odor&lt;/strong&gt; (which has levels “almond”, “creosote”, “foul”, “anise”, “musty”, “nosmell”, “pungent”, “spicy”, “fishy”) is highly predictive of &lt;em&gt;y=&lt;/em&gt;&lt;strong&gt;class&lt;/strong&gt; (which has levels “edible”, “poisonous”). This association between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;odor&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class&lt;/code&gt; is strong and indicates that if we know a mushroom’s odor than we can easily predict its class being edible or poisonous.&lt;/p&gt;

&lt;p&gt;On the contrary, the reverse association  &lt;em&gt;y=&lt;/em&gt;&lt;strong&gt;class&lt;/strong&gt; and &lt;em&gt;x=&lt;/em&gt;&lt;strong&gt;odor&lt;/strong&gt;(i.e. τ(y,x)=0.34; is a strong association and indicates that if we know the mushroom’s class being edible or poisonous than its easy to predict its odor.&lt;/p&gt;

&lt;p&gt;Earlier we have found &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cap.shape&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cap.surface&lt;/code&gt; are dependent to each other (chi-squared significance test). Now, let’s see if the association is strong too or not. Again, from Fig-4, both the forward and reverse association suggest that &lt;em&gt;x=&lt;/em&gt;&lt;strong&gt;cap shape&lt;/strong&gt; is weakly associated to &lt;em&gt;y=&lt;/em&gt;&lt;strong&gt;cap surface&lt;/strong&gt; (i.e.τ(x,y)=0.03) and (i.e.τ(y,x)=0.01). Thus, we can safely say that although these two variables are significant but they are association is weak; i.e. it will be difficult to predict one from another.&lt;/p&gt;

&lt;p&gt;Similarly, many more associations can be interpreted from plot-4. I invite interested reader’s to explore it further.&lt;/p&gt;

&lt;h4 id=&quot;5-conclusion&quot;&gt;5. Conclusion&lt;/h4&gt;

&lt;p&gt;The primary objective of this study was to drive the message, &lt;em&gt;do not tamper the data without providing a credible justification&lt;/em&gt;. The reason I chose categorical data for this study to provide an in-depth treatment of the various measures that can be applied to it. From my prior readings of statistical texts, I could recall that significance test alone was not enough justification; there had to be something more. It is then, I found about the different types of association measures, and it sure did clear my doubts. In my next post, I will continue the current work by providing inferential and predictive analysis. For interested reader’s, I have uploaded the complete code on my Github repository in &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/scripts/Full%20Case%20Studies/CaseStudy-UCI-PoisonousMushroomPredict.R&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Learning a classifier from census data]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/learning-a-classifier-from-census-data/" />
  <id>https://duttashi.github.io/blog/learning-a-classifier-from-census-data</id>
  <published>2017-03-02T00:00:00+00:00</published>
  <updated>2017-03-02T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;

&lt;p&gt;While reading the local daily, &lt;em&gt;“The Star”&lt;/em&gt;, my attention was caught by headlines discussing an ongoing political or social discussion on the country’s financial state. Often, it is interesting to know the underlying cause of a certain political debate or the factors contributing to an increase or decrease in inflation. “A large income is the best recipe for happiness I ever heard of” quotes the famous English novelist Jane Austen. Income is a primary concern that dictates the standard of living and economic status of an individual. Taking into account, its importance and impact on determining a nation’s growth, this study aims at presenting meaningful insights which can be used to serve as the basis for many wiser decisions that could be taken by the nation’s administrators.&lt;/p&gt;

&lt;p&gt;This study is organized as follows;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Research question&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The dataset&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Making data management decisions&lt;/p&gt;

    &lt;p&gt;A. Exploratory Data Analysis (EDA)&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;Data preprocessing (collapse the factor levels &amp;amp; re-coding)&lt;/li&gt;
      &lt;li&gt;Missing data visualization&lt;/li&gt;
      &lt;li&gt;Some obvious relationships&lt;/li&gt;
      &lt;li&gt;Some not-so-obvious relationships&lt;/li&gt;
    &lt;/ul&gt;

    &lt;p&gt;B. Correlation Detection &amp;amp; Treatment&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;Detecting skewed variables&lt;/li&gt;
      &lt;li&gt;Skewed variables treatment&lt;/li&gt;
      &lt;li&gt;Correlation detection&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Predictive data analytics&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;Creating the train and test dataset&lt;/li&gt;
      &lt;li&gt;Fit a Logistic Regression Model&lt;/li&gt;
      &lt;li&gt;Fit a Decision Tree Model&lt;/li&gt;
      &lt;li&gt;Fit a Support Vector Machine (SVM) classification model&lt;/li&gt;
      &lt;li&gt;Fit a Random Forest (RF) classification model&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Conclusion&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;1-research-question&quot;&gt;1. Research question&lt;/h3&gt;

&lt;p&gt;This study is driven by the question, “&lt;em&gt;Predict if a person’s income is above or below 50K$/yr given certain features(both quantitative and qualitative)..&lt;/em&gt;”&lt;/p&gt;

&lt;h3 id=&quot;2-the-dataset&quot;&gt;2. The dataset&lt;/h3&gt;

&lt;p&gt;The dataset used for the analysis is an extraction from the 1994 census data by Barry Becker and donated to the UCI Machine Learning &lt;a href=&quot;http://archive.ics.uci.edu/ml/datasets/Census+Income&quot;&gt;repository&lt;/a&gt;. This dataset is popularly called the “Adult” data set.&lt;/p&gt;

&lt;h3 id=&quot;3-making-data-management-decisions&quot;&gt;3. Making data management decisions&lt;/h3&gt;

&lt;p&gt;With the research question in place and the data source identified, we begin the data storytelling journey. But wait, we first require to load the data,&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Import the data from a url
&amp;gt; theUrl&amp;lt;-&quot;http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data&quot;
&amp;gt; adult.data&amp;lt;- read.table(file = theUrl, header = FALSE, sep = &quot;,&quot;, 
                    strip.white = TRUE, stringsAsFactors = TRUE,
                    col.names=c(&quot;age&quot;,&quot;workclass&quot;,&quot;fnlwgt&quot;,&quot;education&quot;,&quot;educationnum&quot;,&quot;maritalstatus&quot;,                      &quot;occupation&quot;,&quot;relationship&quot;,&quot;race&quot;,&quot;sex&quot;,&quot;capitalgain&quot;,&quot;capitalloss&quot;,                     &quot;hoursperweek&quot;,&quot;nativecountry&quot;,&quot;income&quot;)
                    )
&amp;gt; dim (adult.data)
&amp;gt; [1] 32561    15 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;A. Exploratory Data Analysis (EDA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The function, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;col.names()&lt;/code&gt; adds the user-supplied column names to the dataset. We also see &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;32,561&lt;/code&gt; observations in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt; variables. As always, we look at the data structure,&lt;/p&gt;

&lt;p&gt;Immediately, a few problems can be spotted. First, there are some categorical variables where the missing levels are coded as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;?&lt;/code&gt;; Second, there are more than 10 levels for some categorical variables.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Data preprocessing (collapse the factor levels &amp;amp; re-coding)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We begin by collapsing the factor levels to meaningful and relevant levels. We have also re-coded the missing levels denoted in the original data as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;?&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;misLevel&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; levels(adult.data$workclass)&amp;lt;- c(&quot;misLevel&quot;,&quot;FedGov&quot;,&quot;LocGov&quot;,&quot;NeverWorked&quot;,&quot;Private&quot;,&quot;SelfEmpNotInc&quot;,&quot;SelfEmpInc&quot;,&quot;StateGov&quot;,&quot;NoPay&quot;)

&amp;gt; levels(adult.data$education)&amp;lt;- list(presch=c(&quot;Preschool&quot;), primary=c(&quot;1st-4th&quot;,&quot;5th-6th&quot;),upperprim=c(&quot;7th-8th&quot;), highsch=c(&quot;9th&quot;,&quot;Assoc-acdm&quot;,&quot;Assoc-voc&quot;,&quot;10th&quot;),secndrysch=c(&quot;11th&quot;,&quot;12th&quot;), graduate=c(&quot;Bachelors&quot;,&quot;Some-college&quot;),master=c(&quot;Masters&quot;), phd=c(&quot;Doctorate&quot;))

&amp;gt; levels(adult.data$maritalstatus)&amp;lt;- list(divorce=c(&quot;Divorced&quot;,&quot;Separated&quot;),married=c(&quot;Married-AF-	spouse&quot;,&quot;Married-civ-spouse&quot;,&quot;Married-spouse-absent&quot;),notmarried=c(&quot;Never-married&quot;),widowed=c(&quot;Widowed&quot;))

&amp;gt; levels(adult.data$occupation)&amp;lt;- list(misLevel=c(&quot;?&quot;), clerical=c(&quot;Adm-clerical&quot;), lowskillabr=c(&quot;Craft-repair&quot;,&quot;Handlers-cleaners&quot;,&quot;Machine-op-inspct&quot;,&quot;Other-service&quot;,&quot;Priv-house-	serv&quot;,&quot;Prof-specialty&quot;,&quot;Protective-serv&quot;),highskillabr=c(&quot;Sales&quot;,&quot;Tech-support&quot;,&quot;Transport-moving&quot;,&quot;Armed-Forces&quot;),agricultr=c(&quot;Farming-fishing&quot;))

&amp;gt; levels(adult.data$relationship)&amp;lt;- list(husband=c(&quot;Husband&quot;), wife=c(&quot;Wife&quot;), outofamily=c(&quot;Not-in-family&quot;),unmarried=c(&quot;Unmarried&quot;), relative=c(&quot;Other-relative&quot;), ownchild=c(&quot;Own-child&quot;))

levels(adult.data$nativecountry)&amp;lt;- list(misLevel=c(&quot;?&quot;,&quot;South&quot;),SEAsia=c(&quot;Vietnam&quot;,&quot;Laos&quot;,&quot;Cambodia&quot;,&quot;Thailand&quot;),Asia=c(&quot;China&quot;,&quot;India&quot;,&quot;HongKong&quot;,&quot;Iran&quot;,&quot;Philippines&quot;,&quot;Taiwan&quot;),NorthAmerica=c(&quot;Canada&quot;,&quot;Cuba&quot;,&quot;Dominican-Republic&quot;,&quot;Guatemala&quot;,&quot;Haiti&quot;,&quot;Honduras&quot;,&quot;Jamaica&quot;,&quot;Mexico&quot;,&quot;Nicaragua&quot;,&quot;Puerto-Rico&quot;,&quot;El-Salvador&quot;,&quot;United-States&quot;), SouthAmerica=c(&quot;Ecuador&quot;,&quot;Peru&quot;,&quot;Columbia&quot;,&quot;Trinadad&amp;amp;Tobago&quot;),Europe=c(&quot;France&quot;,&quot;Germany&quot;,&quot;Greece&quot;,&quot;Holand-Netherlands&quot;,&quot;Italy&quot;,&quot;Hungary&quot;,&quot;Ireland&quot;,&quot;Poland&quot;,&quot;Portugal&quot;,&quot;Scotland&quot;,&quot;England&quot;,&quot;Yugoslavia&quot;),PacificIslands=c(&quot;Japan&quot;,&quot;France&quot;),Oceania=c(&quot;Outlying-US(Guam-USVI-etc)&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now, here is an interesting finding about this dataset. Although, the response (dependent) variable can be considered as binary but there are majority of predictors (independent) that are categorical with many levels.&lt;/p&gt;

&lt;p&gt;According to Agresti [1], &lt;em&gt;“Categorical variables have two primary types of scales. Variables having categories without a natural ordering are called nominal. Example, mode of transportation to work (automobile, bicycle, bus, subway, walk). For nominal variables, the order of listing the categories is irrelevant. The statistical analysis does not depend on that ordering. Many categorical variables do have ordered categories. Such variables are called ordinal. Examples are size of automobile (subcompact, compact, midsize, large). Ordinal variables have ordered categories, but distances between categories are unknown. Although a person categorized as moderate is more liberal than a person categorized as conservative, no numerical value describes how much more liberal that person is. An interval variable is one that does have numerical distances between any two values.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;“&lt;em&gt;A variable’s measurement scale determines which statistical methods are
appropriate. In the measurement hierarchy, interval variables are highest,
ordinal variables are next, and nominal variables are lowest. Statistical
methods for variables of one type can also be used with variables at higher
levels but not at lower levels. For instance, statistical methods for nominal
variables can be used with ordinal variables by ignoring the ordering of
categories. Methods for ordinal variables cannot, however, be used with
nominal variables, since their categories have no meaningful ordering.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;“&lt;em&gt;Nominal variables are qualitative, distinct categories differ in quality, not in quantity. Interval variables are quantitative, distinct levels have differing
amounts of the characteristic of interest.&lt;/em&gt;”&lt;/p&gt;

&lt;p&gt;Therefore, we can say that all the categorical predictors in this study are nominal in nature. Also note that R will implicitly coerce the categorical variable with levels into numerical values so there is no need to explicitly do the coercion.&lt;/p&gt;

&lt;p&gt;we check the data structure again and notice that predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;education&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;occupation&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;native.country&lt;/code&gt; have &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;11077, 4066 and 20&lt;/code&gt; missing value respectively. We show this distribution in Fig-1.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;aggr_plot &amp;lt;- aggr(adult.data, col=c(&apos;navyblue&apos;,&apos;red&apos;), numbers=TRUE, sortVars=TRUE, 
              labels=names(adult.data), cex.axis=.7, gap=3, 
              ylab=c(&quot;Histogram of missing data&quot;,&quot;Pattern&quot;)
              )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCI-IncomePredict-missplot.png&quot; alt=&quot;missplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Missing Data Visualization&lt;/p&gt;

&lt;p&gt;Now, some scholars suggest that missing data imputation for categorical variables introduce bias in the data while others oppose it. From, an analytical perspective we will impute the missing data and will use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;missForest&lt;/code&gt; library. The reason why we are imputing is because some classification algorithms will fail if they are passed with data containing missing values.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Missing data treatment
&amp;gt; library(missForest)
&amp;gt; imputdata&amp;lt;- missForest(adult.data) 
# check imputed values
&amp;gt; imputdata$ximp
# assign imputed values to a data frame
&amp;gt; adult.cmplt&amp;lt;- imputdata$ximp
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Some obvious relationships&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A majority of the working adults are between 25 to 65 years of age. From Fig-2, we see that adults below 30 years earn &amp;lt;=50k a year while those above 43 years of age earn greater than fifty thousand dollars. This leads to the assumption that experience surely matters to earn more.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; boxplot (age ~ income, data = adult.cmplt, 
     main = &quot;Age distribution for different income levels&quot;,
     xlab = &quot;Income Levels&quot;, ylab = &quot;Age&quot;, col = &quot;salmon&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-boxplot1.png&quot; alt=&quot;boxplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Boxplot for age and income&lt;/p&gt;

&lt;p&gt;Evidently, those who invest more time at workplace tend to be earning more as depicted by Fig-3.&lt;/p&gt;

&lt;p&gt;It is also interesting to note in Fig-5, that there are roughly 10% of people with doctorate degrees working in low-skilled jobs and earning greater than 50k/year.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; boxplot (hoursperweek ~ income, data = adult.cmplt, 
     main = &quot;More work hours, more income&quot;,
     xlab = &quot;Income Levels&quot;, ylab = &quot;Hours per week&quot;, col = &quot;salmon&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-boxplot3.png&quot; alt=&quot;boxplot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Boxplot for hours per week in office and income&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Some not-so-obvious relationships&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Question: Does higher skill-set (sales, technical-support, transport movers, armed forces) is a guarantor to high income?&lt;/p&gt;

&lt;p&gt;Answer: We explore this question by plotting occupation against income levels. As shown in Fig-4, its evident that acquiring a high skill set does not guarantee increased income. The workers with a low skill set (craft-repair, maintenance services, cleaner, private house security) earn more as compared to those with higher skill set.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; qplot(income, data = adult.cmplt, fill = occupation) + facet_grid (. ~ occupation)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-qplot1.png&quot; alt=&quot;qplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-4: Q-plot for occupation and income&lt;/p&gt;

&lt;p&gt;Question: Does higher education help earn more money?&lt;/p&gt;

&lt;p&gt;Answer: We explore this question by plotting education against income levels. As shown in Fig-5&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; qplot(income, data = adult.cmplt, fill = education) + facet_grid (. ~ education)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-qplot2.png&quot; alt=&quot;qplot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Q-plot for education and income&lt;/p&gt;

&lt;p&gt;From Fig-5, we can easily make out that the number of graduates earning &amp;gt;50K are more than the high school or upper-primary school educated. However, we also notice that they are certainly higher in number when compared to master’s or phd degree holders. It makes sense because if for example, in a given academic session, there will be say 90% graduates, 30% masters, &amp;lt;10% phd degree holders. It is also unfortunate to know that there are roughly 10% of people (&lt;em&gt;n=94&lt;/em&gt;) with doctorate degrees working in low-skilled jobs and earning less than 50k/year!&lt;/p&gt;

&lt;p&gt;We further drill down in this low income group bracket, shown in Fig-5, we realize that majority of them are white male married workers closely followed by the blacks and the Asia-Pacific islanders.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; qplot(income, data = adult.cmplt, fill = relationship) + facet_grid (. ~ race)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-qplot4.png&quot; alt=&quot;qplot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Q-plot for race, relationship and income&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Detecting skewed variables&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A variable is considered, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;highly skewed&lt;/code&gt; if its absolute value is greater than 1. A variable is considered, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;moderately skewed&lt;/code&gt; if its absolute value is greater than 0.5.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; skewedVars&amp;lt;- NA
&amp;gt; library(moments) # for skewness()
&amp;gt; for(i in names(adult.cmplt)){
...   if(is.numeric(adult.cmplt[,i])){
...     if(i != &quot;income&quot;){
...       # Enters this block if variable is non-categorical
...       skewVal &amp;lt;- skewness(adult.cmplt[,i])
...       print(paste(i, skewVal, sep = &quot;: &quot;))
...       if(abs(skewVal) &amp;gt; 0.5){
...         skewedVars &amp;lt;- c(skewedVars, i)
...       }
...     }
...   }
... }
[1] &quot;fnlwgt: 1.44691343514233&quot;
[1] &quot;capitalgain: 11.9532969981943&quot;
[1] &quot;capitalloss: 4.59441745643977&quot;
[1] &quot;age: 0.558717629239857&quot;
[1] &quot;educationnum: -0.311661509635468&quot;
[1] &quot;hoursperweek: 0.227632049774777&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We find that the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fnlwgt&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;capitalgain&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;capitalloss&lt;/code&gt; are highly skewed as their absolute value is greater than 0.5.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Skewed variable treatment&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Post identifying the skewed variables, we proceed to treating them by taking the log transformation. But, first we rearrange/reorder the columns for simplicity;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; adult.cmplt&amp;lt;- adult.cmplt[c(3,11:12,1,5,13,2,4,6:10,14:15)]
&amp;gt; str(adult.cmplt)
&apos;data.frame&apos;:	32561 obs. of  15 variables:
 $ fnlwgt       : num  77516 83311 215646 234721 338409 ...
 $ capitalgain  : num  2174 0 0 0 0 ...
 $ capitalloss  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ age          : num  39 50 38 53 28 37 49 52 31 42 ...
 $ educationnum : num  13 13 9 7 13 14 5 9 14 13 ...
 $ hoursperweek : num  40 13 40 40 40 40 16 45 50 40 ...
 $ workclass    : Factor w/ 9 levels &quot;misLevel&quot;,&quot;FedGov&quot;,..: 8 7 5 5 5 5 5 7 5 5 ...
 $ education    : Factor w/ 8 levels &quot;presch&quot;,&quot;primary&quot;,..: 6 6 5 5 6 7 4 6 7 6 ...
 $ maritalstatus: Factor w/ 4 levels &quot;divorce&quot;,&quot;married&quot;,..: 3 2 1 2 2 2 2 2 3 2 ...
 $ occupation   : Factor w/ 5 levels &quot;misLevel&quot;,&quot;clerical&quot;,..: 2 5 3 3 3 3 3 4 3 4 ...
 $ relationship : Factor w/ 6 levels &quot;husband&quot;,&quot;wife&quot;,..: 3 1 3 1 2 2 3 1 3 1 ...
 $ race         : Factor w/ 5 levels &quot;Amer-Indian-Eskimo&quot;,..: 5 5 5 3 3 5 3 5 5 5 ...
 $ sex          : Factor w/ 2 levels &quot;Female&quot;,&quot;Male&quot;: 2 2 2 2 1 1 1 2 1 2 ...
 $ nativecountry: Factor w/ 8 levels &quot;misLevel&quot;,&quot;SEAsia&quot;,..: 4 4 4 4 4 4 4 4 4 4 ...
 $ income       : Factor w/ 2 levels &quot;&amp;lt;=50K&quot;,&quot;&amp;gt;50K&quot;: 1 1 1 1 1 1 1 2 2 2 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We took a log transformation. Post skewed treatment, we notice that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;capitalgain&lt;/code&gt; &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;capitalloss&lt;/code&gt; have infinite values so we removed them from subsequent analysis.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; adult.cmplt.norm&amp;lt;- adult.cmplt
&amp;gt; adult.cmplt.norm[,1:3]&amp;lt;- log(adult.cmplt[1:3],2) # where 2 is log base 2
&amp;gt; adult.cmplt.norm$capitalgain&amp;lt;- NULL
&amp;gt; adult.cmplt.norm$capitalloss&amp;lt;-NULL
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Correlation detection&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We now checked for variables with high correlations to each other. Correlation measures the relationship between two variables. When two variables are so highly correlated that they explain each other (to the point that one can predict the variable with the other), then we have &lt;em&gt;collinearity&lt;/em&gt; (or &lt;em&gt;multicollinearity&lt;/em&gt;) problem. Therefore, its is important to treat collinearity problem. Let us now check, if our data has this problem or not.&lt;/p&gt;

&lt;p&gt;Again, it is important to note that correlation works only for continuous variables. We can calculate the correlations by using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cor()&lt;/code&gt; as shown;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; correlat&amp;lt;- cor(adult.cmplt.norm[c(1:4)])
&amp;gt; corrplot(correlat, method = &quot;pie&quot;)
&amp;gt; highlyCor &amp;lt;- colnames(adult.cmplt.num)[findCorrelation(correlat, cutoff = 0.7, verbose = TRUE)]
All correlations &amp;lt;= 0.7 
&amp;gt; highlyCor # No high Correlations found
character(0)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-UCIncomePredict-corplot.png&quot; alt=&quot;corplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Correlation detection&lt;/p&gt;

&lt;p&gt;From Fig-7, its evident that none of the predictors are highly correlated to each other. We now proceed to building the prediction model.&lt;/p&gt;

&lt;p&gt;###4. Predictive data analytics&lt;/p&gt;

&lt;p&gt;In this section, we will discuss various approaches applied to model building, predictive power and their trade-offs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A. Creating the train and test dataset&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We now divide the data into 75% training set and 25% testing set. We also created a root mean square evaluation function for model testing.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ratio = sample(1:nrow(adult.cmplt), size = 0.25*nrow(adult.cmplt))
&amp;gt; test.data = adult.cmplt[ratio,] #Test dataset 25% of total
&amp;gt; train.data = adult.cmplt[-ratio,] #Train dataset 75% of total
&amp;gt; dim(train.data)
[1] 24421    15
&amp;gt; dim(test.data)
[1] 8140   15
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;**B. Fit a Logistic Regression Model **&lt;/p&gt;

&lt;p&gt;We fit a logistic regression model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; glm.fit&amp;lt;- glm(income~., family=binomial(link=&apos;logit&apos;),data = train.data)
Warning message:
glm.fit: fitted probabilities numerically 0 or 1 occurred
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred means that the data is possibly linearly separable. Let’s look at the summary for the model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; summary(glm.fit)
Call:
glm(formula = income ~ ., family = binomial(link = &quot;logit&quot;), 
data = train.data)

Deviance Residuals: 
Min       1Q   Median       3Q      Max  
-5.2316  -0.4639  -0.1713  -0.0311   3.4484  

Coefficients: (1 not defined because of singularities)
                              Estimate     Std. Error z value Pr(&amp;gt;|z|)    
(Intercept)                 -27.1523662282 171.0342617549  -0.159 0.873863    
age                           0.0274845471   0.0019376261  14.185  &amp;lt; 2e-16 ***
workclassFedGov               0.4073987950   0.2085465221   1.954 0.050759 .  
workclassLocGov              -0.3070912295   0.1944447001  -1.579 0.114262    
workclassNeverWorked        -10.5345275621 510.1141392772  -0.021 0.983524    
workclassPrivate             -0.1374981405   0.1816628614  -0.757 0.449118    
workclassSelfEmpNotInc       -0.1132407363   0.1995129601  -0.568 0.570316    
workclassSelfEmpInc          -0.6270437314   0.1773500692  -3.536 0.000407 ***
workclassStateGov            -0.4387629630   0.2049449847  -2.141 0.032284 *  
workclassNoPay              -13.9146466535 367.0432320049  -0.038 0.969759    
fnlwgt                        0.0000004226   0.0000002029   2.083 0.037252 *  
educationprimary             18.6369757615 171.0337793366   0.109 0.913229    
educationupperprim           18.6015984474 171.0337199499   0.109 0.913393    
educationhighsch             19.4272321191 171.0336543439   0.114 0.909565    
educationsecndrysch          18.3381423049 171.0336420490   0.107 0.914615    
educationgraduate            20.1855955674 171.0336647250   0.118 0.906051    
educationmaster              20.6169432260 171.0337212540   0.121 0.904053    
educationphd                 20.8122445845 171.0338205358   0.122 0.903149    
educationnum                  0.1301601416   0.0134594027   9.671  &amp;lt; 2e-16 ***
maritalstatusmarried          0.6518153342   0.1922871329   3.390 0.000699 ***
 [ reached getOption(&quot;max.print&quot;) -- omitted 26 rows ]
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 26907  on 24420  degrees of freedom
Residual deviance: 14892  on 24376  degrees of freedom
AIC: 14982

Number of Fisher Scoring iterations: 14  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Its evident that the significant predictors are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;age&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;workclassSelfEmpInc&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fnlwgt&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;educationnum&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;maritalstatusmarried&lt;/code&gt;. As for the statistical significant variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;age&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;educationnum&lt;/code&gt; has the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lowest p value suggesting a strong association with the response, income&lt;/code&gt;. 
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null deviance&lt;/code&gt; shows how well the response is predicted by the model with nothing but an intercept. Deviance is a measure of goodness of fit of a generalized linear model. it’s a measure of badness of fit–higher numbers indicate worse fit. The residual deviance shows how well the response is predicted by the model when the predictors are included. From your example, it can be seen that the residual deviance decreases by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;12115 (27001-14886)&lt;/code&gt; when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15 predictors&lt;/code&gt; were added to it.(note: degrees of freedom = no. of observations – no. of predictors). This decrease in deviance is evidence of significant fit. If the deviance would have increased it would indicate a significant lack of fit. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AIC&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;14976&lt;/code&gt;. The Akaike Information Criterion (AIC) provides a method for assessing the quality of your model through comparison of related models.  It’s based on the Deviance, but penalizes you for making the model more complicated.  Much like adjusted R-squared, it’s intent is to prevent you from including irrelevant predictors. However, unlike adjusted R-squared, the number itself is not meaningful. If you have more than one similar candidate models (where all of the variables of the simpler model occur in the more complex models), then you should select the model that has the smallest AIC. So AIC is useful for comparing models, but isn’t interpretable on its own.&lt;/p&gt;

&lt;p&gt;We now create another logistic model that includes only the significant predictors.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; glm.fit1&amp;lt;- glm(income ~ age + workclass + educationnum + fnlwgt + maritalstatus, family=binomial(link=&apos;logit&apos;),data = train.data)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now we can run the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;anova()&lt;/code&gt; function on the improved model to analyze the table of deviance.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; anova(glm.fit, glm.fit1, test=&quot;Chisq&quot;)

Analysis of Deviance Table

Model 1: income ~ age + workclass + fnlwgt + education + educationnum + 
maritalstatus + occupation + relationship + race + sex + 
capitalgain + capitalloss + hoursperweek + nativecountry
Model 2: income ~ age + workclass + educationnum + fnlwgt + maritalstatus
  	Resid. Df Resid. Dev  Df Deviance  Pr(&amp;gt;Chi)    
1     24376      14892                           
2     24406      18428 -30  -3536.1 &amp;lt; 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;By conducting the anova test, it performs the Chi-square test to compare &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;glm.fit&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;glm.fit1&lt;/code&gt; (i.e. it tests whether reduction in the residual sum of squares are statistically significant or not). The test shows that, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Model 2 is statistically significant as the p value is less than 0.05&lt;/code&gt;. Therefore, the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(age + workclass + educationnum + fnlwgt + maritalstatus)&lt;/code&gt; are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;relevant for the model&lt;/code&gt;. See this links for details, &lt;a href=&quot;http://stats.stackexchange.com/questions/172782/how-to-use-r-anova-results-to-select-best-model&quot;&gt;1&lt;/a&gt;, &lt;a href=&quot;http://stats.stackexchange.com/questions/20523/difference-between-logit-and-probit-models/30909#30909&quot;&gt;2&lt;/a&gt; and &lt;a href=&quot;http://stats.idre.ucla.edu/other/mult-pkg/faq/general/faq-how-do-i-interpret-odds-ratios-in-logistic-regression/&quot;&gt;3&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We now test the logistic model on all predictors and make predictions on unseen data.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(1234)
&amp;gt; glm.pred&amp;lt;- predict(glm.fit, test.data, type = &quot;response&quot;)
&amp;gt; hist(glm.pred, breaks=20)
&amp;gt; hist(glm.pred[test.data$income], col=&quot;red&quot;, breaks=20, add=TRUE)
&amp;gt; table(actual= test.data$income, predicted= glm.pred&amp;gt;0.5)
   predicted
actual  FALSE TRUE
  	&amp;lt;=50K  5674  482
  	&amp;gt;50K    678 1306
&amp;gt; (5674+1306)/8140
[1] 0.8574939
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The classifier returns 86% accuracy when the model includes all predictors in it. Let us see, if the model accuracy increases with the inclusion of significant predictors only;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(1234)
&amp;gt; glm.fit1&amp;lt;- glm(income ~ age + workclass + educationnum + fnlwgt + maritalstatus, family=binomial(link=&apos;logit&apos;),data = train.data)
&amp;gt; glm.pred1&amp;lt;- predict(glm.fit, test.data, type = &quot;response&quot;)
&amp;gt; table(actual= test.data$income, predicted= glm.pred1&amp;gt;0.5)
   predicted
actual  FALSE TRUE
  	&amp;lt;=50K  5683  473
  	&amp;gt;50K    997  987
&amp;gt; (5683+987)/8140
[1] 0.8194103
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With the inclusion of significant predictors in the model, the classifier accuracy decreases by 4 percent to 82%.&lt;/p&gt;

&lt;p&gt;Logistic Regression Inference: The model gives higher accuracy on unseen data when it has all the predictors included. The model’s accuracy decreases when some of the predictors are removed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C. Fit a Decision Tree Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We try the decision tree model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; tree.model&amp;lt;- rpart(income~., data=train.data, method=&quot;class&quot;, minbucket=20)
&amp;gt; tree.predict&amp;lt;- predict(tree.model, test.data, type = &quot;class&quot;)
&amp;gt; confusionMatrix(test.data$income, tree.predict) # 86% accuracy
Confusion Matrix and Statistics

      Reference
Prediction &amp;lt;=50K &amp;gt;50K
 &amp;lt;=50K  5832  324
 &amp;gt;50K    760 1224
                                      
           Accuracy : 0.8668          
             95% CI : (0.8593, 0.8741)
No Information Rate : 0.8098          
P-Value [Acc &amp;gt; NIR] : &amp;lt; 2.2e-16       
                                      
              Kappa : 0.6097          
 	Mcnemar&apos;s Test P-Value : &amp;lt; 2.2e-16       
                                      
        Sensitivity : 0.8847          
        Specificity : 0.7907          
     Pos Pred Value : 0.9474          
     Neg Pred Value : 0.6169          
         Prevalence : 0.8098          
     Detection Rate : 0.7165          
   	Detection Prevalence : 0.7563          
  Balanced Accuracy : 0.8377          
                                      
   &apos;Positive&apos; Class : &amp;lt;=50K           
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The accuracy is 87% for the model with all the predictors in it and the accuracy decreases to 82 percent for a model with significant predictors only. Also, a decision tree model is no better than the logistic regression model in terms of accuracy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D. Fit a Support Vector Machine (SVM) classification model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We tried the SVM model;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; svm.model&amp;lt;- svm(income~., data = train.data,kernel = &quot;radial&quot;, cost = 1, gamma = 0.1)
&amp;gt; svm.predict &amp;lt;- predict(svm.model, test.data)
&amp;gt; confusionMatrix(test.data$income, svm.predict) # 87% accuracy
Confusion Matrix and Statistics

      Reference
Prediction &amp;lt;=50K &amp;gt;50K
	 &amp;lt;=50K  5695  461
   		  &amp;gt;50K    582 1402
                                      
           Accuracy : 0.8719          
             95% CI : (0.8644, 0.8791)
No Information Rate : 0.7711          
P-Value [Acc &amp;gt; NIR] : &amp;lt; 2.2e-16       
                                      
              Kappa : 0.6451          
 	Mcnemar&apos;s Test P-Value : 0.0002027       
                                      
        Sensitivity : 0.9073          
        Specificity : 0.7525          
     Pos Pred Value : 0.9251          
     Neg Pred Value : 0.7067          
         Prevalence : 0.7711          
     Detection Rate : 0.6996          
   	Detection Prevalence : 0.7563          
  Balanced Accuracy : 0.8299          
                                      
   &apos;Positive&apos; Class : &amp;lt;=50K           
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The classification accuracy of the SVM model having all predictors, increases by 1 percent to 87%, when compared to the decision tree and the logistic regression model. Again, its interesting to note that the SVM model accuracy decreases to 4 percent when only the significant predictors are included in the model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;E. Fit a Random Forest (RF) classification model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We finally try the RF model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; rf.model&amp;lt;- randomForest(income~., 
...                         data = train.data, 
...                         importance=TRUE,
...                         keep.forest=TRUE)
&amp;gt; rf.predict &amp;lt;- predict(rf.model, test.data)
&amp;gt; confusionMatrix(test.data$income, rf.predict) # 88%
Confusion Matrix and Statistics

      Reference
Prediction &amp;lt;=50K &amp;gt;50K
 &amp;lt;=50K  5809  347
 &amp;gt;50K    567 1417
                                       
           Accuracy : 0.8877           
             95% CI : (0.8807, 0.8945) 
No Information Rate : 0.7833           
P-Value [Acc &amp;gt; NIR] : &amp;lt; 2.2e-16        
                                       
              Kappa : 0.6835           
 	Mcnemar&apos;s Test P-Value : 0.000000000000436
                                       
        Sensitivity : 0.9111           
        Specificity : 0.8033           
     Pos Pred Value : 0.9436           
     Neg Pred Value : 0.7142           
         Prevalence : 0.7833           
     Detection Rate : 0.7136           
   	Detection Prevalence : 0.7563           
  Balanced Accuracy : 0.8572           
                                       
   &apos;Positive&apos; Class : &amp;lt;=50K             
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So, it is the &lt;strong&gt;Random Forest model&lt;/strong&gt; that gives the &lt;strong&gt;highest prediction accuracy of 88%&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this study, we aimed to predict a person’s income based on variables like habitat, education, marital status, age, race, sex and others. We found in exploring this particular dataset that, &lt;em&gt;higher education is no guarantee to high income&lt;/em&gt;. This pattern could be attributed the uneven sample distribution. Several classification models were tested for prediction accuracy and we determined that the Random Forest model gives the highest accuracy among others.&lt;/p&gt;

&lt;p&gt;As a future work, we will extend this study to include feature engineering methods, to measure if the predictive power of the models could be increased or not.&lt;/p&gt;

&lt;p&gt;The complete code is listed on my Github &lt;a href=&quot;https://github.com/duttashi/LearningR/blob/master/scripts/Full%20Case%20Studies/CaseStudy-UCI-IncomePredict.R&quot;&gt;repository&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Predicting employment related factors in Malaysia- A regression analysis approach]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/predicting-employment-factors-in-malaysia-case-study/" />
  <id>https://duttashi.github.io/blog/predicting-employment-factors-in-malaysia-case-study</id>
  <published>2017-02-20T00:00:00+00:00</published>
  <updated>2017-02-20T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;

&lt;p&gt;A recent news article published in the national daily, &lt;a href=&quot;http://www.thestar.com.my/business/business-news/2017/02/14/jobless-rate-up-slightly/&quot;&gt;The Star&lt;/a&gt;, reported, “&lt;em&gt;The country’s unemployment rate has inched up by 0.1 percentage points to 3.5% in December 2016 compared to the previous month, according to the &lt;a href=&quot;(https://www.dosm.gov.my/v1/index.php?r=column/cthemeByCat&amp;amp;cat=124&amp;amp;bul_id=VWl4c2VyZ0Q3MEUxU0NzOVBPMnlDUT09&amp;amp;menu_id=U3VPMldoYUxzVzFaYmNkWXZteGduZz09)&quot;&gt;Statistics Department&lt;/a&gt;. On a year-on-year comparison, the unemployment rate was also up 0.1 percentage point from December 2015. It said that in December 2016, 14,276,700 people were employed out of the country’s total labour force of 14,788,900, while 512,000 were unemployed.&lt;/em&gt;” The news daily also reported that, “&lt;em&gt;Human Resources Minister Datuk Seri Richard Riot said the country’s unemployment rate was still “manageable” and unlikely to exceed 3.5% this year despite the global economic slowdown.&lt;/em&gt;”&lt;/p&gt;

&lt;p&gt;In this analytical study, we have made an attempt to verify this claim by regressing the employed work force in Malaysia on predictors like Outside Labor Force, Unemployment percentage, Labour Force and others.&lt;/p&gt;

&lt;p&gt;This study is organized as follows;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Business/Research Question&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Data Source&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Making data management decisions&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

  	A. Exploratory Data Analysis (EDA)

&lt;ul&gt;
  &lt;li&gt;Data preprocessing (rename and replace)&lt;/li&gt;
  &lt;li&gt;Data preprocessing (joining the tables)&lt;/li&gt;
  &lt;li&gt;Data preprocessing (missing data visualization &amp;amp; imputation)&lt;/li&gt;
&lt;/ul&gt;

  	B. Basic Statistics

&lt;ul&gt;
  &lt;li&gt;One-way table&lt;/li&gt;
  &lt;li&gt;Two-way table&lt;/li&gt;
  &lt;li&gt;Test of independence for categorical variables&lt;/li&gt;
  &lt;li&gt;Visualizing significant variables found in the test of independence&lt;/li&gt;
&lt;/ul&gt;

  	C. Outlier Detection &amp;amp; Treatment

&lt;ul&gt;
  &lt;li&gt;Boxplots for outlier detection&lt;/li&gt;
  &lt;li&gt;Outlier Treatment&lt;/li&gt;
  &lt;li&gt;Data type conversion&lt;/li&gt;
&lt;/ul&gt;

  	D. Correlation Detection &amp;amp; Treatment

&lt;ul&gt;
  &lt;li&gt;Detecting skewed variables&lt;/li&gt;
  &lt;li&gt;Skewed variable treatment&lt;/li&gt;
  &lt;li&gt;Correlation detection&lt;/li&gt;
  &lt;li&gt;Multicollinearity&lt;/li&gt;
  &lt;li&gt;Multicollinearity treatment
  		* Principal Component Analysis (PCA)
    * Plotting the PCA (biplot) components
    * Determining the contribution (%) of each parameter&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Predictive Data Analytics&lt;/p&gt;

    &lt;p&gt;A. Creating the train and test dataset&lt;/p&gt;

    &lt;p&gt;B. Model Building - Evaluation Method&lt;/p&gt;

    &lt;p&gt;C. Model Building - Regression Analysis&lt;/p&gt;

    &lt;p&gt;D. Model Building - other supervised algorithms&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;Regression Tree method&lt;/li&gt;
      &lt;li&gt;Random Forest method&lt;/li&gt;
    &lt;/ul&gt;

    &lt;p&gt;E. Model Performance comparison&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Conclusion&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;1-businessresearch-question&quot;&gt;1. Business/Research Question&lt;/h3&gt;

&lt;p&gt;Determine the factors which contribute to accurately predicting unemployment rate from historical statistical data on labour force data in Malaysia.&lt;/p&gt;

&lt;h3 id=&quot;2-data-source&quot;&gt;2. Data Source&lt;/h3&gt;

&lt;p&gt;The data comes from the Department of Statistics, Malaysia. This is an open data source portal and the data files can be accessed from their official &lt;a href=&quot;http://www.dosm.gov.my/v1/index.php?r=column3/accordion&amp;amp;menu_id=aHhRYUpWS3B4VXlYaVBOeUF0WFpWUT09&quot;&gt;website&lt;/a&gt;. Click the + sign next to “Labour Force &amp;amp; Social Statistics” to expand the drop down list to access the data files.&lt;/p&gt;

&lt;h3 id=&quot;3-making-data-management-decisions&quot;&gt;3. Making data management decisions&lt;/h3&gt;

&lt;p&gt;Initially, the dataset consisted of five comma-separated files. Each file provided data (from year 1965 to year 2014) on factors like number of rubber estates in Malaysia, total planted area, production of natural rubber, tapped area, yield per hectare and total number of paid employees in the rubber estate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A. Exploratory Data Analysis (EDA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This phase constitutes 80% of a data analytical work. We noticed that each data file consisted of 544 rows in 3 variables where the variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt; was common for all data tables. This confirmed our assumption that the actual dataset was divided into six separate files. We first imported the data files into the R environment as given;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; df1&amp;lt;- read.csv(&quot;data/bptms-Employed_by_State.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)
&amp;gt; df2&amp;lt;- read.csv(&quot;data/bptms-Labour_force_by_State.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)
&amp;gt; df3&amp;lt;- read.csv(&quot;data/bptms-Labour_Force_Participation_rate_by_State.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)
&amp;gt; df4&amp;lt;- read.csv(&quot;data/bptms-Outside_labour_force_by_State.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)
&amp;gt; df5&amp;lt;- read.csv(&quot;data/bptms-Unemployment_Rate.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)

&amp;gt; dim(df1)
[1] 544   3
&amp;gt; dim(df2)
[1] 544   3
&amp;gt; dim(df3)
[1] 544   3
&amp;gt; dim(df4)
[1] 544   3
&amp;gt; dim(df5)
[1] 544   3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now that the data was imported in, we began with the initial process of data exploration. The first step was to look at the data structure for which we used the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str()&lt;/code&gt; as given;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; str(df1)
&apos;data.frame&apos;:	544 obs. of  3 variables:
 $ Year           : int  1982 1983 1984 1985 1986 1987 1988 1989 1990 1992 ...
 $ State.Country  : chr  &quot;Malaysia&quot; &quot;Malaysia&quot; &quot;Malaysia&quot; &quot;Malaysia&quot; ...
 $ Employed...000.: chr  &quot;5,249.00&quot; &quot;5,457.00&quot; &quot;5,566.70&quot; &quot;5,653.40&quot; ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and found that variable like, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; was treated as a character data type by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;R&lt;/code&gt; because it’s values contained a comma in them. Thus, coercing the number to a character data type. We also need to rename the variables to short, succinct names. The variable naming convention will follow &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CamelCase&lt;/code&gt; style.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Data preprocessing (rename and replace)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We begin by renaming the variable names. We will use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rename()&lt;/code&gt; of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plyr&lt;/code&gt; package. This library needs to be loaded in the R environment first. We use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gsub()&lt;/code&gt; to replace the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;comma&lt;/code&gt; between the numbers in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; variable, followed by changing the data type to numeric. We show the data management steps as follows;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(plyr) # for the rename ()
&amp;gt; df1&amp;lt;- rename(df1, c(&quot;State.Country&quot; = &quot;State&quot;))
&amp;gt; df1&amp;lt;- rename(df1, c(&quot;Employed...000.&quot; = &quot;Employed&quot;))
&amp;gt; df2&amp;lt;- rename(df2, c(&quot;State.Country&quot; = &quot;State&quot;))
&amp;gt; df2&amp;lt;- rename(df2, c(&quot;Labour.Force...000.&quot; = &quot;LabrFrc&quot;))
&amp;gt; df3&amp;lt;- rename(df3, c(&quot;State.Country&quot; = &quot;State&quot;))
&amp;gt; df3&amp;lt;- rename(df3, c(&quot;Labour.Force.Participation.Rate..Percentage.&quot; = &quot;LabrFrcPerct&quot;))
&amp;gt; df4&amp;lt;- rename(df4, c(&quot;State.Country&quot; = &quot;State&quot;))
&amp;gt; df4&amp;lt;- rename(df4, c(&quot;Outside.Labour.Force...000.&quot; = &quot;OutLabrFrc&quot;))
&amp;gt; df5&amp;lt;- rename(df5, c(&quot;State.Country&quot; = &quot;State&quot;))
&amp;gt; df5&amp;lt;- rename(df5, c(&quot;Unemployment.Rate..Percentage.&quot; = &quot;UnempRatePerct&quot;))

&amp;gt; ## Change data type
&amp;gt; df1$State&amp;lt;- as.factor(df1$State)
&amp;gt; df1$Employed&amp;lt;- as.numeric(gsub(&quot;,&quot;,&quot;&quot;, df1$Employed))
&amp;gt; df2$State&amp;lt;- as.factor(df2$State)
&amp;gt; df2$LabrFrc&amp;lt;- as.numeric(gsub(&quot;,&quot;,&quot;&quot;, df2$LabrFrc))
&amp;gt; df3$State&amp;lt;- as.factor(df3$State)
&amp;gt; df4$State&amp;lt;- as.factor(df4$State)
&amp;gt; df4$OutLabrFrc&amp;lt;- as.numeric(gsub(&quot;,&quot;,&quot;&quot;, df4$OutLabrFrc))
&amp;gt; df5$State&amp;lt;- as.factor(df5$State)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Data preprocessing (joining the tables)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Next, we apply the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inner_join()&lt;/code&gt; of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dplyr&lt;/code&gt; package to join the five data frames to a single master data frame called, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df.master&lt;/code&gt;. To check the time it takes for data table joins, we wrap the inner join function in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;system.time()&lt;/code&gt; method; Since, this is a small dataset so there are not much overheads involved in an operation like inner join but for large data tables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;system.time()&lt;/code&gt; is a handy function.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(dplyr)
&amp;gt; system.time(join1&amp;lt;- inner_join(df1,df2))
Joining, by = c(&quot;Year&quot;, &quot;State&quot;)
   	user  system elapsed 
   	0.00    0.00    0.47 
&amp;gt; system.time(join2&amp;lt;- inner_join(df3,df4))
Joining, by = c(&quot;Year&quot;, &quot;State&quot;)
   	user  system elapsed 
  0       0       0 
&amp;gt; system.time(join3&amp;lt;- inner_join(join1,join2))
Joining, by = c(&quot;Year&quot;, &quot;State&quot;)
   	user  system elapsed 
  0       0       0 
&amp;gt; system.time(df.master&amp;lt;- inner_join(join3,df5))
Joining, by = c(&quot;Year&quot;, &quot;State&quot;)
   	user  system elapsed 
  0       0       0 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let us look at the structure of the data frame, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df.master&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt;  str(df.master)
&apos;data.frame&apos;:	544 obs. of  7 variables:
 	$ Year          : int  1982 1983 1984 1985 1986 1987 1988 1989 1990 1992 ...
 	$ State         : Factor w/ 17 levels &quot;Johor&quot;,&quot;Kedah&quot;,..: 4 4 4 4 4 4 4 4 4 4 ...
 	$ Employed      : num  5249 5457 5567 5653 5760 ...
 	$ LabrFrc       : num  5431 5672 5862 5990 6222 ...
 	$ LabrFrcPerct  : num  64.8 65.6 65.3 65.7 66.1 66.5 66.8 66.2 66.5 65.9 ...
 	$ OutLabrFrc    : num  2945 2969 3120 3125 3188 ...
 	$ UnempRatePerct: num  3.4 3.8 5 5.6 7.4 7.3 7.2 5.7 4.5 3.7 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Data preprocessing (missing data visualization &amp;amp; imputation)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let us visualize the data now. The objective is to check for missing data patterns. For this, we will use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;aggr_plot()&lt;/code&gt; function of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VIM&lt;/code&gt; package.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(VIM)
&amp;gt; aggr_plot &amp;lt;- aggr(df.master, col=c(&apos;navyblue&apos;,&apos;red&apos;), numbers=TRUE, sortVars=TRUE, labels=names(df.master), cex.axis=.7, gap=3,                    ylab=c(&quot;Histogram of missing data&quot;,&quot;Pattern&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

 	Variables sorted by number of missings: 
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;   Variable      Count
   Employed 0.05330882
   LabrFrc 0.05330882
   	   	LabrFrcPerct 0.05330882
 	OutLabrFrc 0.05330882
 		UnempRatePerct 0.05330882
    Year 0.00000000
    State 0.00000000

Warning message:
In plot.aggr(res, ...) : not enough horizontal space to display frequencies
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Note: The warning message is generated because the plot size is not big enough. I’m using RStudio, where the plot size is small. You can safely ignore this message.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-missplot.png&quot; alt=&quot;missplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Missing Data Visualization&lt;/p&gt;

&lt;p&gt;In Fig-1, the missing data is shown in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;red&lt;/code&gt; color. Here we see that variables like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt; have missing data. To verify, how many instances of missing values are there, use, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;colSums()&lt;/code&gt; like&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; colSums(is.na(df.master))
      Year          State       Employed        LabrFrc   LabrFrcPerct     OutLabrFrc UnempRatePerct 
         0              0             29             29             29             29             29  There are 29 instances of missing data. In an earlier case study, we had used the `Boruta` package for missing data imputation. We tried it on this case study and it failed to impute all missing values, quite a strange phenomenon. Anyway, for this case study we have used the `missForest` method from the `missForest` package. You will have to install/load it in the `R` environment first if you do not have it. We save the imputed data in a new data frame called, `df.cmplt`.

&amp;gt; ## MISSING DATA IMPUTATION 
&amp;gt; library(missForest)
&amp;gt; imputdata&amp;lt;- missForest(df.master)
  	missForest iteration 1 in progress...done!
  	missForest iteration 2 in progress...done!
# check imputed values
&amp;gt; imputdata$ximp
Year             State  Employed   LabrFrc LabrFrcPerct OutLabrFrc UnempRatePerct
1   1982          Malaysia  5249.000  5431.400       64.800  2944.6000          3.400
2   1983          Malaysia  5457.000  5671.800       65.600  2969.4000          3.800
3   1984          Malaysia  5566.700  5862.500       65.300  3119.6000          5.000
4   1985          Malaysia  5653.400  5990.100       65.700  3124.9000          5.600
5   1986          Malaysia  5760.100  6222.100       66.100  3188.3000          7.400
[ reached getOption(&quot;max.print&quot;) -- omitted 530 rows ]
# assign imputed values to a data frame
&amp;gt; df.cmplt&amp;lt;- imputdata$ximp
# check for missing values in the new data frame
&amp;gt; colSums(is.na(df.cmplt))
      Year          State       Employed        LabrFrc   LabrFrcPerct     OutLabrFrc UnempRatePerct 
         0              0              0              0              0              0              0   
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;B. Basic Statistics&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We now provide few basic statistics on the data like frequency tables (one way table, two way table, proportion table and percentage table).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;One-way table&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Simple frequency counts can be generated using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table()&lt;/code&gt; function.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; mytable&amp;lt;- with(data=df.cmplt, table(State))
&amp;gt; mytable
State
        Johor             Kedah          Kelantan          Malaysia            Melaka   Negeri Sembilan 
           32                32                32                32                32                32 
       Pahang             Perak            Perlis      Pulau Pinang             Sabah           Sarawak 
           32                32                32                32                32                32 
     Selangor        Terengganu        W.P Labuan W.P. Kuala Lumpur     W.P.Putrajaya 
           32                32                32                32                32  * **Two-way table**
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For two-way table, the format for the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table()&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mytable&amp;lt;- table(A,B)&lt;/code&gt; where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; is the row variable and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; is the column variable. Alternatively, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xtabs()&lt;/code&gt; function allows to create a contingency table using the formula style input. The format is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mytable&amp;lt;- xtabs(~ A + B, data=mydata)&lt;/code&gt; where, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mydata&lt;/code&gt; is a matrix of data frame. In general, the variables to be cross classified appear on the right side of the formula (i.e. to the right side of the ~) separated by + sign.
Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prop.table(mytable)&lt;/code&gt; to express table entries as fractions.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Test of independence for categorical variables&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;R provides several methods for testing the independence of the categorical variables like &lt;em&gt;chi-square test of independence&lt;/em&gt;, &lt;em&gt;Fisher exact test&lt;/em&gt;, &lt;em&gt;Cochran-Mantel-Haenszel test&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;For this report, we applied the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chisq.test()&lt;/code&gt; to a two-way table to produce the &lt;em&gt;chi square test of independence&lt;/em&gt; of the row and column variable as shown next;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(vcd) # for xtabs() and assocstats()
Loading required package: grid
&amp;gt; mytable&amp;lt;- xtabs(~State+Employed, data= df.cmplt)
&amp;gt; chisq.test(mytable)

Pearson&apos;s Chi-squared test

data:  mytable
X-squared = 8534, df = 8368, p-value = 0.1003

Warning message:
In chisq.test(mytable) : Chi-squared approximation may be incorrect
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here, the p value is greater than 0.05, indicating no relationship between state &amp;amp; employed variable. Let’s look at another example as given below;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; mytable&amp;lt;- xtabs(~State+UnempRatePerct, data= df.cmplt)
&amp;gt; chisq.test(mytable) 

Pearson&apos;s Chi-squared test

data:  mytable
X-squared = 2104.2, df = 1776, p-value = 0.00000009352

Warning message:
In chisq.test(mytable) : Chi-squared approximation may be incorrect
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here, the p value is less than 0.05, indicating a relationship between state &amp;amp; Unemployed rate percent variable.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; mytable&amp;lt;- xtabs(~State+LabrFrcPerct, data= df.cmplt)
&amp;gt; chisq.test(mytable)

Pearson&apos;s Chi-squared test

data:  mytable
X-squared = 3309.2, df = 2928, p-value = 0.0000008368
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Again, the p value is less than 0.05, indicating a relationship between state &amp;amp; labour force in percentage variable&lt;/p&gt;

&lt;p&gt;Therefore, to summarise, the significance test conducted using chi-square test of independence evaluates whether or not sufficient evidence exists to reject a null hypothesis of independence between the variables. We could not reject the null hypothesis for State vs Employed, Labour Force and Outside Labour Force variables confirming that there exists no relationship between these variables.&lt;/p&gt;

&lt;p&gt;However, we were unable to reject the null hypothesis for state vs UnempRatePerct and LabrFrcPerct. This proves that there exist a relationship between these variables.&lt;/p&gt;

&lt;p&gt;Unfortunately we cannot test the association between the two categorical variables &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;State&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;, because the measures of association like Phi and Cramer’s V require the categorical variables to have at least two levels example &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Sex&quot;&lt;/code&gt; got two levels, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Male&quot;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Female&quot;&lt;/code&gt;. Use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;assocstats()&lt;/code&gt; from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vcd&lt;/code&gt; package to test association.&lt;/p&gt;

&lt;p&gt;Now, that we have determined the variables that have relationships with each other, we continue to the next step of visualizing their distribution in the data. We have used density plots for continuous variable distribution.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Visualizing significant variables found in the test of independence&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We have used the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ggplot2&lt;/code&gt; library for data visualization. The plots are shown in Fig-2 and Fig-3 respectively.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.cmplt)+
...   geom_density(aes(x=LabrFrcPerct, fill=&quot;red&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-chisq1.png&quot; alt=&quot;chisqplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Density plot for variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In Fig-2, we see that a majority of the labor force in Malaysia lies between the 60-70 percentage bracket.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.cmplt)+
...   geom_density(aes(x=UnempRatePerct, fill=&quot;red&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-chisq2.png&quot; alt=&quot;chisqplot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Density plot for variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;From Fig-3, its evident that a majority of unemployment rate peaks between 2.5 to 5.0 interval.&lt;/p&gt;

&lt;p&gt;We now, derive a subset of the data based on the significant variation revealed in Fig-2 and Fig-3 respectively for further data analysis.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; subst.data.2&amp;lt;- subset(df.cmplt, 
...                     (LabrFrcPerct&amp;gt;=60 &amp;amp; LabrFrcPerct &amp;lt;=70) &amp;amp; 
...                     (UnempRatePerct&amp;gt;=2.5 &amp;amp; UnempRatePerct&amp;lt;=5.0)
...                     )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This reduces the dataset size to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;269 observations&lt;/code&gt; as given in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt; dim(subst.data.2)
[1] 269   7&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C. Outlier Detection &amp;amp; Treatment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Outlier treatment is a vital part of descriptive analytics since outliers can lead to misleading conclusions regarding our data. For continuous variables, the values that lie outside the 1.5 * IQR limits. For categorical variables, outliers are considered to be the values of which frequency is less than 10% outliers gets the extreme most observation from the mean. If you set the argument opposite=TRUE, it fetches from the other side.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Boxplots for outlier detection&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When reviewing a boxplot, an outlier is defined as a data point that is located outside the fences (“whiskers”) of the boxplot (e.g: outside 1.5 times the interquartile range above the upper quartile and bellow the lower quartile).&lt;/p&gt;

&lt;p&gt;Remember, ggplot2 requires both an x and y variable of a boxplot. Here is how to make a single boxplot as shown by leaving the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; aesthetic &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;blank&lt;/code&gt;;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt;p1&amp;lt;-ggplot(data= df.cmplt, aes(x=&quot;&quot;, y=Employed))+
  	geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)
&amp;gt;p2&amp;lt;-ggplot(data= df.cmplt, aes(x=&quot;&quot;, y=LabrFrc))+
  	geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)
&amp;gt;p3&amp;lt;-ggplot(data= df.cmplt, aes(x=&quot;&quot;, y=OutLabrFrc))+
  	geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)

&amp;gt; p1+ ggtitle(&quot;Employed in Malaysia (1982-2014)&quot;)+
  	xlab(&quot;&quot;)+ylab(&quot;Employed&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp1.png&quot; alt=&quot;boxplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-4: Boxplot for outliers detected in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p2+ ggtitle(&quot;Labour Force in Malaysia (1982-2014)&quot;)+
  	xlab(&quot;&quot;)+ylab(&quot;Labour Force&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp2.png&quot; alt=&quot;boxplot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Boxplot for outliers detected in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p3+ ggtitle(&quot;Outside Labour Force in Malaysia (1982-2014)&quot;)+
  	xlab(&quot;&quot;)+ylab(&quot;Outside Labour Force&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp3.png&quot; alt=&quot;boxplot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-6: Boxplot for outliers detected in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Outlier Treatment&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One of the method is to derive a subset to remove the outliers. After, several trials of plotting boxplots, we found that variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; when less than or equal to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1600&lt;/code&gt; generates no outliers. So, we subset the data frame and call it as, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;subst.data.3&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; subst.data.3&amp;lt;- subset(df.cmplt, 
                  (LabrFrc&amp;lt;=1200 &amp;amp; LabrFrcPerct&amp;gt;=60 &amp;amp; LabrFrcPerct &amp;lt;=70) &amp;amp; 
                    (UnempRatePerct&amp;gt;=2.5 &amp;amp; UnempRatePerct&amp;lt;=5.0)
&amp;gt; dim(subst.data.3)
[1] 221   7  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We then plot this new data frame devoid of outliers as shown in Fig-7,8,9.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p1&amp;lt;-ggplot(data= subst.data.3, aes(x=&quot;&quot;, y=Employed))+
  geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)
&amp;gt; p2&amp;lt;-ggplot(data= subst.data.3, aes(x=&quot;&quot;, y=LabrFrc))+
  geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)
&amp;gt; p3&amp;lt;-ggplot(data= subst.data.3, aes(x=&quot;&quot;, y=OutLabrFrc))+
  geom_boxplot(outlier.size=2,outlier.colour=&quot;red&quot;)

p1+ ggtitle(&quot;Employed in Malaysia (1982-2014)&quot;)+
  xlab(&quot;&quot;)+ylab(&quot;Employed&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp4.png&quot; alt=&quot;boxplot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Boxplot with outliers treated in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p2+ ggtitle(&quot;Labour Force in Malaysia (1982-2014)&quot;)+
  	xlab(&quot;&quot;)+ylab(&quot;Labour Force&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp5.png&quot; alt=&quot;boxplot5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-8: Boxplot with outliers treated in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; p3+ ggtitle(&quot;Outside Labour Force in Malaysia (1982-2014)&quot;)+
  	xlab(&quot;&quot;)+ylab(&quot;Outside Labour Force&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp6.png&quot; alt=&quot;boxplot6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-9: Boxplot with outliers treated in variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;A simple and easy way to plot multiple plots is to adjust the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;par&lt;/code&gt; option. We show this as follows;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; par(mfrow=c(1,5),col.lab=&quot;blue&quot;, fg=&quot;indianred&quot;) # divide the screen into 1 row and five columns
&amp;gt; for(i in 3:7){
...  boxplot(subst.data.2[,i], main=names(subst.data.3[i]))
... }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp7.png&quot; alt=&quot;boxplot7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-10: Easy alternative method to plot multiple boxplot with outliers&lt;/p&gt;

&lt;p&gt;As is evident in Fig-10, the variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt; show clear indications of outliers. Subsequently, in Fig-11, we show multiple boxplots with outliers treated.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; par(mfrow=c(1,5)) # divide the screen into 1 row and four columns
&amp;gt; for(i in 3:7){
...   boxplot(subst.data.3[,i], main=names(subst.data.3[i]))
... }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-bxp8.png&quot; alt=&quot;boxplot8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-11: Multiple boxplot with outliers treated&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Data type conversion&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For subsequent data analytical activities, we converted the factor data type of the variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;State&lt;/code&gt; to numeric. Note, there were 17 levels in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;State&lt;/code&gt; variable.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; table(df.cmplt$State)

        Johor             Kedah          Kelantan          Malaysia            Melaka   Negeri Sembilan 
            7                19                12                 0                 8                28 
       Pahang             Perak            Perlis      Pulau Pinang             Sabah           Sarawak 
           26                12                 7                 7                 4                11 
     Selangor        Terengganu        W.P Labuan W.P. Kuala Lumpur     W.P.Putrajaya 
            4                13                16                20                27  

&amp;gt; df.cmplt$State&amp;lt;-as.factor(gsub(&quot;W.P.Putrajaya&quot;,&quot;Putrajaya&quot;, df.cmplt$State,ignore.case=T))
&amp;gt; df.cmplt$State&amp;lt;-as.factor(gsub(&quot;W.P. Kuala Lumpur&quot;,&quot;Kuala Lumpur&quot;, df.cmplt$State,ignore.case=T))
&amp;gt; df.cmplt$State&amp;lt;-as.factor(gsub(&quot;W.P Labuan&quot;,&quot;Labuan&quot;, df.cmplt$State,ignore.case=T))
&amp;gt; df.cmplt$State&amp;lt;- as.numeric(df.cmplt$State)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;D. Correlation Detection &amp;amp; Treatment&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Detecting skewed variables&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A variable is considered, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;highly skewed&lt;/code&gt; if its absolute value is greater than 1. A variable is considered, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;moderately skewed&lt;/code&gt; if its absolute value is greater than 0.5.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;skewedVars &amp;lt;- NA
&amp;gt; library(moments) # for skewness function
for(i in names(subst.data.3)){
  	if(is.numeric(subst.data.3[,i])){
		if(i != &quot;UnempRatePerct&quot;){
  			# Enters this block if variable is non-categorical
  			skewVal &amp;lt;- skewness(subst.data.3[,i])
  			print(paste(i, skewVal, sep = &quot;: &quot;))
  			if(abs(skewVal) &amp;gt; 0.5){
    			skewedVars &amp;lt;- c(skewedVars, i)
  				}
			}
  			}
	}    

[1] &quot;Year: -0.0966073203178181&quot;
[1] &quot;State: 0&quot;
[1] &quot;Employed: 4.02774976187303&quot;
[1] &quot;LabrFrc: 4.00826453293672&quot;
[1] &quot;LabrFrcPerct: 0.576284963607043&quot;
[1] &quot;OutLabrFrc: 4.03480268085273&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We find that the variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt; are highly skewed.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Skewed variable treatment&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Post identifying the skewed variables, we proceed to treating them by taking the log transformation. But, first we rearrange/reorder the columns for simplicity;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ## reorder the columns in df.cmplt data frame
&amp;gt; df.cmplt&amp;lt;- df.cmplt[c(1:2,4:5,3,6:7)]
&amp;gt; str(df.cmplt)
&apos;data.frame&apos;:	544 obs. of  7 variables:
 	$ Year          : num  1982 1983 1984 1985 1986 ...
 	$ State         : num  6 6 6 6 6 6 6 6 6 6 ...
 	$ UnempRatePerct: num  3.4 3.8 5 5.6 7.4 7.3 7.2 5.7 4.5 3.7 ...
 	$ LabrFrcPerct  : num  64.8 65.6 65.3 65.7 66.1 66.5 66.8 66.2 66.5 65.9 ...
 	$ Employed      : num  5249 5457 5567 5653 5760 ...
 	$ LabrFrc       : num  5431 5672 5862 5990 6222 ...
 	$ OutLabrFrc    : num  2945 2969 3120 3125 3188 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next, we treat the skewed variables by log base 2 transformation, given as follows;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; # Log transform the skewed variables
&amp;gt; df.cmplt.norm&amp;lt;-df.cmplt
&amp;gt; df.cmplt.norm[,3:7]&amp;lt;- log(df.cmplt[3:7],2) # where 2 is log base 2
&amp;gt; for(i in names(df.cmplt.norm)){
...   if(is.numeric(df.cmplt.norm[,i])){
...     if(i != &quot;UnempRatePerct&quot;){
...       # Enters this block if variable is non-categorical
...       skewVal &amp;lt;- skewness(df.cmplt.norm[,i])
...       print(paste(i, skewVal, sep = &quot;: &quot;))
...       if(abs(skewVal) &amp;gt; 0.5){
...         skewedVars &amp;lt;- c(skewedVars, i)
...       }
...     }
...   }
... }
[1] &quot;Year: -0.0966073203178181&quot;
[1] &quot;State: 0&quot;
[1] &quot;LabrFrcPerct: 0.252455838759805&quot;
[1] &quot;Employed: -0.222298401708258&quot;
[1] &quot;LabrFrc: -0.210048778006162&quot;
[1] &quot;OutLabrFrc: -0.299617325738179&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As we can see now, the skewed variables are now normalized.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Correlation detection&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We now checked for variables with high correlations to each other. Correlation measures the relationship between two variables. When two variables are so highly correlated that they explain each other (to the point that one can predict the variable with the other), then we have &lt;em&gt;collinearity&lt;/em&gt; (or &lt;em&gt;multicollinearity&lt;/em&gt;) problem. Therefore, its is important to treat collinearity problem. Let us now check, if our data has this problem or not.&lt;/p&gt;

&lt;p&gt;Again, it is important to note that correlation works only for continuous variables. We can calculate the correlations by using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cor()&lt;/code&gt; as shown;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; correlations&amp;lt;- cor(df.cmplt.norm)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We then plotted the correlations shown in Fig-12. For this, we used the package &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;corrplot&lt;/code&gt;;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(corrplot)
&amp;gt; corrplot(correlations, method = &quot;number&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-corplot.png&quot; alt=&quot;corplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-12: Correlation plot&lt;/p&gt;

&lt;p&gt;As we can see from Fig-12, there are high correlations between variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed - LaborForce&lt;/code&gt;; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed - OutsideLaborForce&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LaborForce - OutsideLaborForce&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Multicollinearity&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Multicollinearity occurs because two (or more) variables are related or they measure the same thing. If one of the variables in your model doesn’t seem essential to your model, removing it may reduce multicollinearity. Examining the correlations between variables and taking into account the importance of the variables will help you make a decision about what variables to drop from the model.&lt;/p&gt;

&lt;p&gt;There are several methods for dealing with multicollinearity. The simplest is to construct a correlation matrix and corresponding scatterplots. If the correlations between predictors approach 1, then multicollinearity might be a problem. In that case, one can make some educated guesses about which predictors to retain in the analysis.&lt;/p&gt;

&lt;p&gt;Use, &lt;em&gt;Variance Inflation Factor (VIF)&lt;/em&gt;. The VIF is a metric computed for every &lt;em&gt;X&lt;/em&gt; variable that goes into a linear model. If the VIF of a variable is high, it means the information in that variable is already explained by the other &lt;em&gt;X&lt;/em&gt; variables present in the given model, which means, more redundant is that variable. According to some references, if the VIF is too large(more than 5 or 10), we consider that the multicollinearity is existent. So, &lt;strong&gt;lower the VIF (&amp;lt;2) the better it is&lt;/strong&gt;. VIF for a X var is calculated as; &lt;img src=&quot;https://duttashi.github.io/images/vif.png&quot; alt=&quot;vif0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;where, Rsq is the Rsq term for the model with given X as response against all other Xs that went into the model as predictors.&lt;/p&gt;

&lt;p&gt;Practically, if two of the X′s have high correlation, they will likely have high VIFs. Generally, VIF for an X variable should be less than 4 in order to be accepted as not causing multicollinearity. The cutoff is kept as low as 2, if you want to be strict about your X variables. Now, assume we want to predict &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePect&lt;/code&gt; (unemployment rate percent) from rest of the predictors, so we regress it over others as given below in the equation; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt; mod&amp;lt;- lm(Employed~., data=df.cmplt)&lt;/code&gt;. We then calculate the VIF for this model by using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vif()&lt;/code&gt; method from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DAAG&lt;/code&gt; library, and find that the variables &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;State&lt;/code&gt; are correlated.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; vfit&amp;lt;-vif(mod)
&amp;gt; sqrt(vif(mod)) &amp;gt; 2
      Year          State UnempRatePerct   LabrFrcPerct        LabrFrc     OutLabrFrc 
     FALSE          FALSE          FALSE           TRUE           TRUE           TRUE  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Multicollinearity Treatment&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Principal Component Analysis (PCA): unsupervised data reduction method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Principal Component Analysis (PCA) reduces the number of predictors to a smaller set of uncorrelated components. Remember, the PCA method can only be applied to continuous variables.&lt;/p&gt;

&lt;p&gt;We aim to find the components which explain the maximum variance. This is because, we want to retain as much information as possible using these components. So, higher is the explained variance, higher will be the information contained in those components.&lt;/p&gt;

&lt;p&gt;The base R function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;princomp()&lt;/code&gt; from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stats package&lt;/code&gt; is used to conduct the PCA test. By default, it centers the variable to have mean equals to zero. With parameter scale. = T, the variables (or the predictors) can be normalized to have standard deviation equals to 1. Since, we have already normalized the variables, we will not be using the scale option.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(stats) # for princomp()
&amp;gt; df.cmplt.norm.pca&amp;lt;- princomp(df.cmplt.norm, cor = TRUE)
&amp;gt; summary(df.cmplt.norm.pca)

Importance of components:
			Comp.1    	Comp.2    Comp.3    Comp.4     Comp.5        Comp.6       Comp.7
Standard 
deviation   1.7588184 1.2020620 1.0730485 0.8807122 0.73074799 0.02202556837 0.0063283251
Proportion 
of Variance 0.4419203 0.2064219 0.1644904 0.1108077 0.07628466 0.00006930367 0.0000057211
Cumulative 
Proportion  0.4419203 0.6483422 0.8128326 0.9236403 0.99992498 0.99999427890 1.0000000000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;From the above summary, we can see that the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; explains &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;44% variance&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.2&lt;/code&gt; explains &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;20% variance&lt;/code&gt; and so on. Also we can see that Comp.1 to Comp.5 have the highest standard deviation which indicates the number of components to retain (for further data analysis) as they explain maximum variance in the data.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Plotting the PCA (biplot) components&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A PCA would not be complete without a bi-plot. In a biplot, the arrows point in the direction of increasing values for each original variable. The closeness of the arrows means that the variables are highly correlated. In Fig-13, notice the closeness of the arrows for variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; indicates strong correlation. Again, notice the mild closeness of arrows for variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;State&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt; indicate mild correlation. Finally, notice the perpendicular distance between variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt; that indicates no correlation.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; # Plotting
&amp;gt; biplot(df.cmplt.norm.pca)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-biplot.png&quot; alt=&quot;biplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-13: Biplot for PCA components&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Determining the contribution (%) of each parameter in the calculated PCA&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, the important question is how to determine the percentage of contribution (of each parameter) to each PC? simply put, how to know that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; consist of say 35% of parameter1, 28% of parameter2 and so on.&lt;/p&gt;

&lt;p&gt;The answer lies in computing the proportion of variance explained by each component, we simply divide the variance by sum of total variance. Thus we see that the first principal component &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; explains 44% of variance. The second component &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.2&lt;/code&gt; explains 20% variance, the third component &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.3&lt;/code&gt; explains 16% variance and so on.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; std_dev&amp;lt;- df.cmplt.norm.pca$sdev
&amp;gt; df.cmplt.norm.pca.var&amp;lt;- std_dev^2
&amp;gt; round(df.cmplt.norm.pca.var)
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7 
	3      1      1      1      1      0      0 
#proportion of variance explained
prop_varex &amp;lt;- df.cmplt.norm.pca.var/sum(df.cmplt.norm.pca.var)
 	&amp;gt; round(prop_varex,3)
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7 
 	0.442  0.206  0.164  0.111  0.076  0.000  0.000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Although, we have identified that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.5&lt;/code&gt; explain the maximum variance in the data but we use a scree plot for a visual identification too. A scree plot is used to access components or factors which explains the most of variability in the data. The cumulative scree plot in Fig-14, shows that 5 components explain about 99% of variance in the data. Therefore, in this case, we’ll select number of components as 05 [PC1 to PC5] and proceed to the modeling stage. For modeling, we’ll use these 05 components as predictor variables and follow the subsequent analysis.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; plot(cumsum(prop_varex), xlab = &quot;Principal Component&quot;,
...     ylab = &quot;Cumulative Proportion of Variance Explained&quot;,
...      type = &quot;b&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-pca-screeplot.png&quot; alt=&quot;screeplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-14: Cumulative Scree Plot for PCA&lt;/p&gt;

&lt;p&gt;Now, we know that there are at least 5 components or variables in this dataset that exhibit maximum variance. Let us now see, what variables are these;&lt;/p&gt;

&lt;p&gt;It is worth mentioning here that the principal components are located in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loadings&lt;/code&gt; component of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;princomp()&lt;/code&gt; function. And if using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prcomp&lt;/code&gt; function, than the principal components are located in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rotation&lt;/code&gt; component.&lt;/p&gt;

&lt;p&gt;Let’s now look at the first 5 PCA in first 5 rows&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; df.cmplt.norm.pca$loadings[1:5,1:5]
                Comp.1      Comp.2      Comp.3      Comp.4      Comp.5
Year           -0.15571810  0.59924346 -0.33488893 -0.17721252  0.68781319
State          -0.01783084 -0.31630022 -0.66890937 -0.63612401 -0.21804005
UnempRatePerct  0.12931025 -0.60105660  0.34584708 -0.29005678  0.64662656
LabrFrcPerct   -0.12043003 -0.40426976 -0.53298376  0.68221483  0.24047888
Employed       -0.56396551 -0.08143999  0.07256198 -0.01140229 -0.02185788
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We now demonstrate the relative contribution of each loading per column and express it as as a proportion of the column (loading) sum, taking care to use the absolute values to account for negative loading. See, this &lt;a href=&quot;http://stackoverflow.com/questions/12760108/principal-components-analysis-how-to-get-the-contribution-of-each-paramete&quot;&gt;SO solution&lt;/a&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; load &amp;lt;- with(df.cmplt.norm.pca, unclass(loadings))
&amp;gt; round(load,3)

               Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7
Year           -0.156  0.599 -0.335 -0.177  0.688  0.004  0.000
State          -0.018 -0.316 -0.669 -0.636 -0.218 -0.001  0.000
UnempRatePerct  0.129 -0.601  0.346 -0.290  0.647 -0.006 -0.010
LabrFrcPerct   -0.120 -0.404 -0.533  0.682  0.240  0.121 -0.003
Employed       -0.564 -0.081  0.073 -0.011 -0.022 -0.423 -0.700
LabrFrc        -0.563 -0.091  0.077 -0.015 -0.012 -0.399  0.714
OutLabrFrc     -0.556 -0.035  0.160 -0.118 -0.053  0.804 -0.014
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And, this final step then yields the proportional contribution to the each principal component.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; aload &amp;lt;- abs(load) ## save absolute values
&amp;gt; round(sweep(aload, 2, colSums(aload), &quot;/&quot;),3)
               Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7
Year            0.074  0.282  0.153  0.092  0.366  0.002  0.000
State           0.008  0.149  0.305  0.330  0.116  0.001  0.000
UnempRatePerct  0.061  0.282  0.158  0.150  0.344  0.003  0.007
LabrFrcPerct    0.057  0.190  0.243  0.353  0.128  0.069  0.002
Employed        0.268  0.038  0.033  0.006  0.012  0.241  0.485
LabrFrc         0.267  0.043  0.035  0.008  0.006  0.227  0.495
OutLabrFrc      0.264  0.016  0.073  0.061  0.028  0.457  0.010
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We already know that there are five components/variables with maximum variance in them. Now all that is left is to determine what are these variables. This can be determined easily from the above result. Remember, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; shows variables with maximum variance, followed by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.2&lt;/code&gt; and so on. Now, in the column, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Comp.1&lt;/code&gt; we keep only those variables that are greater than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt;. Therefore, the variables to keep are, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; vars_to_retain&amp;lt;- c(&quot;Year&quot;,&quot;Employed&quot;,&quot;UnempRatePerct&quot;,&quot;LabrFrc&quot;,&quot;LabrFrcPerct&quot;,&quot;OutLabrFrc&quot;)
&amp;gt; newdata&amp;lt;- df.cmplt.norm[,vars_to_retain]
&amp;gt; str(newdata)
&apos;data.frame&apos;:	544 obs. of  6 variables:
 	$ Year          : num  1982 1983 1984 1985 1986 ...
 	$ Employed      : num  12.4 12.4 12.4 12.5 12.5 ...
 	$ UnempRatePerct: num  1.77 1.93 2.32 2.49 2.89 ...
 	$ LabrFrc       : num  12.4 12.5 12.5 12.5 12.6 ...
 	$ LabrFrcPerct  : num  6.02 6.04 6.03 6.04 6.05 ...
 	$ OutLabrFrc    : num  11.5 11.5 11.6 11.6 11.6 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Note: We will be building the model on the normalized data stored in the variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df.cmplt.norm&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;4-predictive-data-analytics&quot;&gt;4. Predictive Data Analytics&lt;/h3&gt;

&lt;p&gt;In this section, we will discuss various approaches applied to model building, predictive power and their trade-offs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A. Creating the train and test dataset&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We now divide the data into 75% training set and 25% testing set. We also created a root mean square evaluation function for model testing.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ratio = sample(1:nrow(newdata), size = 0.25*nrow(newdata))
&amp;gt; test.data = newdata[ratio,] #Test dataset 25% of total
&amp;gt; train.data = newdata[-ratio,] #Train dataset 75% of total
&amp;gt; dim(train.data)
[1] 408   4
&amp;gt; dim(test.data)
[1] 136  4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;B. Model Building - Evaluation Method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We created a custom root mean square function that will evaluate the performance of our model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Evaluation metric function

RMSE &amp;lt;- function(x,y)
	{
  			a &amp;lt;- sqrt(sum((log(x)-log(y))^2)/length(y))
  			return(a)
	}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;C. Model Building - Regression Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Regression is a supervised technique, a statistical process for estimating the relationship between a response variable and one or more predictors. Often the outcome variable is also called the response variable or the dependent variable and the and the risk factors and confounders are called the predictors, or explanatory or independent variables. In regression analysis, the dependent variable is denoted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; and the independent variables are denoted by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The response variable for this study is continuous in nature therefore the choice of regression model is most appropriate.&lt;/p&gt;

&lt;p&gt;Our multiple linear regression model for the response variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; reveals that the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; are the most significant predictors such that if included in the model will enhance the predictive power of the response variable. The remaining predictors do not contribute to the regression model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; linear.mod&amp;lt;- lm(Employed~., data = train.data)
&amp;gt; summary(linear.mod)

Call:
lm(formula = Employed ~ ., data = train.data)

Residuals:
  Min        1Q    Median        3Q       Max 
-0.060829 -0.002058  0.001863  0.004615  0.184889 

Coefficients:
              	Estimate  	Std. Error 		t value 	Pr(&amp;gt;|t|)    
(Intercept)    -0.38447474  0.34607122  	-1.111    	0.267    
Year            0.00009844  0.00008295   	1.187    	0.236    
UnempRatePerct -0.03869329  0.00119011 		-32.512   	&amp;lt;2e-16 ***
LabrFrc         0.97901237  0.01634419  	59.900   	&amp;lt;2e-16 ***
LabrFrcPerct    0.03468488  0.04784967   	0.725    	0.469    
OutLabrFrc      0.02223528  0.01624485   	1.369    	0.172    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.01452 on 402 degrees of freedom
Multiple R-squared:  0.9999,	Adjusted R-squared:  0.9999 
F-statistic: 1.223e+06 on 5 and 402 DF,  p-value: &amp;lt; 2.2e-16
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The t value also known as the t-test which is positive for predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt; indicating that these predictors are associated with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt;. A larger t-value indicates that that it is less likely that the coefficient is not equal to zero purely by chance.&lt;/p&gt;

&lt;p&gt;Again, as the p-value for variables, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; is less than 0.05 they are both statistically significant in the multiple linear regression model for the response variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; . The model’s, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p-value: &amp;lt; 2.2e-16&lt;/code&gt; is also lower than the statistical significance level of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt;, this indicates that we can safely reject the null hypothesis that the value for the coefficient is zero (or in other words, the predictor variable has no explanatory relationship with the response variable).&lt;/p&gt;

&lt;p&gt;We tested this model using the root mean square evaluation method. The RMSE is 0.003.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; RMSE0&amp;lt;- RMSE(predict, test.data$Employed)
&amp;gt; RMSE0&amp;lt;- round(RMSE0, digits = 3)
&amp;gt; RMSE0
[1] 0.003
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-residuals.png&quot; alt=&quot;residuals&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-14: Residuals vs Fitted values for the response variable, “Employed”&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; actuals_preds &amp;lt;- data.frame(cbind(actuals=test.data$Employed, predicteds=predict)) # make actuals_predicteds dataframe.
&amp;gt; correlation_accuracy &amp;lt;- cor(actuals_preds)
&amp;gt; correlation_accuracy # 99%
	         actuals 	predicteds
actuals    	1.0000000  	0.9999386
predicteds 	0.9999386  	1.0000000

&amp;gt; min_max_accuracy &amp;lt;- mean (apply(actuals_preds, 1, min) / apply(actuals_preds, 1, max))
&amp;gt; min_max_accuracy
[1] 0.9988304
&amp;gt; mape &amp;lt;- mean(abs((actuals_preds$predicteds - actuals_preds$actuals))/actuals_preds$actuals)
&amp;gt; mape
[1] 0.001170885
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The AIC and the BIC model diagnostics values are low too. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt; AIC(linear.mod) [1] -2287.863&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt; BIC(linear.mod) [1] -2259.784&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D. Model Building - other supervised algorithms&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Regression Tree method&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The regression tree method gives an accuracy of 0.037&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(rpart)
&amp;gt; model &amp;lt;- rpart(Employed ~., data = train.data, method = &quot;anova&quot;)
&amp;gt; predict &amp;lt;- predict(model, test.data)
&amp;gt; RMSE1 &amp;lt;- RMSE(predict, test.data$Employed)
&amp;gt; RMSE1 &amp;lt;- round(RMSE1, digits = 3)
&amp;gt; RMSE1
[1] 0.037
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;Random Forest method&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The random forest method gives an accuracy of 0.009. Look at the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;IncNodePurity plot&lt;/code&gt; in Fig-15. We see that important predictors are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt; ,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabourFrcPerct&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(randomForest)
&amp;gt; model.forest &amp;lt;- randomForest(Employed ~., data = train.data, method = &quot;anova&quot;,
...                              ntree = 300,
...                              mtry = 2, #mtry is sqrt(6)
...                              replace = F,
...                              nodesize = 1,
...                              importance = T)
&amp;gt; varImpPlot(model.forest)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Labor-vifplot.png&quot; alt=&quot;vifplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-15: VIF plot&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; prediction &amp;lt;- predict(model.forest,test.data)
&amp;gt; RMSE3 &amp;lt;- sqrt(mean((log(prediction)-log(test.data$Employed))^2))
&amp;gt; round(RMSE3, digits = 3)
[1] 0.009
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;D.1 Model Performance comparison&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As a rule of thumb, smaller the RMSE value better is the model. See this &lt;a href=&quot;http://stats.stackexchange.com/questions/56302/what-are-good-rmse-values&quot;&gt;SO post&lt;/a&gt;. So its feasible to state that the multiple linear regression model yields the best predictive performance as it has the lowest RMSE value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.003&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Multiple Linear Regression RMSE: 0.003&lt;/p&gt;

&lt;p&gt;Random Forest RMSE:  0.009&lt;/p&gt;

&lt;p&gt;Regression Tree RMSE: 0.037&lt;/p&gt;

&lt;h3 id=&quot;5-conclusion&quot;&gt;5. Conclusion&lt;/h3&gt;

&lt;p&gt;In this analytical study, we have explored three supervised learning models to predict the factors contributing to an accurate prediction of employed persons by state in Malaysia. Our multiple linear regression model for the response variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Employed&lt;/code&gt; reveals that the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UnempRatePerct&lt;/code&gt;and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrc&lt;/code&gt; are the most significant predictors such that if included in the model will enhance the predictive power of the response variable. The other predictors such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OutLabrFrc&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LabrFrcPerct&lt;/code&gt;does not contribute to the regression model. This model gives an &lt;strong&gt;accuracy of 99%&lt;/strong&gt; on unseen data and has the lowest RMSE of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.003&lt;/code&gt; as compared to the other supervised learning methods. Again, its worthwhile to mention here the reason for such a high accuracy of the predictive model because we chose the correct model for the response variable and ensured to carry out a rigorous data preprocessing and modeling activities.&lt;/p&gt;

&lt;p&gt;The complete code is listed on my Github repository in &lt;a href=&quot;https://github.com/duttashi/learnr/blob/master/scripts/Full%20Case%20Studies/CaseStudy-MY-LaborForce.R&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Predicting rubber plantation yield- A regression analysis approach]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/predicting-rubber-yield-case-study/" />
  <id>https://duttashi.github.io/blog/predicting-rubber-yield-case-study</id>
  <published>2017-02-09T00:00:00+00:00</published>
  <updated>2017-02-09T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;

&lt;p&gt;Malaysia is the leading producer of natural rubber in the world. Being a leader in the production of natural rubber, Malaysia is contributing around 46% of total rubber production in the world. The rubber plantation was started in Malaysia in 1877.&lt;/p&gt;

&lt;p&gt;The favorable rubber plantation climate requires a mean temperature of 27°C, never falling below 22°C. It also requires heavy rainfall above 200 cm. with no drought including deep rich soils with good drainage preferably brittle, well-oxidized and acidic in reaction. Sufficient supply of labour is an important factor for the collection and plantation of rubber over large holdings.&lt;/p&gt;

&lt;p&gt;In Malaysia, rubber can grow anywhere, because of the suitability of climate and top soil; but most of the rubber estates are located in the western coastal plains of Malaysia. The plantation in coastal zone gets the benefit of nearest port for its export. Yet very low areas are avoided in order not to suffer from stagnation of water. The greatest production is in it’s Johor State of Southern Malaysia. Over here the rubber cultivation occupies about 4-2 million acres or about 66% of the total cultivated area in the nation.&lt;/p&gt;

&lt;p&gt;This report consist of the following sections;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Business/Research Question&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Data Source&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Making data management decisions&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

  	A. Exploratory Data Analysis (EDA)

  	* Data preprocessing (rename and round)

  	* Data preprocessing (joining the tables)

  	B. Data visualization

  	C. Data transformation

 	* Skewed variable treatment

  	D. Feature importance

&lt;ol&gt;
  &lt;li&gt;Predictive Data Analytics&lt;/li&gt;
&lt;/ol&gt;

 	A. Creating the train and test dataset

  	B. Model Building - Evaluation Method

  	C. Model Building - Regression Analysis

  	D. Model Performance on various supervised algorithms

  	* Regression Tree method

  	* Random Forest method

  	D.1. Comparison of Predictive Model Performance

  	E. Model Diagnostics

  	* The p Value: Checking for statistical significance

  	* Check the AIC and BIC

  	* The R-Squared and Adjusted R-Squared

  	* How do you know if the model is best fit for the data?

  	* Residuals

  	F. Model Inference Summary

  	G. Calculate prediction accuracy and error rates

&lt;ol&gt;
  &lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;References&lt;/p&gt;

&lt;h3 id=&quot;1-businessresearch-question&quot;&gt;1. Business/Research Question&lt;/h3&gt;

&lt;p&gt;Determine the factors which contribute to accurately predicting high rubber yield per kg based on historical rubber plantation data.&lt;/p&gt;

&lt;h3 id=&quot;2-data-source&quot;&gt;2. Data Source&lt;/h3&gt;

&lt;p&gt;The data comes from the Department of Statistics, Malaysia. This is an open data source portal and the data files can be accessed from their official &lt;a href=&quot;http://www.dosm.gov.my/v1/index.php?r=column3/accordion&amp;amp;menu_id=aHhRYUpWS3B4VXlYaVBOeUF0WFpWUT09&quot;&gt;website&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;3-making-data-management-decisions&quot;&gt;3. Making data management decisions&lt;/h3&gt;

&lt;p&gt;Initially, the dataset consisted of six comma-separated files. Each file provided data (from year 1965 to year 2014) on factors like number of rubber estates in Malaysia, total planted area, production of natural rubber, tapped area, yield per hectare and total number of paid employees in the rubber estate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A. Exploratory Data Analysis (EDA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each data file had the same dimension of 51 rows in 2 continuous variables. On knowing that each of the six-data file had the same dimensions, it confirmed our initial assumption that the actual dataset was divided into six separate files.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; df1&amp;lt;- read.csv(&quot;data/rubberestate/rubber-paidemployee.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE) 
&amp;gt; df2&amp;lt;- read.csv(&quot;data/rubberestate/rubber-plantedarea.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE) 
&amp;gt; df3&amp;lt;- read.csv(&quot;data/rubberestate/rubber-production.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE) 
&amp;gt; df4&amp;lt;- read.csv(&quot;data/rubberestate/rubber-taparea.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE) 
&amp;gt; df5&amp;lt;- read.csv(&quot;data/rubberestate/rubber-yield.csv&quot;, header = TRUE, sep = &quot;,&quot;, stringsAsFactors = FALSE)

&amp;gt; dim(df1)
[1] 51  2
&amp;gt; dim(df2)
[1] 51  2
&amp;gt; dim(df3)
[1] 51  2
&amp;gt; dim(df4)
[1] 51  2
&amp;gt; dim(df5)
[1] 51  2
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Another peculiarity found was the column headings were too long for each of the data file. We decided to merge the six data files into a single dataset and rename the column names to short succinct names. For data analysis we are using the R programming language (Ihaka &amp;amp; Gentleman, 1996).&lt;/p&gt;

&lt;p&gt;Besides, we also found that column value for number of employees was expressed in decimals! Now, there cannot be 2.5 employees so we decided to round all such values.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; names(df1)
[1] &quot;Year&quot;                                                             
[2] &quot;Total.Number.of.Paid.Employee.During.the.Last.Pay.Period..Estate.&quot;
&amp;gt; names(df2) # additional space after column names. do formatting
[1] &quot;Year&quot;                                 &quot;Planted.Area..Estate....000..Hectare&quot;
&amp;gt; names(df3)
[1] &quot;Year&quot;                             &quot;Production..Estate....000..Tonne&quot;
&amp;gt; names(df4)
[1] &quot;Year&quot;                                &quot;Tapped.Area..Estate....000..Hectare&quot;
&amp;gt; names(df5)
[1] &quot;Year&quot;                            &quot;Yeild.per.Hectare..Estate...Kg.&quot;

&amp;gt; head(df1) # You cannot have employees in decimals. Round this variable
  Year Total.Number.of.Paid.Employee.During.the.Last.Pay.Period..Estate.

1 1965                                                             262.1

2 1966                                                             258.4

3 1967                                                             235.4

4 1968                                                             209.8

5 1969                                                             212.7

6 1970                                                             205.4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So, we first decided to perform basic data management tasks that were identified above. For this we use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rename&lt;/code&gt; function in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plyr&lt;/code&gt; library (Wickham, 2015).&lt;/p&gt;

&lt;p&gt;You will need to load this library in the R environment first before you can use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rename&lt;/code&gt; function.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Data preprocessing (rename and round)&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; # Basic Data Management
&amp;gt; # Renaming the column name
&amp;gt; library(plyr)
&amp;gt; df1&amp;lt;- rename(df1, c(&quot;Total.Number.of.Paid.Employee.During.the.Last.Pay.Period..Estate.&quot; = &quot;TotalPaidEmployee&quot;))
&amp;gt; df2&amp;lt;-rename(df2, c(&quot;Planted.Area..Estate....000..Hectare&quot; = &quot;AreaPlantedHect&quot;))
&amp;gt; df3&amp;lt;-rename(df3, c(&quot;Production..Estate....000..Tonne&quot; = &quot;ProduceTonne&quot;))
&amp;gt; df4&amp;lt;-rename(df4, c(&quot;Tapped.Area..Estate....000..Hectare&quot; = &quot;TapAreaHect&quot;))
&amp;gt; df5&amp;lt;-rename(df5, c(&quot;Yeild.per.Hectare..Estate...Kg.&quot; = &quot;YieldperHectKg&quot;))
&amp;gt; # Rounding the column value for TotalPaidEmployee because there can’t be  example 2.5 employees
&amp;gt; df1$TotalPaidEmployee&amp;lt;- round(df1$TotalPaidEmployee)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Data pre-processing (joining the tables)&lt;/p&gt;

    &lt;p&gt;We also notice that all the six data files have a common column which is, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;. So, we now join the files on this common column and save the resultant in a master data frame called, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df.master&lt;/code&gt;. This process is known as the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inner join&lt;/code&gt;.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &amp;gt; # Inner Join the data frames on common column
  &amp;gt; df.m1&amp;lt;- merge(df1,df2, by=&quot;Year&quot;)
  &amp;gt; df.m2&amp;lt;- merge(df3,df4, by=&quot;Year&quot;)
  &amp;gt; df.m3&amp;lt;- merge(df.m2, df5, by=&quot;Year&quot;)
  &amp;gt; df.master&amp;lt;- merge(df.m1, df.m3, by=&quot;Year&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;

    &lt;p&gt;Now, that the dataset is ready for inspection, the first step would be to summarize it using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;summary&lt;/code&gt; function call.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &amp;gt; summary(df.master)
	Year      TotalPaidEmployee AreaPlantedHect   ProduceTonne     TapAreaHect     YieldperHectKg
   	Min.   :1965   Min.   : 10.00    Min.   : 49.70   Min.   : 53.00   Min.   : 38.50   Min.   : 937  
   	1st Qu.:1977   1st Qu.: 16.75    1st Qu.: 87.47   1st Qu.: 88.62   1st Qu.: 64.62   1st Qu.:1304  
   	Median :1990   Median :105.00    Median :354.85   Median :414.70   Median :307.05   Median :1381  
   	Mean   :1990   Mean   :103.62    Mean   :352.94   Mean   :364.27   Mean   :277.42   Mean   :1347  
   	3rd Qu.:2002   3rd Qu.:174.50    3rd Qu.:554.25   3rd Qu.:580.98   3rd Qu.:433.40   3rd Qu.:1420  
   	Max.   :2014   Max.   :262.00    Max.   :788.50   Max.   :684.60   Max.   :542.30   Max.   :1525  
   	NA&apos;s   :1      NA&apos;s   :1         NA&apos;s   :1        NA&apos;s   :1        NA&apos;s   :1        NA&apos;s   :1     
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We see that the minimum yield per hectare is 937 kg and the minimum area planted is 49.7 hectares. Besides, there is also one data point with missing value.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Missing data treatment&lt;/p&gt;

    &lt;p&gt;We have applied the predictive mean modeling method for missing data imputation. This method is available in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mice&lt;/code&gt; (Buuren &amp;amp; Groothuis-Oudshoorn, 2011) library. You will need to load it in the R environment first.&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &amp;gt;library(mice)
  &amp;gt; tempData &amp;lt;- mice(df.master,m=5,maxit=50,meth=&apos;pmm&apos;,seed=1234)
  &amp;gt; df.master&amp;lt;- mice::complete(tempData,1)
  &amp;gt; colSums(is.na(df.master))
  
  Year TotalPaidEmployee   AreaPlantedHect      ProduceTonne       TapAreaHect    YieldperHectKg 
          0                 0                 0                 0                 0                 0 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, the dataset is ready for visualization. This will help us in determining a research question. At this point it’s best to describe about our dataset. for this, we use the method &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;describe&lt;/code&gt; from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;psych&lt;/code&gt; library (Revelle, 2014). A basic example can be see &lt;a href=&quot;http://www.statmethods.net/stats/descriptives.html&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;B. Data visualization: visualizing data in pursuit of finding relationship between predictors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We begin the data exploration by univariate data visualization. Here, we will be using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;%&amp;gt;%&lt;/code&gt; or the pipe operator from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;magrittr&lt;/code&gt; package (Bache &amp;amp; Wickham, 2014) and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;select&lt;/code&gt; statement from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dplyr package&lt;/code&gt; (Wickham &amp;amp; Francois, 2015) to visualize all the predictors excluding Year.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(magrittr)
&amp;gt; library(dplyr)
&amp;gt; # Method 1: selecting individual predictor name
&amp;gt; boxplot(df.master %&amp;gt;%
...           select(AreaPlantedHect,YieldperHectKg,ProduceTonne,TapAreaHect,TotalPaidEmployee))
&amp;gt; # Method 2: Use the minus sign before the predictor you dont want to plot such that the remaining predictors are plotted

&amp;gt; boxplot(df.master %&amp;gt;%
...           select(-Year),
...         col = c(&quot;red&quot;,&quot;sienna&quot;,&quot;palevioletred1&quot;,&quot;royalblue2&quot;,&quot;brown&quot;),
...         ylab=&quot;Count&quot;, xlab=&quot;Predictors&quot;
...         )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-boxplot1.png&quot; alt=&quot;boxplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-1: Boxplot&lt;/p&gt;

&lt;p&gt;From Fig-1, it seems that there are some outlier’s for the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt; predictor. We will come to it later, for now, we continue exploring the data.&lt;/p&gt;

&lt;p&gt;Now, we use the line plots to determine relationships between continuous predictors.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.master)+ geom_line(aes(x=AreaPlantedHect, y=YieldperHectKg, color=”red”))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-lineplot1.png&quot; alt=&quot;lineplot1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-2: Line Plot for predictors &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;An interesting pattern is revealed in Fig-2. The &lt;em&gt;yield per hectare has a sharp decline (after 600 hectares) as plantation area increases&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Lets’ explore the remaining predictors;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.master)+ geom_line(aes(x=AreaPlantedHect, y=ProduceTonne, color=&quot;red&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-lineplot2.png&quot; alt=&quot;lineplot2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-3: Line Plot for predictors &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We see that produce increases with area but then it begins to decline after 600 hectares. There is a positive linear relationship between area planted and tap area as shown below in Fig-4.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.master)+ geom_line(aes(x=AreaPlantedHect, y=TapAreaHect, color=&quot;red&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-lineplot3.png&quot; alt=&quot;lineplot3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-4: Line Plot for predictors &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Again, in Fig-5, we notice a positive linear relationship between area planted and paid employees but there is a sharp decline at 600 hectares persists.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ggplot(df.master)+ geom_line(aes(x=AreaPlantedHect, y=TotalPaidEmployee, color=&quot;red&quot;))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-lineplot4.png&quot; alt=&quot;lineplot4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-5: Line Plot for predictors &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The evidence of strong positive linear relationship between the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; cannot be overlooked. We, cross-check this phenomenon by deducing the correlation between them.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; cor(df.master$AreaPlantedHect, df.master$TapAreaHect) # very strong positive correlation
[1] 0.9930814
&amp;gt; cor(df.master$AreaPlantedHect, df.master$ProduceTonne) # very strong positive correlation
[1] 0.9434092
&amp;gt; cor(df.master$AreaPlantedHect, df.master$TotalPaidEmployee) # very strong positive correlation, as land size increases more labour is required
[1] 0.9951871
&amp;gt; cor(df.master$AreaPlantedHect, df.master$YieldperHectKg) # negative correlation, proving the point above that the yield per hectare decreases as plantation size increases
[1] -0.5466433
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;we now have ample evidence that the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonee&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt; have a strong positive correlationship. Let’s visualize it.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; correlations&amp;lt;- cor(df.master)

&amp;gt; corrplot(correlations, method=&quot;number&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-corrplot.png&quot; alt=&quot;corrplot-1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-6: Correlation Plot for predictors and response variables.&lt;/p&gt;

&lt;p&gt;As seen in Fig-6 above, the predictors &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldPerHect&lt;/code&gt; have low positive correlation with each other; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldHect&lt;/code&gt; have a semi-strong negative correlation; others like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldPerHect&lt;/code&gt; have a strong negative correlation and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperhectKg&lt;/code&gt; have a low negative correlation with each other.&lt;/p&gt;

&lt;p&gt;We can also create a scatter plot matrix (see Fig-7) to plot correlations among the continuous predictors by using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pairs&lt;/code&gt; function from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ggplot2&lt;/code&gt; library(Wickham, 2016)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-corrplot-1.png&quot; alt=&quot;corrplot-2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Scatter plot matrix for predictor and response variable correlation&lt;/p&gt;

&lt;p&gt;We end this discussion by a simple question. Does the yield increase if the plantation area increases? Lets find this out in the following graph, see Fig-8.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library (RColorBrewer)
# We will select the first 4 colors in the Set1 palette
&amp;gt; cols&amp;lt;-brewer.pal(n=4,name=&quot;Set1&quot;)
# cols contain the names of four different colors
&amp;gt; plot(Training$AreaPlantedHect, Training$YieldperHectKg, pch=16,col=cols,
 main=&quot; Does high plantation area yield more rubber?&quot;,
 xlab = &quot;Area planted (in hectare)&quot;,
 ylab = &quot;Yield in Kg (per hectare)&quot;
 )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-plot1.png&quot; alt=&quot;plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-7: Scatter plot matrix for predictor and response variable correlation&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C. Data transformation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Skewed variable treatment&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A variable is considered ‘highly skewed’ if its absolute value is greater than 1. A variable is considered ‘moderately skewed’ if its absolute value is greater than 0.5. let’s check if any of the predictors are skewed or not.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; for(i in names(df.master)){
...   if(is.numeric(df.master[,i])){
...     if(i != &quot;YieldperHectKg&quot;){
...       # Enters this block if variable is non-categorical
...       skewVal &amp;lt;- skewness(df.master[,i])
...       print(paste(i, skewVal, sep = &quot;: &quot;))
...       if(abs(skewVal) &amp;gt; 0.5){
...         skewedVars &amp;lt;- c(skewedVars, i)
...       }
...     }
...   }
... }

[1] &quot;Year: 0.0380159253762087&quot;
[1] &quot;TotalPaidEmployee: 0.238560934226388&quot;
[1] &quot;AreaPlantedHect: 0.118115337328111&quot;
[1] &quot;ProduceTonne: -0.184114105316565&quot;
[1] &quot;TapAreaHect: -0.0526176590077839&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;There are no skewed predictors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D. Feature importance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, that we have statistically quantified the validity of the predictors, we proceed to determining the most relevant features. Such features when found will help in building a robust predictive model. We will use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Boruta&lt;/code&gt; package (Kursa &amp;amp; Rudnicki, 2010).&lt;/p&gt;

&lt;p&gt;We are interested in predicting the variable Yield per hectare in kg (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt;) therefore we will remove it from the feature selection process and perform the analysis on the remaining predictors.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(Boruta)
&amp;gt; set.seed(1234) # for code reproducibility
&amp;gt; response &amp;lt;- df.master$YieldperHectKg
&amp;gt; response &amp;lt;- df.master$YieldperHectKg
&amp;gt; bor.results &amp;lt;- Boruta(df.master,response,
...                       maxRuns=101,
...                       doTrace=0)

&amp;gt; cat(&quot;\n\nRelevant Attributes:\n&quot;)
	Relevant Attributes:
&amp;gt; getSelectedAttributes(bor.results)
[1] &quot;Year&quot;              &quot;TotalPaidEmployee&quot; &quot;AreaPlantedHect&quot;   &quot;ProduceTonne&quot;      &quot;TapAreaHect&quot;      
[6] &quot;YieldperHectKg&quot;   
&amp;gt; plot(bor.results)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-boruta.png&quot; alt=&quot;plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-8: Feature importance plot&lt;/p&gt;

&lt;p&gt;We see from Fig-8, that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Boruta&lt;/code&gt; predicts all the features to be important for building a predictive model. Let us know proceed to building the predictive model.&lt;/p&gt;

&lt;h2 id=&quot;4-predictive-data-analytics&quot;&gt;4. Predictive Data Analytics&lt;/h2&gt;

&lt;p&gt;In this section, we will discuss various approaches in model building, predictive power and their trade-offs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A.	Creating the train and test dataset&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Researchers and data practitioners have always emphasized on building a model that is intensively trained on a larger sample of the train data. Therefore, we will divide the dataset into 70% training data and 30% testing data.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ratio = sample(1:nrow(df.master), size = 0.25*nrow(df.master))
&amp;gt; Test = df.master[ratio,] #Test dataset 25% of total
&amp;gt; Training = df.master[-ratio,] #Train dataset 75% of total
&amp;gt; dim(Training)
[1] 39  6
&amp;gt; dim(Test)
[1] 12  6
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;B.	Model Building - Evaluation Method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We created a custom root mean square function that will evaluate the performance of our model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Evaluation metric function

RMSE &amp;lt;- function(x,y)
	{
  			a &amp;lt;- sqrt(sum((log(x)-log(y))^2)/length(y))
  			return(a)
	}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;C.	Model Building - Regression Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Regression is a supervised technique, a statistical process for estimating the relationship between a response variable and one or more predictors. Often the outcome variable is also called the response variable or the dependent variable and the and the risk factors and confounders are called the predictors, or explanatory or independent variables. In regression analysis, the dependent variable is denoted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; and the independent variables are denoted by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Regression analysis is a widely used technique which is useful for evaluating multiple independent variables. It serves to answer the question, “Which factors matter the most?”. Interested readers should see (Kleinbaum, Kupper and Muller, 2013) for more details on regression analysis and its many applications.&lt;/p&gt;

&lt;p&gt;We then, created a multiple linear regression model for the response variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt; and the summary statistic showed that the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt; are the most significant predictors such that if included in the model will enhance the predictive power of the response variable. 
The other predictors like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt; do not contribute to the regression model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; linear.mod&amp;lt;- lm(YieldperHectKg~., data = Training)
&amp;gt; summary(linear.mod)

Call:
lm(formula = YieldperHectKg ~ ., data = Training)

Residuals:
Min      1Q  Median      3Q     Max 
-73.203 -23.203  -1.562  13.087 108.326 

Coefficients:
                	Estimate Std. Error t value       Pr(&amp;gt;|t|)    
(Intercept)       -1839.5867  5221.4502  -0.352        0.72684    
Year                  1.6199     2.5965   0.624        0.53699    
TotalPaidEmployee     2.1835     0.7680   2.843        0.00761 ** 
AreaPlantedHect      -0.4247     0.4927  -0.862        0.39490    
ProduceTonne          2.1643     0.2541   8.518 0.000000000764 ***
TapAreaHect          -3.2198     0.9014  -3.572        0.00111 ** 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 36.69 on 33 degrees of freedom
Multiple R-squared:  0.9244,	Adjusted R-squared:  0.913 
F-statistic: 80.74 on 5 and 33 DF,  p-value: &amp;lt; 2.2e-16
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The t value also known as the t-test which is positive for predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Year&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AreaPlantedHect&lt;/code&gt;,&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt; indicating that these predictors are associated with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt;. A larger t-value indicates that that it is less likely that the coefficient is not equal to zero purely by chance.&lt;/p&gt;

&lt;p&gt;Again, as the p-value for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt; is less than 0.05 they are both statistically significant in the multiple linear regression model for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt; response variable. The model’s, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p-value: &amp;lt; 2.2e-16&lt;/code&gt; is also lower than the statistical significance level of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.05&lt;/code&gt;, this indicates that we can safely reject the null hypothesis that the value for the coefficient is zero (or in other words, the predictor variable has no explanatory relationship with the response variable).&lt;/p&gt;

&lt;p&gt;In Regression, the Null Hypothesis is that the coefficients associated with the variables is equal to zero. The alternate hypothesis is that the coefficients are not equal to zero (i.e. there exists a relationship
between the independent variable in question and the dependent variable).&lt;/p&gt;

&lt;p&gt;We tested this model using the root mean square evaluation method.&lt;/p&gt;

&lt;p&gt;Note, we did not remove the non-contributing predictors from the regression model and found the RMSE to be quite low of 0.045. This model has an F-statistic of 80.74 which is considerably high and better.&lt;/p&gt;

&lt;p&gt;Next, we performed the model prediction on unseen data.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; predict&amp;lt;- predict(linear.mod, Test)
&amp;gt; RMSE0&amp;lt;- RMSE(predict, Test$YieldperHectKg)
&amp;gt; RMSE0
[1] 0.04533296
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;D. Model Performance on various supervised algorithms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We now test the model performance on some supervised algorithms to determine the model’s prediction accuracy.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Regression Tree method&lt;/strong&gt;&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &amp;gt; library(rpart)
  &amp;gt; model &amp;lt;- rpart(YieldperHectKg ~., data = Training, method = &quot;anova&quot;)
  &amp;gt; predict &amp;lt;- predict(model, Test)
  # RMSE
  &amp;gt; RMSE1 &amp;lt;- RMSE(predict, Test$YieldperHectKg)
  &amp;gt; RMSE1 &amp;lt;- round(RMSE1, digits = 3)
  &amp;gt; RMSE1
  &amp;gt; [1] 0.098
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Random Forest method&lt;/strong&gt;&lt;/p&gt;

    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &amp;gt; model.forest &amp;lt;- randomForest(YieldperHectKg ~., data = Training, method = &quot;anova&quot;, 
                ntree = 300,
                mtry = 2, #mtry is sqrt(6)
                replace = F,
                nodesize = 1,
                importance = T)


  &amp;gt; varImpPlot(model.forest) # Look at the IncNodePurity plot. From this plot we see that important vars are `TotalPaidEmployee`, `ProduceTonne` and `TapAreaHect`

  &amp;gt; prediction &amp;lt;- predict(model.forest,Test)

  &amp;gt; rmse &amp;lt;- sqrt(mean((log(prediction)-log(Test$YieldperHectKg))^2))

  &amp;gt; round(rmse, digits = 3) # 0.049
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Variance Inflation Factor (VIF) plot shows the predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt; as most important.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-VIFPlot.png&quot; alt=&quot;plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-9: VIF plot&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D.1. Comparison of Predictive Model Performance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So to predict the response variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt; the best results were given by Regression Tree based model which gave an accuracy of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;98%&lt;/code&gt; as compared to others;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Linear Regression: 0.04533296
Regression Tree RMSE: 0.098
Random Forest RMSE:  0.049 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;E. Model Diagnostics&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. The p Value: Checking for statistical significance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is extremely important for the model to be statistically significant before we can go ahead and use it to predict (or estimate) the dependent variable, otherwise, the confidence in predicted values from that model reduces and may be construed as an event of chance.&lt;/p&gt;

&lt;p&gt;In this model &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;linear.mod&lt;/code&gt; the p-Values of the predictors are well below the 0.05 threshold, so we can conclude our model is indeed statistically significant. This can visually be interpreted by the significance stars at the end of the row. The more the stars beside the variable’s p-Value, the more significant the variable is.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ii. Check the AIC and BIC&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Akaike’s Information Criterion AIC (Akaike, 1974) and the Bayesian Information Criterion BIC (Schwarz, 1978) are measures of the goodness of fit of an estimated statistical model and can also be used for model selection.&lt;/p&gt;

&lt;p&gt;Both criteria depend on the maximized value of the likelihood function L for the
estimated model.&lt;/p&gt;

&lt;p&gt;The AIC is defined as:
AIC = (−2) • ln (L) + 2 • k
where k is the number of model parameters and the BIC is defined as:
BIC = (−2) • ln(L) + k • ln(n)
where n is the sample size.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; AIC(linear.mod)
[1] 399.1521
&amp;gt; BIC(linear.mod)
[1] 410.797
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For model comparison, the model with the lowest AIC and BIC score is preferred. Suppose, we had build another linear model with only two predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt; given as;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; linear.mod1&amp;lt;- lm(YieldperHectKg~ProduceTonne+TapAreaHect, data = Training)
&amp;gt; AIC(linear.mod1)
[1] 402.8458
&amp;gt; BIC(linear.mod1)
[1] 409.5001
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AIC&lt;/code&gt; &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BIC&lt;/code&gt; for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;linear.mod&lt;/code&gt; is &lt;strong&gt;lower&lt;/strong&gt; than the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;linear.mod1&lt;/code&gt; therefore, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;linear.mod&lt;/code&gt; is a &lt;strong&gt;better model&lt;/strong&gt; for predicting the response variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iii. The R-Squared and Adjusted R-Squared&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The actual information in a data is the total variation it contains. 
What R-Squared tells us is the proportion of variation in the dependent (response) variable that has been explained by this model.&lt;/p&gt;

&lt;p&gt;Also, we do not necessarily have to discard a model based on a low R-Squared value. It’s a better practice to look at the AIC and prediction accuracy on validation sample when deciding on the efficacy of a model.&lt;/p&gt;

&lt;p&gt;What about the adjusted R-Squared? As you add terms to your model, the R-Squared value of the new model will always be greater than that of its subset. This is because, since all the variables in the original model is also present, their contribution to explain the depend variable still remains in the super-set and
therefore, whatever new variable we add can only enhance (if not significantly) what was already explained.&lt;/p&gt;

&lt;p&gt;Here is how, the adjusted R-Squared value comes to help. Adj R-Squared penalizes total value for the number of terms (read predictors) in your model.&lt;/p&gt;

&lt;p&gt;Therefore, when comparing nested models, it is a good practice to look at adj-R-squared value over R-squared.&lt;/p&gt;

&lt;p&gt;We also have an adjusted r-square value (we’re now looking at adjusted R-square as a more appropriate metric of variability as the adjusted R-squared increases only if the new term added ends up improving the model more than would be expected by chance). In this model, we arrived in a larger R-squared number of 0.94&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iv. How do you know if the model is best fit for your data?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The most common metrics to look at while selecting the model are:&lt;/p&gt;

&lt;p&gt;r-squared-	Higher the better&lt;/p&gt;

&lt;p&gt;Adj. r-squared- 	Higher the better&lt;/p&gt;

&lt;p&gt;AIC- Lower the better&lt;/p&gt;

&lt;p&gt;BIC- Lower the better&lt;/p&gt;

&lt;p&gt;MAPE (Mean Absolute Percentage Error)- Lower the better&lt;/p&gt;

&lt;p&gt;MSE (Mean Squared Error)- Lower the better&lt;/p&gt;

&lt;p&gt;Min_Max Accuracy- Higher the better&lt;/p&gt;

&lt;p&gt;RMSE- lower the better&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;v. Residuals&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The difference between the observed value of the dependent variable (y) and the predicted value (ŷ) is called the residual (e). Each data point has one residual.&lt;/p&gt;

&lt;p&gt;Residual = Observed value - Predicted value
  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;e = y - ŷ&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Both the sum and the mean of the residuals are equal to zero. That is, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Σ e = 0&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;e = 0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A residual plot is a graph that shows the residuals on the vertical axis and the independent variable on the horizontal axis. If the points in a residual plot are randomly dispersed around the horizontal axis, a linear regression model is appropriate for the data; otherwise, a non-linear model is more appropriate.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/casestudy-MY-Rubber-residualplot.png&quot; alt=&quot;plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-10: Residual plot&lt;/p&gt;

&lt;p&gt;From the residual plot in Fig-10, we see the points are randomly distributed, thus the choice of our multiple linear regression was appropriate in predicting the response variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;F. Model Inference Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From the model diagnostics, we see that the model p value and predictor’s p value are less than the significance level, so we know we have a statistically significant model. Also, the R-Sq and Adj R-Sq are comparative to the
original model built on full data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;G. Calculate prediction accuracy and error rates&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A simple correlation between the actuals and predicted values can be used as a form of accuracy measure.&lt;/p&gt;

&lt;p&gt;A higher correlation accuracy implies that the actuals and predicted values have similar directional movement, i.e. when the actuals values increase the predicted also increase and vice-versa.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; predict&amp;lt;- predict(linear.mod, Test)
&amp;gt; actuals_preds &amp;lt;- data.frame(cbind(actuals=Test$YieldperHectKg, predicteds=predict)) # make actuals_predicteds dataframe.
&amp;gt; correlation_accuracy &amp;lt;- cor(actuals_preds)
&amp;gt; correlation_accuracy

         actuals predicteds
actuals    1.0000000  0.9447834
predicteds 0.9447834  1.0000000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The prediction accuracy of the model &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;linear.mod&lt;/code&gt; on unseen data is &lt;strong&gt;94%&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now let’s calculate the Min Max accuracy and MAPE&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; min_max_accuracy &amp;lt;- mean (apply(actuals_preds, 1, min) / apply(actuals_preds, 1, max))
&amp;gt; min_max_accuracy
[1] 0.9721728
&amp;gt; mape &amp;lt;- mean(abs((actuals_preds$predicteds - actuals_preds$actuals))/actuals_preds$actuals)
&amp;gt; mape
[1] 0.02970934
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Looks like we have a good model in here because the MAPE value is &lt;strong&gt;0.029&lt;/strong&gt; which is quite low and min max accuracy of &lt;strong&gt;0.97&lt;/strong&gt; which is quite high.&lt;/p&gt;

&lt;h3 id=&quot;5-conclusion&quot;&gt;5. Conclusion&lt;/h3&gt;

&lt;p&gt;In building a data powered case study, the primary component is the &lt;em&gt;research/business question&lt;/em&gt;, that takes precedence above anything else. Experience has taught us that if one cannot think of a feasible research question then its best to perform exploratory data analysis first. This exploratory phase serves many purposes like it gives you a first hand account of the data at hand (&lt;em&gt;in terms of missing value, outliers, skewness, relationships etc&lt;/em&gt;). During the exploratory phase, ensure to document and justify data management decisions so as to maintain &lt;em&gt;data accountability&lt;/em&gt; and &lt;em&gt;data transparency&lt;/em&gt;. This process subsequently leads in formulating the research question. Another approach could be to perform an extensive literature review, find the gap in existing literature, formulate the problem and then acquire the relevant dataset to answer the problem. Both approaches are correct but at the beginner level we would recommend the former approach because you will be more closer to &lt;em&gt;active action&lt;/em&gt; rather than &lt;em&gt;passive thinking&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Continuing further, in tree based models where the response or target variable can take a finite set of values are called, &lt;em&gt;classification tree’s&lt;/em&gt;. In these tree structures, the &lt;em&gt;leaves&lt;/em&gt; represent the &lt;em&gt;class labels&lt;/em&gt; and the &lt;em&gt;branches&lt;/em&gt; represent the &lt;em&gt;node&lt;/em&gt; of features that lead to those class labels. On the contrary the decision trees where the response or target variable can take continuous value &lt;em&gt;(like price of a house)&lt;/em&gt; are called &lt;em&gt;regression trees&lt;/em&gt;. The term, &lt;em&gt;Classification and Regression Trees (CART)&lt;/em&gt; is thus an umbrella term that combines both the procedures.&lt;/p&gt;

&lt;p&gt;As we have seen so far, a rigorous model testing must be applied to build an efficient model. The predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ProduceTonne&lt;/code&gt; is most significant for prediction of the response variable, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;YieldperHectKg&lt;/code&gt; and is closely followed by other predictors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TotalPaidEmployee&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TapAreaHect&lt;/code&gt;. We also see that &lt;strong&gt;Regression tree&lt;/strong&gt; based approach give &lt;strong&gt;98% accuracy&lt;/strong&gt; in predicting the response variable while Random Forest model (&lt;strong&gt;0.049%&lt;/strong&gt;) does not even come close.&lt;/p&gt;

&lt;p&gt;The reason we achieved such an high predictive accuracy for regression tree based model was because there was a strong positive linear relationship between the predictors and this works best for regression tree accuracy. In Fig-11, we show a graphical representation of which type of decision tree to use. The random forest algorithm would have served a response variable with finite set of values better. A simple and good introduction to understanding random forest is given &lt;a href=&quot;http://blog.echen.me/2011/03/14/laymans-introduction-to-random-forests/&quot;&gt;here.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/which-type-of-decision-tree-to-use.png&quot; alt=&quot;plot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Fig-11: Which Decision Tree method to use&lt;/p&gt;

&lt;p&gt;Another, hat tip for beginners in data science is to look at the response variable in deciding which algorithm to use. In this case study, the response variable was continuous in nature with strong positive linear relationship among the predictors. Therefore, the choice of regression trees was ideal.&lt;/p&gt;

&lt;p&gt;The complete code is listed on my Github repository in &lt;a href=&quot;https://github.com/duttashi/LearningR/blob/master/scripts/Full%20Case%20Studies/CaseStudy-MY-RubberPlantation.R&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;references&quot;&gt;References&lt;/h3&gt;

&lt;p&gt;Bache, S. M., &amp;amp; Wickham, H. (2014). Magrittr: A forward-pipe operator for R. R package version, 1(1).&lt;/p&gt;

&lt;p&gt;Buuren, S., &amp;amp; Groothuis-Oudshoorn, K. (2011). mice: Multivariate imputation by chained equations in R. Journal of Statistical Software, 45(3).&lt;/p&gt;

&lt;p&gt;Ihaka, R., &amp;amp; Gentleman, R. (1996). R: a language for data analysis and graphics. Journal of computational and graphical statistics, 5(3), 299-314.&lt;/p&gt;

&lt;p&gt;Kursa, M. B., &amp;amp; Rudnicki, W. R. (2010). Feature selection with the Boruta package: Journal of Statistical Software.&lt;/p&gt;

&lt;p&gt;Revelle, W. (2014). psych: Procedures for personality and psychological research. Northwestern University, Evanston. R package version, 1(1).&lt;/p&gt;

&lt;p&gt;Wickham, H. (2015). plyr: Tools for splitting, applying and combining data. R package version 1.8. 1. R Found. Stat. Comput., Vienna.&lt;/p&gt;

&lt;p&gt;Wickham, H. (2016). ggplot2: elegant graphics for data analysis: Springer.&lt;/p&gt;

&lt;p&gt;Wickham, H., &amp;amp; Francois, R. (2015). dplyr: A grammar of data manipulation. R package version 0.4, 1, 20.&lt;/p&gt;

&lt;p&gt;Kleinbaum, D., Kupper, L., Nizam, A., &amp;amp; Rosenberg, E. (2013). Applied regression analysis and other multivariable methods. Nelson Education.&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Basic assumptions to be taken care of when building a predictive model]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/basic-assumptions-to-be-taken-care-of-when-building-a-predictive-model/" />
  <id>https://duttashi.github.io/blog/basic-assumptions-to-be-taken-care-of-when-building-a-predictive-model</id>
  <published>2017-01-18T00:00:00+00:00</published>
  <updated>2017-01-18T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;Before starting to build on a predictive model in R, the following assumptions should be taken care off;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 1&lt;/strong&gt;: &lt;strong&gt;The parameters of the linear regression model must be numeric and linear in nature&lt;/strong&gt;. 
If the parameters are non-numeric like categorical then use one-hot encoding (python) or dummy encoding (R) to convert them to numeric.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 2&lt;/strong&gt;: &lt;strong&gt;The mean of the residuals is Zero&lt;/strong&gt;. 
Check the mean of the residuals. If it zero (or very close), then this assumption is held true for that model. This is default unless you explicitly make amends, such as setting the intercept term to zero.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(2)
&amp;gt; mod &amp;lt;- lm(dist ~ speed, data=cars) 
&amp;gt; mean(mod$residuals)
[1] 8.65974e-17 Since the mean of residuals is approximately zero, this assumption holds true for this model.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Assumption 3&lt;/strong&gt;: &lt;strong&gt;Homoscedasticity of residuals or equal variance&lt;/strong&gt;: 
This assumption means that the variance around the regression line is the same for all values of the predictor variable (X).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to check?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Once the regression model is built, set&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; par(mfrow=c(2, 2))  then, plot the model using

&amp;gt; plot(lm.mod)  This produces four plots. The top-left and bottom-left plots shows how the residuals vary as the fitted values increase. First, I show an example where heteroscedasticity is present. To show this, I use the mtcars dataset from the base R dataset package.

&amp;gt; set.seed(2) # for example reproducibility
&amp;gt; par(mfrow=c(2,2)) # set 2 rows and 2 column plot layout
&amp;gt; mod_1 &amp;lt;- lm(mpg ~ disp, data=mtcars) # linear model 
&amp;gt; plot(mod_1) 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/lrassum-1.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 1: An example of heteroscedasticity in mtcars dataset&lt;/p&gt;

&lt;p&gt;From Figure 1, look at the first plot (top-left), as the fitted values along x increase, the residuals decrease and then increase. This pattern is indicated by the red line, which should be approximately flat if the disturbances are homoscedastic. The plot on the bottom left also checks and confirms this, and is more convenient as the disturbance term in Y axis is standardized. In this case, there is a definite pattern noticed. So, there is heteroscedasticity. Lets check this on a different model. Now, I will use the cars dataset from the base r dataset package in R.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(2) # for example reproducibility
&amp;gt; par(mfrow=c(2,2)) # set 2 rows and 2 column plot layout
&amp;gt; mod &amp;lt;- lm(dist ~ speed, data=cars) 
&amp;gt; plot(mod)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/lrassum-2.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 2: An example of homoscedasticity in cars dataset&lt;/p&gt;

&lt;p&gt;From Figure 2, looking at the first plot (top-left) the points appear random and the line looks pretty flat, with no increasing or decreasing trend. So, the condition of homoscedasticity can be accepted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 4&lt;/strong&gt;: &lt;strong&gt;No autocorrelation of residuals&lt;/strong&gt;
Autocorrelation is specially applicable for time series data. It is the correlation of a time series with lags of itself. When the residuals are autocorrelated, it means that the current value is dependent of the previous (historic) values and that there is a definite unexplained pattern in the Y variable that shows up in the disturbances.
So how do I check for autocorrelation?
There are several methods for it like the runs test for randomness &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(R: lawstat::runs.test())&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;durbin-watson test (R: lmtest::dwtest())&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;acf plot&lt;/code&gt; from the ggplot2 library. I will use the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;acf plot()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Method : Visualise with acf plot from the base R package&lt;/em&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; ?acf # check the help page the acf function
&amp;gt; data(cars) # using the cars dataset from base R 
&amp;gt; acf(cars)  # highly autocorrelated, see figure 3.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/acf.png&quot; alt=&quot;acf&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 3: Detecting Auto-Correlation in Predictors&lt;/p&gt;

&lt;p&gt;The X axis corresponds to the lags of the residual, increasing in steps of 1. The very first line (to the left) shows the correlation of residual with itself (Lag0), therefore, it will always be equal to 1.
If the residuals were not autocorrelated, the correlation (Y-axis) from the immediate next line onwards will drop to a near zero value below the dashed blue line (significance level). Clearly, this is not the case here. So we can conclude that the residuals are autocorrelated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Remedial action to resolve Heteroscedasticity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Add a variable named resid1 (can be any name for the variable) of residual as an X variable to the original model. This can be conveniently done using the slide function in DataCombine package. If, even after adding lag1 as an X variable, does not satisfy the assumption of autocorrelation of residuals, you might want to try adding lag2, or be creative in making meaningful derived explanatory variables or interaction terms. This is more like art than an algorithm. For more details, see &lt;a href=&quot;https://stat.ethz.ch/R-manual/R-devel/library/stats/html/acf.html&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(DataCombine)
&amp;gt; set.seed(2) # for example reproducibility 
&amp;gt; lmMod &amp;lt;- lm(dist ~ speed, data=cars) 
&amp;gt; cars_data &amp;lt;- data.frame(cars, resid_mod1=lmMod$residuals) 
&amp;gt; cars_data_1 &amp;lt;- slide(cars_data, Var=&quot;resid_mod1&quot;, NewVar = &quot;lag1&quot;, slideBy = -1) 
&amp;gt; cars_data_2 &amp;lt;- na.omit(cars_data_1) 
&amp;gt; lmMod2 &amp;lt;- lm(dist ~ speed + lag1, data=cars_data_2) 
&amp;gt; acf(lmMod2$residuals)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/acf1-2.png&quot; alt=&quot;acf1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 4: Homoscedasticity of residuals or equal variance&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 5&lt;/strong&gt;: &lt;strong&gt;The residuals and the X variables must be uncorrelated&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How to check correlation among predictors, use the cor.test function&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(2)
&amp;gt; mod.lm &amp;lt;- lm(dist ~ speed, data=cars) 
&amp;gt; cor.test(cars$speed, mod.lm$residuals)  # do correlation test 
 
Pearson&apos;s product-moment correlation
data: cars$speed and mod.lm$residuals
 	t = 5.583e-16, df = 48, p-value = 1
 	alternative hypothesis: true correlation is not equal to 0
 	95 percent confidence interval:
 	-0.2783477 0.2783477
 	sample estimates:
 	cor
 	8.058406e-17
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Since p value is greater than zero, it is high, so the null hypothesis that the true correlation is Zero cannot be rejected. So the assumption holds true for this model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 6&lt;/strong&gt;: &lt;strong&gt;The number of observations must be greater than the number of predictors or X variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This can be observed by looking at the data&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 7&lt;/strong&gt;: &lt;strong&gt;The variability in predictors or X values is positive&lt;/strong&gt;
What this infers to is that the variance in the predictors should not all be the same (or even nearly the same).&lt;/p&gt;

&lt;p&gt;How to check this in R?&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; var(cars$dist)
[1] 664.0608
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The variance in the X variable above is much larger than 0. So, this assumption is satisfied.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 8&lt;/strong&gt;: &lt;strong&gt;No perfect multicollinearity between the predictors&lt;/strong&gt;
What this means is that there should not be a perfect linear relationship between the predictors or the explanatory variables.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How to check for multicollinearity?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Use Variance Inflation Factor (VIF). VIF is a metric computed for every X variable that goes into a linear model. If the VIF of a variable is high, it means the information in that variable is already explained by other X variables present in the given model, which means, more redundant is that variable. according to some references, if the VIF is too large(more than 5 or 10), we consider that the multicollinearity is existent. So, lower the VIF (less than 2) the better. VIF for a X var is calculated as:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/vif.png&quot; alt=&quot;vif&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 5: Variance Inflation Factor&lt;/p&gt;

&lt;p&gt;where, &lt;em&gt;Rsq&lt;/em&gt; is the Rsq term for the model with given X as response against all other Xs that went into the model as predictors.&lt;/p&gt;

&lt;p&gt;Practically, if two of the X′s have high correlation, they will likely have high VIFs. Generally, VIF for an X variable should be less than 4 in order to be accepted as not causing multi-collinearity. The cutoff is kept as low as 2, if you want to be strict about your X variables.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; mod1 &amp;lt;- lm(mpg ~ ., data=mtcars) 
&amp;gt; library(car) # load the car package which has the vif()
&amp;gt; vif(mod1)
 
  cyl      disp        hp      drat        wt      qsec        vs        am      gear      carb 
15.373833 21.620241  9.832037  3.374620 15.164887  7.527958  4.965873  4.648487  5.357452  7.908747  From here, we can see that the VIF for data mtcars is high for all X’s variables or predictors indicating high multicollinearity.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;How to remedy the issue of multicollinearity&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In order to solve this problem, there are 2 main approaches. Firstly, we can use robust regression analysis instead of OLS(ordinary least squares), such as ridge regression, lasso regression and principal component regression. On the other hand, statistical learning regression is also a good method, like regression tree, bagging regression, random forest regression, neural network and SVR(support vector regression).  In R language, the function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lm.ridge()&lt;/code&gt; in package &lt;a href=&quot;https://cran.r-project.org/web/packages/MASS/index.html&quot;&gt;MASS&lt;/a&gt; could implement ridge regression(linear model). The sample codes and output as follows&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(corrplot)
corrplot(cor(mtcars[, -1]))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/corplot.png&quot; alt=&quot;corrplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 6: Correlation Plot&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Assumption 9&lt;/strong&gt;: &lt;strong&gt;The normality of the residuals&lt;/strong&gt;
The residuals should be normally distributed. This can be visually checked by using the qqnorm() plot.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; par(mfrow=c(2,2))
&amp;gt; mod &amp;lt;- lm(dist ~ speed, data=cars)
&amp;gt; plot(mod)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/qqnorm-plot.png&quot; alt=&quot;qqnormplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 7: The qqnorm plot to depict the residuals&lt;/p&gt;

&lt;p&gt;The qqnorm() plot in top-right evaluates this assumption. If points lie exactly on the line, it is perfectly normal distribution. However, some deviation is to be expected, particularly near the ends (note the upper right), but the deviations should be small, even lesser that they are here.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check the aforementioned assumptions automatically&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt; gvlma()&lt;/code&gt; from the gvlma package offers to check for the important assumptions on a given linear model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; install.packages(&quot;gvlma&quot;)
&amp;gt; library(gvlma)
&amp;gt; par(mfrow=c(2,2))  # draw 4 plots in same window
&amp;gt; mod &amp;lt;- lm(dist ~ speed, data=cars)
Call:
lm(formula = dist ~ speed, data = cars)
 
Coefficients:
(Intercept)        speed  
	-17.579        3.932  
 
ASSESSMENT OF THE LINEAR MODEL ASSUMPTIONS
USING THE GLOBAL TEST ON 4 DEGREES-OF-FREEDOM:
Level of Significance =  0.05 
 
Call:
gvlma::gvlma(x = mod) 
 
                Value  p-value                   Decision
Global Stat        15.801 0.003298 Assumptions NOT satisfied!
Skewness            6.528 0.010621 Assumptions NOT satisfied!
Kurtosis            1.661 0.197449    Assumptions acceptable.
Link Function       2.329 0.126998    Assumptions acceptable.
Heteroscedasticity  5.283 0.021530 Assumptions NOT satisfied!
 
&amp;gt; plot(mod)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Three of the assumptions are not satisfied. This is probably because we have only 50 data points in the data and having even 2 or 3 outliers can impact the quality of the model. So the immediate approach to address this is to remove those outliers and re-build the model. Take a look at the diagnostic plot below.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot1-1.png&quot; alt=&quot;diagnosticplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 8: The diagnostic plot&lt;/p&gt;

&lt;p&gt;As we can see in the above plot (figure 7), the data points: 23, 35 and 49 are marked as outliers. Lets remove them from the data and re-build the model.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; mod &amp;lt;- lm(dist ~ speed, data=cars[-c(23, 35, 49), ])
&amp;gt; gvlma::gvlma(mod)
 
Call:
lm(formula = dist ~ speed, data = cars[-c(23, 35, 49), ])
 
Coefficients:
(Intercept)        speed  
	-15.137        3.608  
  
ASSESSMENT OF THE LINEAR MODEL ASSUMPTIONS 
USING THE GLOBAL TEST ON 4 DEGREES-OF-FREEDOM:
Level of Significance =  0.05 
 
Call:
gvlma::gvlma(x = mod) 
 
                Value p-value                Decision
Global Stat        7.5910 0.10776 Assumptions acceptable.
Skewness           0.8129 0.36725 Assumptions acceptable.
Kurtosis           0.2210 0.63831 Assumptions acceptable.
Link Function      3.2239 0.07257 Assumptions acceptable.
Heteroscedasticity 3.3332 0.06789 Assumptions acceptable.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Post removing the outliers we can see from the results that all our assumptions have been met in the new model.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot1-3.png&quot; alt=&quot;normalisedmodelplot&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 9: Normalised variables plot&lt;/p&gt;

&lt;p&gt;Note: For a good regression model, the red smoothed line should stay close to the mid-line and no point should have a large cook’s distance (i.e. should not have too much influence on the model.). On plotting the new model, the changes look minor, it is more closer to conforming with the assumptions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;End thoughts&lt;/strong&gt;
Given a dataset, its very important to first ensure that it fulfills the aforementioned assumptions before you begin with any sort or inferential or predictive modeling. Moreover, by taking care of these assumptions you are ensuring a robust model that will survive and yield high predictive values.&lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Data Transformations in R]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/data-transform/" />
  <id>https://duttashi.github.io/blog/data-transform</id>
  <published>2017-01-11T00:00:00+00:00</published>
  <updated>2017-01-11T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;A number of reasons can be attributed to when a predictive model crumples such as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Inadequate data pre-processing&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Inadequate model validation&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Unjustified extrapolation&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Over-fitting&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(Kuhn, 2013)&lt;/p&gt;

&lt;p&gt;Before we dive into data preprocessing, let me quickly define a few terms that I will be commonly using.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Predictor/Independent/Attributes/Descriptors&lt;/em&gt; – are the different terms that are used as input for the prediction equation.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Response/Dependent/Target/Class/Outcome&lt;/em&gt; – are the different terms that are referred to the outcome event that is to be predicted.&lt;/p&gt;

&lt;p&gt;In this article, I am going to summarize some common data pre-processing approaches with examples in R&lt;/p&gt;

&lt;p&gt;a. &lt;strong&gt;Centering and Scaling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variable centering is perhaps the most intuitive approach used in predictive modeling. To center a predictor variable, the average predictor value is subtracted from all the values. as a result of centering, the predictor has zero mean.
To scale the data, each predictor value is divided by its standard deviation (sd). This helps in coercing the predictor value to have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sd&lt;/code&gt; of one. Needless to mention, centering and scaling will work for continuous data. The drawback of this activity is loss of interpretability of the individual values.
An R example:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Load the default datasets
&amp;gt; library(datasets)
&amp;gt; data(mtcars)
&amp;gt; dim(mtcars)
32 11

&amp;gt; str(mtcars)
&apos;data.frame&apos;:   32 obs. of  11 variables:
$ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
$ disp: num  160 160 108 258 360 ...
$ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
$ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num  16.5 17 18.6 19.4 17 ...
$ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
$ am  : num  1 1 1 0 0 0 0 0 0 0 ...
$ gear: num  4 4 4 3 3 3 3 4 4 4 ...
$ carb: num  4 4 1 1 2 1 4 2 2 4 ...

&amp;gt; cov(mtcars$disp, mtcars$cyl) # check for covariance
[1] 199.6603
&amp;gt; mtcars$disp.scl&amp;lt;-scale(mtcars$disp, center = TRUE, scale = TRUE)  
&amp;gt; mtcars$cyl.scl&amp;lt;- scale(mtcars$cyl, center = TRUE, scale = TRUE)  
&amp;gt; cov(mtcars$disp.scl, mtcars$cyl.scl) # check for covariance in scaled data
          [,1]
[1,] 0.9020329
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;b. &lt;strong&gt;Resolving Skewness&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Skewness is a measure of shape. A common appraoch to check for skewness is to plot the predictor variable. As a rule, negative skewness indicates that the mean of the data values is less than the median, and the data distribution is left-skewed. Positive skewness would indicates that the mean of the data values is larger than the median, and the data distribution is right-skewed.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;If the skewness of the predictor variable is 0, the data is perfectly symmetrical,&lt;/li&gt;
  &lt;li&gt;If the skewness of the predictor variable is less than -1 or greater than +1, the data is highly skewed,&lt;/li&gt;
  &lt;li&gt;If the skewness of the predictor variable is between -1 and -1/2 or between +1 and +1/2 then the data is moderately skewed,&lt;/li&gt;
  &lt;li&gt;If the skewness of the predictor variable is -1/2 and +1/2, the data is approximately symmetric.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I will use the function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skewness&lt;/code&gt; from the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;e1071 package&lt;/code&gt; to compute the skewness coefficient&lt;/p&gt;

&lt;p&gt;An R example:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(e1071)
&amp;gt; engine.displ&amp;lt;-skewness(mtcars$disp) &amp;gt; engine.displ
[1] 0.381657
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So the variable displ is moderately positively skewed.&lt;/p&gt;

&lt;p&gt;c. &lt;strong&gt;Resolving Outliers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The outliers package provides a number of useful functions to systematically extract outliers. Some of these are convenient and come handy, especially the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;outlier()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scores()&lt;/code&gt; functions.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Outliers&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;outliers()&lt;/code&gt; gets the extreme most observation from the mean.
If you set the argument &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;opposite=TRUE&lt;/code&gt;, it fetches from the other side.&lt;/p&gt;

&lt;p&gt;An R example:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(4680) # for code reproducibility
&amp;gt; y&amp;lt;- rnorm(100) # create some dummy data &amp;gt; library(outliers) # load the library
&amp;gt; outlier(y)
[1] 3.581686
&amp;gt; dim(y)&amp;lt;-c(20,5) # convert it to a matrix &amp;gt; head(y,2)# Look at the first 2 rows of the data
     [,1]       [,2]      [,3]      [,4]       [,5]
[1,] 0.5850232  1.7782596  2.051887  1.061939 -0.4421871
[2,] 0.5075315 -0.4786253 -1.885140 -0.582283  0.8159582
&amp;gt; outlier(y) # Now, check for outliers in the matrix
[1] -1.902847 -2.373839  3.581686  1.583868  1.877199
&amp;gt; outlier(y, opposite = TRUE)
[1]  1.229140  2.213041 -1.885140 -1.998539 -1.571196
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;There are two aspects the the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scores()&lt;/code&gt; function.
Compute the normalised scores based on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;z&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chisq&lt;/code&gt; etc.&lt;/p&gt;

&lt;p&gt;Find out observations that lie beyond a given percentile based on a given score.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; set.seed(4680)
&amp;gt; x = rnorm(10)
&amp;gt; scores(x)  # z-scores =&amp;gt; (x-mean)/sd
[1]  0.9510577  0.8691908  0.6148924 -0.4336304 -1.6772781...
&amp;gt; scores(x, type=&quot;chisq&quot;)  # chi-sq scores =&amp;gt; (x - mean(x))^2/var(x)
[1] 0.90451084 0.75549262 0.37809269 0.18803531 2.81326197 . . .
&amp;gt; scores(x, type=&quot;t&quot;)  # t scores
[1]  0.9454321  0.8562050  0.5923010 -0.4131696 -1.9073009
&amp;gt; scores(x, type=&quot;chisq&quot;, prob=0.9)  # beyond 90th %ile based on chi-sq
[1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
&amp;gt; scores(x, type=&quot;chisq&quot;, prob=0.95)  # beyond 95th %ile
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
&amp;gt; scores(x, type=&quot;z&quot;, prob=0.95)  # beyond 95th %ile based on z-scores
[1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
&amp;gt; scores(x, type=&quot;t&quot;, prob=0.95)  # beyond 95th %ile based on t-scores
[1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;d. &lt;strong&gt;Outlier Treatment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once the outliers are identified, you may rectify it by using one of the following approaches.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Imputation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Imputation with mean / median / mode.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Capping&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For missing values that lie outside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.5 * IQR limits&lt;/code&gt;, we could cap it by replacing those observations outside the lower limit with the value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5th%ile&lt;/code&gt; and those that lie above the upper limit, with the value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;95th%ile&lt;/code&gt;. For example, it can be done like this as shown;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; par(mfrow=c(1, 2)) # for side by side plotting
&amp;gt; x &amp;lt;- mtcars$mpg &amp;gt; plot(x)
&amp;gt; qnt &amp;lt;- quantile(x, probs=c(.25, .75), na.rm = T) 
&amp;gt; caps &amp;lt;- quantile(x, probs=c(.05, .95), na.rm = T) 
&amp;gt; H &amp;lt;- 1.5 * IQR(x, na.rm = T) 
&amp;gt; x[x &amp;lt; (qnt[1] - H)] &amp;lt;- caps[1] 
&amp;gt; x[x &amp;gt; (qnt[2] + H)] &amp;lt;- caps[2] 
&amp;gt; plot(x)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;e. Missing value treatment&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Impute Missing values with median or mode&lt;/li&gt;
  &lt;li&gt;Impute Missing values based on K-nearest neighbors&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use the library &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DMwR&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mice&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rpart&lt;/code&gt;. If using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DMwR&lt;/code&gt;, for every observation to be imputed, it identifies ‘k’ closest observations based on the euclidean distance and computes the weighted average (weighted based on distance) of these ‘k’ obs. The advantage is that you could impute all the missing values in all variables with one call to the function. It takes the whole data frame as the argument and you don’t even have to specify which variabe you want to impute. But be cautious not to include the response variable while imputing.&lt;/p&gt;

&lt;p&gt;There are many other types of transformations like treating colinearity, dummy variable encoding, covariance treatment which I will cover in another post.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Kuhn, M., Johnson, K. (2013). Applied predictive modeling (pp. 389-400). New York: Springer.&lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Sold! How do home features add up to its price tag?]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/sold-how-do-home-features-add-up-to-its-price-tag/" />
  <id>https://duttashi.github.io/blog/sold-how-do-home-features-add-up-to-its-price-tag</id>
  <published>2016-09-06T13:20:00+00:00</published>
  <updated>2016-09-06T13:20:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;I begin with a new project. It is from the&lt;/span&gt; &lt;a href=&quot;https://www.kaggle.com/c/house-prices-advanced-regression-techniques&quot; target=&quot;_blank&quot;&gt;Kaggle&lt;/a&gt; &lt;span style=&quot;color:#000000;&quot;&gt;playground wherein the objective is to build a regression model &lt;em&gt;(as the response variable or the outcome or dependent variable is continuous in nature) &lt;/em&gt;from a given set of predictors or independent variables. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;My motivation to work on this project are the following;&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Help me to learn and improve upon &lt;em&gt;feature engineering&lt;/em&gt; and advanced regression algorithms like &lt;em&gt;random forests, gradient boosting with xgboost&lt;/em&gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Help me in articulating compelling data powered stories &lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Help me understand and build a complete end to end data powered solution&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;&lt;strong&gt;The Dataset&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;From the Kaggle page,&lt;/span&gt; “&lt;em&gt;The &lt;a class=&quot;pdf-link&quot; href=&quot;http://www.amstat.org/publications/jse/v19n3/decock.pdf&quot; target=&quot;_blank&quot;&gt;Ames Housing dataset&lt;/a&gt; &lt;span style=&quot;color:#000000;&quot;&gt;was compiled by Dean De Cock for use in data science education. It’s an incredible alternative for data scientists looking for a modernized and expanded version of the often cited Boston Housing dataset.”&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;The Data Dictionary&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;The data dictionary can be accessed from&lt;/span&gt; &lt;a href=&quot;http://www.amstat.org/publications/jse/v19n3/decock/DataDocumentation.txt&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;Objective&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;With 79 explanatory variables describing (almost) every aspect of residential homes in Ames, Iowa, this competition challenges you to predict the final price of each home.&lt;/span&gt;&lt;/p&gt;
&lt;h4 class=&quot;page-name&quot;&gt;&lt;strong&gt;Model Evaluation&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Submissions are evaluated on&lt;/span&gt; &lt;a href=&quot;https://en.wikipedia.org/wiki/Root-mean-square_deviation&quot; target=&quot;_blank&quot;&gt;Root-Mean-Squared-Error (RMSE)&lt;/a&gt; &lt;span style=&quot;color:#000000;&quot;&gt;between the logarithm of the predicted value and the logarithm of the observed sales price. (Taking logs means that errors in predicting expensive houses and cheap houses will affect the result equally.)  In simple terms this means that the lower the RMSE value, greater is the accuracy of your prediction model.&lt;/span&gt;&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;About the dataset&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;The dataset is split into training and testing files where the training dataset has &lt;em&gt;81&lt;/em&gt; variables in &lt;em&gt;1460&lt;/em&gt; rows and the testing dataser has &lt;em&gt;80&lt;/em&gt; variables in &lt;em&gt;1459&lt;/em&gt; rows. These variables focus on the quantity and quality of many physical attributes of the real estate property. &lt;em&gt; &lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;There are a large number of categorical variables (23 nominal, 23 ordinal) associated with this data set. They range from 2 to 28 classes with the smallest being STREET (gravel or paved) and the largest being NEIGHBORHOOD (areas within the Ames city limits). The nominal variables typically identify various types of dwellings, garages, materials, and environmental conditions while the ordinal variables typically rate various items within the property.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;The 14 discrete variables typically quantify the number of items occurring within the house. Most are specifically focused on the number of kitchens, bedrooms, and bathrooms (full and half) located in the basement and above grade (ground) living areas of the home.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;In general the 20 continuous variables relate to various area dimensions for each observation. In addition to the typical lot size and total dwelling square footage found on most common home listings, other more specific variables are quantified in the data set.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;“&lt;em&gt;A strong analysis should include the interpretation of the various coefficients, statistics, and plots associated with their model and the verification of any necessary assumptions.”&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;em&gt;&lt;strong&gt;An interesting feature of the dataset&lt;/strong&gt;&lt;/em&gt; is that &lt;span style=&quot;text-decoration:underline;&quot;&gt;several  of the predictors are labelled as NA when actually they are not missing values and correspond to actual data points&lt;/span&gt;. This can be verified from the data dictionary where variable like Alley, Pool etc have NA value that correspond to &lt;em&gt;No Alley Access&lt;/em&gt; and &lt;em&gt;No Pool &lt;/em&gt;respectively.&lt;em&gt; &lt;/em&gt;This &lt;a href=&quot;http://stackoverflow.com/questions/19379081/how-to-replace-na-values-in-a-table-for-selected-columns-data-frame-data-tab&quot; target=&quot;_blank&quot;&gt;SO question&lt;/a&gt; that was answered by the user ‘flodel’ solves this problem of recoding specific columns of a dataset. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;A total of &lt;i&gt;357&lt;/i&gt; missing values are present in training predictors (&lt;em&gt;LotFrontage-259, MasVnrType-8, MasVnrArea-8, Electrical-1, GarageYrBlt-81&lt;/em&gt;) and &lt;i&gt;358&lt;/i&gt; missing values in testing dataset predictors (&lt;em&gt;MSZoning-4,&lt;/em&gt; &lt;em&gt;LotFrontage-227,  Exterior1st-1, Exterior2nd-1, MasVnrType-16, MasVnArea-15, BsmtFinSF1-1, BsmtFinType2-1, BsmtFinSF2-1, BsmtUnfSF-1, TotalBsmtSF-1, BsmtFullBath-2, BsmtHalfBath-2, KitchenQual-1, Functional-2, GarageYrBlt-78, SaleType-1&lt;/em&gt;).&lt;/span&gt;&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;Data Preprocessing&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Some basic problems that need to be solved first namely, &lt;em&gt;data dimensionality reduction, missing value treatment, correlation, dummy coding. &lt;/em&gt;A common question that most ask is that how to determine the relevant predictors in a high dimensional dataset as this. The approach that I will use for dimensionality reduction will be two fold, first I will check for zero variance predictors. &lt;/span&gt;&lt;/p&gt;
&lt;h4&gt;(a) &lt;em&gt;Check for Near Zero Variance Predictors&lt;/em&gt;&lt;/h4&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;A predictor with zero variability does not contribute anything to the prediction model and can be removed. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;em&gt;&lt;span style=&quot;text-decoration:underline;&quot;&gt;Computing&lt;/span&gt;: &lt;/em&gt;This can easily be accomplished by using the &lt;em&gt;nearZeroVar() &lt;/em&gt;method from the &lt;em&gt;caret package. &lt;/em&gt;In training dataset, there are 21 near zero variance variables namely (&lt;/span&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;em&gt;‘Street’ ‘LandContour’ ‘Utilities’ ‘LandSlope’ ‘Condition2’ ‘RoofMatl’ ‘BsmtCond’ ‘BsmtFinType2’ ‘BsmtFinSF2’ ‘Heating’ ‘LowQualFinSF’ ‘KitchenAbvGr’ ‘Functional’ ‘GarageQual’ ‘GarageCond’ ‘EnclosedPorch’ ‘X3SsnPorch’ ‘ScreenPorch’ ‘PoolArea’ ‘MiscFeature’ ‘MiscVal’&lt;/em&gt;) &lt;em&gt;and in the testing dataset there are 19 near zero variance predictors namely (‘Street’ ‘Utilities’ ‘LandSlope’ ‘Condition2’ ‘RoofMatl’ ‘BsmtCond’ ‘BsmtFinType2’ ‘Heating’ ‘LowQualFinSF’ ‘KitchenAbvGr’ ‘Functional’ ‘GarageCond’ ‘EnclosedPorch’ ‘X3SsnPorch’ ‘ScreenPorch’ ‘PoolArea’ ‘MiscVal’). &lt;/em&gt;Post removal of these predictors from both the training and testing dataset, the data dimension is reduced to &lt;em&gt;60 predictors for train data &lt;/em&gt;and &lt;em&gt;61 predictors &lt;/em&gt;each. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(b) &lt;em&gt;Missing data treatment&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;There are two types of missing data;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;(i) MCAR (Missing Completetly At Random) &amp;amp; (ii) MNAR (Missing Not At Random)&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Usually, MCAR is the desirable scenario in case of missing data. For this analysis I will assume that MCAR is at play. Assuming data is MCAR, too much missing data can be a problem too. Usually a safe maximum threshold is 5% of the total for large datasets. If missing data for a certain feature or sample is more than 5% then you probably should leave that feature or sample out. We therefore check for features (columns) and samples (rows) where more than 5% of the data is missing using a simple function. Some good references are&lt;/span&gt; &lt;a href=&quot;http://stackoverflow.com/questions/4862178/remove-rows-with-nas-missing-values-in-data-frame&quot; target=&quot;_blank&quot;&gt;1&lt;/a&gt; &lt;span style=&quot;color:#000000;&quot;&gt;and&lt;/span&gt; &lt;a href=&quot;http://stackoverflow.com/questions/4605206/drop-data-frame-columns-by-name&quot; target=&quot;_blank&quot;&gt;2&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;span style=&quot;text-decoration:underline;&quot;&gt;&lt;em&gt;Computing&lt;/em&gt;&lt;/span&gt;: I have used the &lt;em&gt;VIM package &lt;/em&gt;in R for missing data visualization. I set the threshold at 0.80, any predictors equal to or above this threshold need no imputation and should be removed. Post removal of the near zero variance predictors, I next check for high missing values and I find that there are no predictors with high missing values in either the train or test data. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000080;&quot;&gt;Important Note:&lt;/span&gt; &lt;span style=&quot;color:#000000;&quot;&gt;As per this &lt;a href=&quot;https://www.r-bloggers.com/imputing-missing-data-with-r-mice-package/&quot; target=&quot;_blank&quot;&gt;r-blogger’s post&lt;/a&gt;, it is not advisable to use mean imputation for continuous predictors because it can affect the variance in the data. Also, one should avoid using the mode imputation for categorical variables so I use the &lt;em&gt;mice library&lt;/em&gt; for missing valueimputation for the continuous variables. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;(c) Correlation treatment&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;Correlation refers to a technique used to measure the relationship between two or more variables.&lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;When two objects are correlated, it means that they vary together.&lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot;&gt;Positive correlation means that high scores on one are associated with high scores on the other, and that low scores on one are associated with low scores on the other. Negative correlation, on the other hand, means that high scores on the first thing are associated with low scores on the second. Negative correlation also means that low scores on the first are associated with high scores on the second.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;font-weight:300;&quot;&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Pearson &lt;em&gt;r&lt;/em&gt; is a statistic that is commonly used to calculate bivariate correlations. Or better said, its checks for linear relations. &lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;font-weight:300;&quot;&gt;&lt;span style=&quot;color:#000000;&quot;&gt;For an Example Pearson &lt;em&gt;r&lt;/em&gt; = -0.80, &lt;em&gt;p&lt;/em&gt; &amp;lt; .01. What does this mean?&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;font-weight:300;&quot;&gt;&lt;span style=&quot;color:#000000;&quot;&gt;To interpret correlations, four pieces of information are necessary.&lt;/span&gt;
&lt;span style=&quot;color:#000000;&quot;&gt;&lt;b&gt;&lt;strong&gt;1.   &lt;em&gt;The numerical value of the correlation coefficient.&lt;/em&gt;&lt;/strong&gt;&lt;/b&gt;Correlation coefficients can vary numerically between 0.0 and 1.0. The closer the correlation is to 1.0, the stronger the relationship between the two variables. A correlation of 0.0 indicates the absence of a relationship. If the correlation coefficient is –0.80, which indicates the presence of a strong relationship.&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;font-weight:300;&quot;&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;b style=&quot;line-height:1.7;&quot;&gt;&lt;strong&gt;&lt;em&gt;2. The sign of the correlation coefficient&lt;/em&gt;.&lt;/strong&gt;&lt;/b&gt;A positive correlation coefficient means that as variable 1 increases, variable 2 increases, and conversely, as variable 1 decreases, variable 2 decreases. In other words, the variables move in the same direction when there is a positive correlation. A negative correlation means that as variable 1 increases, variable 2 decreases and vice versa. In other words, the variables move in opposite directions when there is a negative correlation. The negative sign indicates that as class size increases, mean reading scores decrease.&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;font-weight:300;&quot;&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;b style=&quot;line-height:1.7;&quot;&gt;&lt;strong&gt;&lt;em&gt;3. The statistical significance of the correlation. &lt;/em&gt;&lt;/strong&gt;&lt;/b&gt;&lt;span style=&quot;line-height:1.7;&quot;&gt;A statistically significant correlation is indicated by a probability value of less than 0.05. This means that the probability of obtaining such a correlation coefficient by chance is less than five times out of 100, so the result indicates the presence of a relationship.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;In any data anlysis activity, the analyst should always check for highly correlated variables and remove them from the dataset because correlated predictors do not quantify &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;&lt;strong&gt;4.   &lt;i&gt;The effect size of the correlation.&lt;/i&gt;&lt;/strong&gt;For correlations, the effect size is called the coefficient of determination and is defined as &lt;i&gt;r&lt;/i&gt;&lt;sup&gt;2&lt;/sup&gt;. The coefficient of determination can vary from 0 to 1.00 and indicates that the proportion of variation in the scores can be predicted from the relationship between the two variables.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;A correlation can only indicate the presence or absence of a relationship, not the nature of the relationship. &lt;i&gt;&lt;strong&gt;Correlation is not causation&lt;/strong&gt;.&lt;/i&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;How Problematic is Multicollinearity?&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;Moderate multicollinearity may not be problematic. However, severe multicollinearity is a problem because it can increase the variance of the coefficient estimates and make the estimates very sensitive to minor changes in the model. The result is that the coefficient estimates are unstable and difficult to interpret. Multicollinearity saps the statistical power of the analysis, can cause the coefficients to switch signs, and makes it more difficult to specify the correct model. According to Tabachnick &amp;amp; Fidell (1996) the independent variables with a bivariate correlation more than .70 should not be included in multiple regression analysis.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;text-decoration:underline;color:#000000;&quot;&gt;&lt;em&gt;&lt;strong&gt;Computing&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;To detect highly correlated predictors in the data, I used the &lt;em&gt;findCorrelation()&lt;/em&gt; method of the caret library and I find that there are four predictors in the training dataset with more than 80% correlation and these are “YearRemodAdd”,”OverallCond”,”BsmtQual”,”Foundation” which I then remove from the train data thereby reducing the data dimension to 56. I follow the similar activity for the test data and I find that there are two predictors with more than 80% correlation and these are “Foundation” “LotShape” which I then remove from the test data.
The final data dimensions are 1460 rows in 56 columns in train data and 1460 rows in 59 columns in the test data.
&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;The R code used in this post can be can be accessed on my &lt;a style=&quot;color:#000000;&quot; href=&quot;https://github.com/duttashi/House-Price-Prediction/blob/master/scripts/data_preproc.R&quot; target=&quot;_blank&quot;&gt;github&lt;/a&gt; account and my Kaggle notebook can be viewed &lt;a href=&quot;https://www.kaggle.com/ashishdutt/house-prices-advanced-regression-techniques/ahoy-all-relevant-guests-on-board-let-s-sail&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. &lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000000;&quot;&gt;In the next post, I will discuss on the issue of outlier detection, skewness resolution and data visualization.&lt;/span&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Learning from data science competitions- baby steps]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/learning-from-data-science-competitions-xgboost-algorithm/" />
  <id>https://duttashi.github.io/blog/learning-from-data-science-competitions-xgboost-algorithm</id>
  <published>2016-08-24T08:17:00+00:00</published>
  <updated>2016-08-24T08:17:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;Off lately a considerable number of winner machine learning enthusiasts have used &lt;a href=&quot;https://github.com/dmlc/xgboost&quot; target=&quot;_blank&quot;&gt;XGBoost&lt;/a&gt; as their predictive analytics solution. This algorithm has taken a preceedence over the traditional tree based algorithms like Random Forests and Neural Networks.&lt;/p&gt;

&lt;p&gt;The acronym &lt;strong&gt;Xgboost &lt;/strong&gt;stands for e&lt;strong&gt;X&lt;/strong&gt;treme G&lt;strong&gt;radient &lt;/strong&gt;&lt;strong&gt;B&lt;/strong&gt;oosting package. The creators of this algorithm presented its &lt;a href=&quot;https://www.kaggle.com/tqchen/otto-group-product-classification-challenge/understanding-xgboost-model-on-otto-data&quot; target=&quot;_blank&quot;&gt;implementation&lt;/a&gt; by winning the Kaggle Otto Group competition. Another interesting tutorial is listed &lt;a href=&quot;https://www.r-bloggers.com/an-introduction-to-xgboost-r-package/&quot;&gt;here&lt;/a&gt; and the complete documentation can be seen &lt;a href=&quot;http://xgboost.readthedocs.io/en/latest/R-package/xgboostPresentation.html&quot;&gt;here&lt;/a&gt;. This page lists a comprehensive list of &lt;a href=&quot;https://github.com/dmlc/xgboost/tree/master/demo#tutorials&quot; target=&quot;_blank&quot;&gt;awesome tutorials&lt;/a&gt; on it and this one shows &lt;a href=&quot;http://fr.slideshare.net/MichaelBENESTY/feature-importance-analysis-with-xgboost-in-tax-audit&quot; target=&quot;_blank&quot;&gt;feature importance&lt;/a&gt;  It is a classification algorithm and the reasons of its superior efficiency are,&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;It&apos;s written in C++&lt;/li&gt;
	&lt;li&gt;It can be multithreaded on a single machine&lt;/li&gt;
	&lt;li&gt;It preprocesses the data before the training algorithm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Unlike its previous tree based predecessors it takes care of many of the inherent problems associated with tree based classification. For example, “By setting the parameter &lt;code&gt;early_stopping&lt;/code&gt;,&lt;code&gt;xgboost&lt;/code&gt; will terminate the training process if the performance is getting worse in the iteration.” [1]&lt;/p&gt;

&lt;p&gt;As with all machine learning algorithms, xgboost works on numerical data. If categorical data is there then use one-hot encoding from the R caret package to transform the categorical data (factors)  to numerical dummy variables that can be used by the algorithm. Here is a good &lt;a href=&quot;http://stackoverflow.com/questions/24142576/one-hot-encoding-in-r-categorical-to-dummy-variables&quot;&gt;SO discussion&lt;/a&gt; on one-hot encoding in R. This &lt;a href=&quot;https://www.quora.com/What-is-one-hot-encoding-and-when-is-it-used-in-data-science&quot; target=&quot;_blank&quot;&gt;Quora thread&lt;/a&gt; discusses the question on “&lt;em&gt;when should you be using one-hot encoding in data science?”.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Okay, enough of background information. Now let’s see some action.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem Description&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The objective is to predict whether a donor has donated blood in March 2007. To this effect, the dataset for this study is derived from &lt;a href=&quot;https://www.drivendata.org/competitions/2/page/7/&quot; target=&quot;_blank&quot;&gt;DrivenData&lt;/a&gt; which incidentally is also hosting a practice data science competition on the same.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem Type: Classification&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;And how did I figure this out? Well, one has to read the problem description carefully as well as the submission format. In this case, the submission format categorically states that the response variable to be either 1 or 0 which is proof enough that this is a classification problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choice of predictive algorithm&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Boy, that really let my head spinning for some time. You see I was torn between the traditionalist approach and the quickie (get it out there) approach. First, I thought let me learn and explore what story is the data trying to tell me (&lt;em&gt;traditionalist approach) &lt;/em&gt;but then I gave up on this idea because of my past experiences. Once I venture this path, I get stuck somewhere or keep digging in a quest to perfect my solution and time slips away. So this time, I said to myself, “&lt;em&gt;Enough! let me try the quickie approach that is get it (read the solution) out of the lab as quickly as possible. And I can later continue to improve the solution”&lt;/em&gt;.  So following this intuition and a very much required &lt;em&gt;self-morale boost&lt;/em&gt; (&lt;em&gt;that is what happens to you when you are out in the laboratory all by yourself&lt;/em&gt;) I decided to choose XGBoost as the preliminary predictive classification algorithm. Being neck deep into clustering algorithms (&lt;em&gt;which is my research area) &lt;/em&gt;and if truth be told I never really had a penchant for supervised algorithms (&lt;em&gt;once again a gut feeling that they were too easy because you already know the outcome. Dammn! I was so wrong)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choice of tool&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For sometime now, I had been juggling between the choice of being a pythonist or an R user, &lt;em&gt;“To be or not to be, that is the question”. &lt;/em&gt; The worldwide web has some great resources on this discussion and you can take your pick. In my case, I decided to chose and stick with R because of two reasons, primarily its a statistical programming language and two predictive analytics or machine learning has its roots in statistics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The&lt;/strong&gt;  &lt;strong&gt;Strategy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;“Visualize it, &lt;em&gt;Clean it, Smoothe it, Publish it”.  &lt;/em&gt;&lt;/p&gt;

&lt;p&gt;After reading the data in R, my first step was to plot as many meaningful graphs as possible to detect a trend or a relationship. I started with line plots but before I get into that, a brief about the dataset. The dataset was pre-divided into training and testing data. The training data had 576 observations in 6 continuous variables of which the last variable was the response. Similarly, the test data had 200 observations in 5 continuous variables.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Read in the data
train.data&amp;lt;- read.csv(&quot;data//blood_donation_train.csv&quot;, sep = &quot;,&quot;, header=TRUE)
test.data&amp;lt;-read.csv(&quot;data//blood_donation_test.csv&quot;, sep = &quot;,&quot;, header=TRUE) 
# Check the data structure 
&amp;gt; str(train.data)
&apos;data.frame&apos;: 576 obs. of 6 variables:
$ ID : int 619 664 441 160 358 335 47 164 736 436 ...
$ Months.since.Last.Donation : int 2 0 1 2 1 4 2 1 5 0 ...
$ Number.of.Donations : int 50 13 16 20 24 4 7 12 46 3 ...
$ Total.Volume.Donated..c.c..: int 12500 3250 4000 5000 6000 1000 1750 3000 11500 750 ...
$ Months.since.First.Donation: int 98 28 35 45 77 4 14 35 98 4 ...
$ Made.Donation.in.March.2007: int 1 1 1 1 0 0 1 0 1 0 ...

&amp;gt; str(test.data)
&apos;data.frame&apos;: 200 obs. of 5 variables:
$ ID : int 659 276 263 303 83 500 530 244 249 728 ...
$ Months.since.Last.Donation : int 2 21 4 11 4 3 4 14 23 14 ...
$ Number.of.Donations : int 12 7 1 11 12 21 2 1 2 4 ...
$ Total.Volume.Donated..c.c..: int 3000 1750 250 2750 3000 5250 500 250 500 1000 ...
$ Months.since.First.Donation: int 52 38 4 38 34 42 4 14 87 64 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;b&gt; a. Data Visualization&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;I first started with the base R graphics library, you know commands like &lt;em&gt;hist() or plot()&lt;/em&gt; but honestly speaking the visualization was draconian, awful. You see it did not appeal to me at all and thus my grey cells slumbered. Then, I chose the ggplot2 library. Now, that was something. The visualizations were very appealing inducing the grey mater to become active.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Learning note&lt;/strong&gt;: So far, I have not done any data massaging activity like centering or scaling. Why? The reason is one will find patterns in the raw data and not in a centered or scaled data.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Off the numerous graphs I plotted, I finally settled on the ones that displayed some proof of variablity. I wanted to see if there was a cohort of people who were donating more blood than normal. I was interested in this hypothesis because there are some cool folks out there (pun intended) for whom blood donation is a business. Anyway, if you look at the line plot 1 that explores my perceived hypothesis, you will notice a distinct cluster of people who donated between 100 cc to 5000 cc in approx 35 months range.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot-2-1.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Line plot 1: Distribution of total blood volume donated in year 2007-2010&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;highDonation2&amp;lt;- subset(train.data, Total.Volume.Donated..c.c..&amp;gt;=100 &amp;amp; Total.Volume.Donated..c.c..&amp;lt;=5000 &amp;amp; Months.since.Last.Donation&amp;lt;=35)

p5&amp;lt;- ggplot() +geom_line(aes(x=Total.Volume.Donated..c.c.., y=Months.since.Last.Donation, colour=Total.Volume.Donated..c.c..),size=1 ,data=highDonation2, stat = &quot;identity&quot;)

p5 # Visualize it

highDonation2.3&amp;lt;- subset(train.data, Total.Volume.Donated..c.c..&amp;gt;800 &amp;amp; Total.Volume.Donated..c.c..&amp;lt;=5000 &amp;amp; Months.since.Last.Donation&amp;lt;=35)

str(highDonation2.3)

p6.3&amp;lt;- ggplot() +geom_line(aes(x=Total.Volume.Donated..c.c.., y=Months.since.Last.Donation, colour=Total.Volume.Donated..c.c..),size=1 ,data=highDonation2.3, stat = &quot;identity&quot;)

p6.3 # Visualize it

highDonation2.4&amp;lt;- subset(train.data, Total.Volume.Donated..c.c..&amp;gt;2000 &amp;amp; Total.Volume.Donated..c.c..&amp;lt;=5000 &amp;amp; Months.since.Last.Donation&amp;lt;=6)

p6.2&amp;lt;- ggplot() +geom_line(aes(x=Total.Volume.Donated..c.c.., y=Months.since.Last.Donation, colour=Total.Volume.Donated..c.c..),size=1 ,data=highDonation2.4, stat = &quot;identity&quot;)

p6.2 # Visualize it
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I then took a subset of these people and I noticed that total observations was 562 which is just 14 observations less than the original dataset. Hmm.. maybe I should narrow my range down a bit more.  so then I narrowed the range between 1000 cc to 5000 cc  of blood donated in the 1 year and I find there are 76 people and when I further narrow it down to between 2000-5000 cc of blood donation in 6 months, there are 55 people out of 576 as shown in line plot 2.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot-2-2.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Line plot 2: Distribution of total blood volume (in cc) donated in 06 months of 2007&lt;/p&gt;

&lt;p&gt;If you look closely at the line plot 2, you will notice a distinct spike between 4 and 6 months. (&lt;em&gt;Ohh baby, things are getting soo hot and spicy now, I can feel the mounting tension). &lt;/em&gt;Let’s plot it. And lo behold there are 37 good folks who have donated approx 2000 cc to 5000 cc in the months of May and June, 2007.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot-2-3.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Line plot 3: Distribution of total blood volume (in cc) donated in May &amp;amp; June of 2007&lt;/p&gt;

&lt;p&gt;I finally take this exploration one step further wherein I search for a pattern or a group of people who had made more than 20 blood donations in six months of year 2007. And they are 08 such good guys who were hyperactive in blood donation. This I show in line plot 4.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/rplot2-4.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Line plot 4: Distribution of high blood donors in six months of year 2007&lt;/p&gt;

&lt;p&gt;This post is getting too long now. I thin it will not be easier to read and digest it. So I will stop here and continue it in another post.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaway Learning Points&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A few important points that have helped me a lot.&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;A picture is worth a thousand words. Believe in the power of visualizations&lt;/li&gt;
	&lt;li&gt;Always, begin the data exploration with a hypothesis or question and then dive into the data to prove it. You will find something if not anything.&lt;/li&gt;
	&lt;li&gt;Read and regurgiate on the research question, read material related to it to ensure that the data at hand is enough to answer your questions.&lt;/li&gt;
	&lt;li&gt;If you are a novice, don&apos;t you dare make assumptions or develop any preconceived notions about knowledge nuggets (&lt;em&gt;for example, my initial aversion towards supervised learning as noted above) &lt;/em&gt;that you have not explored.&lt;/li&gt;
	&lt;li&gt;Get your fundamentals strong in statistics, linear algebra and probability for these are the base of data science.&lt;/li&gt;
	&lt;li&gt;Practice programming your learnings and it will be best if create an end to end project. Needless to mention, the more you read, the more you write and the more you code, you will get better in your craft.And stick to one programming tool.&lt;/li&gt;
	&lt;li&gt;Subscribe to data science blogs like R-bloggers, kaggle, driven data etc. Create a blog which will serve as your live portfolio.&lt;/li&gt;
	&lt;li&gt;I think to master the art of story telling with data takes time and a hell lot of reading and analysis.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the next part of this post, I will elaborate and discuss on my strategy that i undertook to submit my initial entry for predicting blood donor, competition hosted at driven data.&lt;/p&gt;

&lt;p&gt;References&lt;/p&gt;

&lt;p&gt;“An Introduction To Xgboost R Package”. R-bloggers.com. N.p., 2016. Web. 23 Aug. 2016.&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Data Splitting]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/data-splitting/" />
  <id>https://duttashi.github.io/blog/data-splitting</id>
  <published>2016-08-08T13:41:00+00:00</published>
  <updated>2016-08-08T13:41:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;A few common steps in data model building are;&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Pre-processing the predictor data (predictor - independent variable&apos;s)&lt;/li&gt;
	&lt;li&gt;Estimating the model parameters&lt;/li&gt;
	&lt;li&gt;Selecting the predictors for the model&lt;/li&gt;
	&lt;li&gt;Evaluating the model performance&lt;/li&gt;
	&lt;li&gt;Fine tuning the class prediction rules&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;“One of the first decisions to make when modeling is to decide which samples will be used to evaluate performance. Ideally, the model should be evaluated on samples that were not used to build or fine-tune the model, so that they provide an unbiased sense of model effectiveness. When a large amount of data is at hand, a set of samples can be set aside to evaluate the final model. The “training” data set is the general term for the samples used to create the model, while the “test” or “validation” data set is used to qualify performance.” (Kuhn, 2013)&lt;/p&gt;

&lt;p&gt;In most cases, the training and test samples are desired to be as homogenous as possible. Random sampling methods can be used to create similar data sets.
Let’s take an example. I will be using R programming language and will use two datasets from the UCI Machine Learning repository.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# clear the workspace
&amp;gt; rm(list=ls())
# ensure the process is reproducible
&amp;gt; set.seed(2)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The first dataset is the Wisconsin Breast Cancer Database
Description: Predict whether a cancer is malignant or benign from biopsy details.
Type: Binary Classification
Dimensions: 699 instances, 11 attributes
Inputs: Integer (Nominal)
Output: Categorical, 2 class labels
UCI Machine Learning Repository: &lt;a href=&quot;https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Original)&quot; target=&quot;_blank&quot;&gt;Description&lt;/a&gt;
Published accuracy results: &lt;a href=&quot;http://www.is.umk.pl/projects/datasets.html#Wisconsin&quot; target=&quot;_blank&quot;&gt;Summary&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;span style=&quot;color:#000080;&quot;&gt;&lt;strong&gt;Splitting based on Response/Outcome/Dependent variable&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Let’s say, I want to take a sample of 70% of my data, I will do it like&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; BreastCancer[sample(nrow(BreastCancer), 524),] # 70% sample size
&amp;gt; table(smpl$Class)
benign malignant
345       179
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p style=&quot;text-align:left;&quot;&gt;And when I plot it is shown in figure 1 below;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://duttashi.github.io/images/data-split-1.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Figure 1: Plot of categorical class variable&lt;/p&gt;

&lt;p style=&quot;text-align:left;&quot;&gt;However, if you want to give different probabilities of being selected for the elements, lets say, elements that cancer type is benign has probability 0.25, while those whose cancer type is malignant has prob 0.75, you should do like&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; prb &amp;lt;- ifelse(BreastCancer$Class ==&quot;benign&quot;,0.25, 0.75)
&amp;gt; smpl&amp;lt;- BreastCancer[sample(nrow(BreastCancer), 524, prob = prb),]
&amp;gt; table(smpl$Class)
benign malignant
299     225
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p style=&quot;text-align:left;&quot;&gt;And when I plot it is like shown in figure 2,&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; plot(smpl$Class)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p style=&quot;text-align:left;&quot;&gt;

![image](https://duttashi.github.io/images/data-split-1-1.png)

Figure 2: Plot of categorical class variable with probability based sample split

If the outcome or the response variable is categorical then split the data using stratified random sampling that applies random sampling within subgroups (such as the classes). In this way, there is a higher likelihood that the outcome distributions will match. The function &lt;em&gt;createDataPartition &lt;/em&gt;of the caret package can be used to create balanced splits of the data or random stratified split. I show it using an example in R as given;

	&amp;gt; library(caret)
	&amp;gt; train.rows&amp;lt;- createDataPartition(y= BreastCancer$Class, p=0.7, list = FALSE)
	&amp;gt; train.data&amp;lt;- BreastCancer[train.rows,] # 70% data goes in here
	&amp;gt; table(train.data$Class)
	benign malignant
	321       169

And the plot shown in figure 3

![image](https://duttashi.github.io/images/data-split-2-train.png)

Figure 3: Plot of categorical class variable from train sample data

Similarly, I do for the test sample data as given

	&amp;gt; test.data&amp;lt;- BreastCancer[-train.rows,] # 30% data goes in here
	&amp;gt; table(test.data$Class)
	benign malignant
	137        72
	&amp;gt; plot(test.data$Class)

And I show the plot in figure 4,

![image](https://duttashi.github.io/images/data-split-2-test.png)

Figure 4: Plot of categorical class variable from test sample data

&lt;span style=&quot;color:#000080;&quot;&gt;&lt;strong&gt;Splitting based on Predictor/Input/Independent variables&lt;/strong&gt;&lt;/span&gt;

So far we have seen the data splitting was based on the outcome or the response variable. However, the data can be split on the predictor variables too. This is achieved by &lt;em&gt;maximum dissimilarity sampling &lt;/em&gt; as proposed by Willet (1999) and Clark (1997).  This is particularly useful for unsupervised learning where there are no response variables. There are many methods in R to calculate dissimilarity. caret uses the proxy package. See the manual for that package for a list of available measures. Also, there are many ways to calculate which sample is “most dissimilar”. The argument obj can be used to specify any function that returns a scalar measure. caret includes two functions, minDiss and sumDiss, that can be used to maximize the minimum and total dissimilarities, respectfully.

References

Kuhn, M.,&amp;amp; Johnson, K. (2013). Applied predictive modeling (pp. 389-400). New York: Springer.

Willett, P. (1999), &quot;Dissimilarity-Based Algorithms for Selecting Structurally Diverse Sets of Compounds,&quot; Journal of Computational Biology, 6, 447-457.
&lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Big or small-lets save them all- Visualizing Data]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/big-or-small-lets-save-them-all-visualizing-data/" />
  <id>https://duttashi.github.io/blog/big-or-small-lets-save-them-all-visualizing-data</id>
  <published>2016-01-23T00:00:00+00:00</published>
  <updated>2016-01-23T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;I am revisiting the research question once again, “Can alcohol consumption increase the risk of breast cancer in working class women? and the variables to explore are;&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;‘alcconsumption’- average alcohol consumption, adult (15+) per capita consumption in litres pure alcohol&lt;/li&gt;
	&lt;li&gt;‘breastcancerper100TH’- Number of new cases of breast cancer in 100,000 female residents during the certain year&lt;/li&gt;
	&lt;li&gt;‘femaleemployrate’- Percentage of female population, age above 15, that has been employed during the given year&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;From the research question, the &lt;span style=&quot;text-decoration:underline;&quot;&gt;dependent variable&lt;/span&gt; or the response or the outcome variable &lt;span style=&quot;text-decoration:underline;&quot;&gt;is breast cancer per 100&lt;sup&gt;th&lt;/sup&gt; women&lt;/span&gt; and the &lt;span style=&quot;text-decoration:underline;&quot;&gt;independent variables&lt;/span&gt; are &lt;span style=&quot;text-decoration:underline;&quot;&gt;alcohol consumption and female employ rate&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Let us now look at the measures of center and spread of the aforementioned variables. This will help us to better understand our quantitative variables. In python, to measure the mean, median, mode, minimum and maximum value, standard deviation and percentiles of a quantitative variable can be computed using the describe() function as shown below&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;#using the describe function to get the standard deviation and other descriptive statistics of our variables
desc1=data[&apos;breastcancerper100th&apos;].describe()
desc2=data[&apos;femaleemployrate&apos;].describe()
desc3=data[&apos;alcconsumption&apos;].describe()
print &quot;\nBreast Cancer per 100th person\n&quot;, desc1
print &quot;\nfemale employ rate\n&quot;, desc2
print &quot;\nAlcohol consumption in litres\n&quot;, desc3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and the result will be&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Breast Cancer per 100th person
count    173.000000
mean      37.402890
std       22.697901
min        3.900000
25%       20.600000
50%       30.000000
75%       50.300000
max      101.100000 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So, on an average there are 37 women per 100th in whom breast cancer is reported with a standard deviation of +- 22.&lt;/p&gt;

&lt;p&gt;Similarly, I next find the mean and standard deviation of the variable, ‘femalemployrate’&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;female employ rate
count    178.000000
mean      47.549438
std       14.625743
min       11.300000
25%       38.725000
50%       47.549999
75%       55.875000
max       83.300003 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I can say that on an average there are 47% women employed in a given year with a deviation of +-15.&lt;/p&gt;

&lt;p&gt;Finally, I find the mean and deviation of the variable, ‘alcconsumption’ given as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Alcohol consumption in litres
count    187.000000
mean       6.689412
std        4.899617
min        0.030000
25%        2.625000
50%        5.920000
75%        9.925000
max       23.010000 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This can be interpreted as among adults (15+) the average alcohol consumption in liters per capita income is 7 liters (rounding off) with a standard deviation of +-5 (rounding off).&lt;/p&gt;

&lt;p&gt;Therefore the inference will be that in 47% &lt;em&gt;(+-15)&lt;/em&gt; employed women in a given year the average alcohol consumption is 7 liters (+-5) per capita and the number of breast cancer cases reported on an average are 37 (+-22) per 100th female residents.&lt;/p&gt;

&lt;p&gt;Another, alternative method of finding descriptive statistic for your variables is to use the describe() on the dataframe which in this case is called ‘data’ as given&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;data.describe()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I now provide the univariate data analysis of the individual variables&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Now plotting the univariate quantitative variables using the distribution plot
sub5=sub4.copy()
sns.distplot(sub5[&apos;alcconsumption&apos;].dropna(),kde=True)
plt.xlabel(&apos;Alcohol consumption in litres&apos;)
plt.title(&apos;Breast cancer in working class women&apos;)
plt.show()

&apos;&apos;&apos;Note: Although there is no need to use the show() method for ipython notebook as %matplotlib inline does the trick but I am adding it here because matplotlib inline does not work for an IDE like Pycharm and for that i need to use plt.show&apos;&apos;&apos;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the barchart is&lt;/p&gt;

&lt;p&gt;&lt;img class=&quot; size-full wp-image-1227 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/fd1.png&quot; alt=&quot;fd1&quot; width=&quot;521&quot; height=&quot;380&quot; /&gt;&lt;/p&gt;
&lt;p style=&quot;text-align:center;&quot;&gt;Bar Chart 1: Alcohol consumption in liters&lt;/p&gt;
&lt;p&gt;Notice, we have two peaks in bar chart 1. So it is a bimodal distribution which means that there are two distinct groups of data. The two groups are evident from the bar chart 1, where the first group (or the first peak) is centered at 5 liters of alcohol consumption and the second group (or the second peak) is centered at 35 liters of alcohol consumption&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;sns.distplot(sub5[&apos;breastcancerper100th&apos;].dropna(),kde=True)
plt.xlabel(&apos;Breast cancer per 100th women&apos;)
plt.title(&apos;Breast cancer in working class women&apos;)
plt.show() 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the barchart is&lt;/p&gt;

&lt;p&gt;&lt;img class=&quot; size-full wp-image-1233 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/fd2.png&quot; alt=&quot;fd2&quot; width=&quot;501&quot; height=&quot;365&quot; /&gt;&lt;/p&gt;
&lt;p style=&quot;text-align:center;&quot;&gt;Bar Chart 2: Breast cancer per 100th women&lt;/p&gt;
&lt;p style=&quot;text-align:left;&quot;&gt;Similarly, in bar chart 2,  there are two peaks so it is a bimodal distribution where the first group is centered at 35 cases of new breast cancer reported and the second group  is centered at 86 cases of new breast cancer reported.&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;sns.distplot(sub5[&apos;femaleemployrate&apos;].dropna(),kde=True)
plt.xlabel(&apos;Female employee rate&apos;)
plt.title(&apos;Breast cancer in working class women&apos;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the bar chart is&lt;/p&gt;

&lt;p&gt;&lt;img class=&quot; size-full wp-image-1237 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/fd3.png&quot; alt=&quot;fd3&quot; width=&quot;495&quot; height=&quot;365&quot; /&gt;&lt;/p&gt;
&lt;p style=&quot;text-align:center;&quot;&gt;Bar Chart 3: Female Employed Rate above 15+ (in %age) in a given year&lt;/p&gt;
&lt;p style=&quot;text-align:left;&quot;&gt;In bar chart 3 we see a unimodal distribution where there is one group with maximum number of 42.&lt;/p&gt;
&lt;p&gt;Now that we have seen the individual variable visually, I will now come back to the research question to see if there is any relationship between the research questions. Recall, for this study the various hypotheses were;&lt;/p&gt;

&lt;p&gt;H&lt;sub&gt;0 &lt;/sub&gt;(Null Hypothesis) =   Breast cancer is not caused by alcohol consumption&lt;/p&gt;

&lt;p&gt;H&lt;sub&gt;1 &lt;/sub&gt;(Alternative Hypothesis) = Alcohol consumption causes breast cancer&lt;/p&gt;

&lt;p&gt;H&lt;sub&gt;2 &lt;/sub&gt;(Alternative Hypothesis) = Female employee are susceptible to increased risk of breast cancer.&lt;/p&gt;

&lt;p&gt;So, let’s check if there is any relationship between the breast cancer and alcohol consumption.&lt;/p&gt;

&lt;p&gt;Please note here that since all the variables of this study are quantitative in nature so I will be using the scatter plot to visualize them.&lt;/p&gt;

&lt;p&gt;Note that a histogram is not a bar chart. Histograms are used to show distributions of variables while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into bins or intervals while bar charts plot categorical data. For Dell Statistica, you can take a look &lt;a href=&quot;http://documents.software.dell.com/Statistics/Textbook/Graphical-Analytic-Techniques&quot;&gt;here&lt;/a&gt; for the graphical data visualization and in Python it can be done using matplotlib library as shown &lt;a href=&quot;https://plot.ly/matplotlib/bar-charts/&quot;&gt;here&lt;/a&gt; and a good SO question &lt;a href=&quot;http://stackoverflow.com/questions/11617719/how-to-plot-a-very-simple-bar-chart-python-matplotlib-using-input-txt-file&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;When visualizing a categorical to categorical relationship we use a Bar Chart.&lt;/li&gt;
	&lt;li&gt;When visualizing a categorical to quantitative relationship we use a Bar Chart.&lt;/li&gt;
	&lt;li&gt;When visualizing a quantitative to quantitative relationship we use a Scatter Plot.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Also, please note that it is very important to bear in mind when plotting association between two variables, the &lt;span style=&quot;text-decoration:underline;&quot;&gt;independent or the explanatory variable is ‘X’ plotted on the x-axis&lt;/span&gt; and the &lt;span style=&quot;text-decoration:underline;&quot;&gt;dependent or the response variable is ‘Y’ plotted on the y-axis&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;img class=&quot;  wp-image-1350 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/ind_dep_graph.png&quot; alt=&quot;ind_dep_graph&quot; width=&quot;268&quot; height=&quot;265&quot; /&gt;&lt;/p&gt;

&lt;p&gt;So to check if the relationship exist or not, I code it in python as follows&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# using scatter plot the visulaize quantitative variable.
# if categorical variable then use histogram
scat1= sns.regplot(x=&apos;alcconsumption&apos;, y=&apos;breastcancerper100th&apos;, data=data)
plt.xlabel(&apos;Alcohol consumption in liters&apos;)
plt.ylabel(&apos;Breast cancer per 100th person&apos;)
plt.title(&apos;Scatterplot for the Association between Alcohol Consumption and Breast Cancer 100th person&apos;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the corresponding scatter plot is &lt;img class=&quot; size-full wp-image-1251 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/sct1.png&quot; alt=&quot;sct1&quot; width=&quot;527&quot; height=&quot;365&quot; /&gt;&lt;/p&gt;
&lt;p style=&quot;text-align:center;&quot;&gt;Scatter Plot 1&lt;/p&gt;
&lt;p&gt;From the scatter plot 1, its evident that we have a positive relationship between the two variables. And this proves the alternative hypothesis (H&lt;sub&gt;1&lt;/sub&gt;) that higher alcohol consumption by women has increased chances of breast cancer in them. Thus we can safely reject the null hypothesis that alcohol consumption does not cause breast cancer in women. Also, the points on the scatter plot are densely scattered around the linear line therefore the strength of the relationship is strong. This means that we have a statistically significant and strong positive relationship between higher alcohol consumption causing increased number of breast cancer patients in women.&lt;/p&gt;

&lt;p&gt;Now, let us check if the other alternative hypothesis (H&lt;sub&gt;2&lt;/sub&gt;), “Female employee are susceptible to increased risk of breast cancer” is true or not.  To verify this claim, I code it as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;scat2= sns.regplot(x=&apos;femaleemployrate&apos;, y=&apos;breastcancerper100th&apos;, data=data)
plt.xlabel(&apos;Female Employ Rate&apos;)
plt.ylabel(&apos;Breast cancer per 100th person&apos;)
plt.title(&apos;Scatterplot for the Association between Female Employ Rate and Breast Cancer per 100th Rate&apos;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the scatter plot is  &lt;img class=&quot; size-full wp-image-1263 aligncenter&quot; src=&quot;https://edumine.files.wordpress.com/2016/01/sct2.png&quot; alt=&quot;sct2&quot; width=&quot;529&quot; height=&quot;365&quot; /&gt;&lt;/p&gt;
&lt;p style=&quot;text-align:center;&quot;&gt;Scatter Plot 2&lt;/p&gt;
&lt;p&gt;From scatter plot 2, we can see that there is a negative relationship between the two variables. That means as the number of female employment count increases the number of breast cancer patients in employed women decreases. Also the strength of this relationship is weak as the number of points are sparsely located on the linear line. So, I will say that although the relationship is statistically significant but it is weak thus its safe to conclude that female employment rate does not necessarily contribute to breast cancer in women.&lt;/p&gt;

&lt;p&gt;I now come to the conclusion of this analytical series. After performing descriptive and exploratory data analysis on the gapminder dataset using python as a programming tool, I have been successful in determining that higher alcohol consumption by women increases the chance of breast cancer in them. I have also been successful in determining that breast cancer occurrence in employed females has a weak correlation. Perhaps, there are other factors that could prove this.&lt;/p&gt;

&lt;p&gt;Finally, to conclude this exploratory data analysis series of posts has been very fruitful and immensely captivating to me. In the next post, I will discuss on the statistical relationships between the variables and testing the hypotheses in the context of Analysis of Variance (when you have one quantitative variable and one categorical variable). And since the dataset that I chose does not have any categorical variable, I will also show how to categorize a quantitative variable.&lt;/p&gt;

&lt;p&gt;The complete python code is listed on my GitHub account &lt;a href=&quot;https://github.com/duttashi/Data-Analysis-Visualization/blob/master/gapminder_data_analysis.py&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cheers!&lt;/p&gt;

</content>
</entry>


<entry>
  <title type="html"><![CDATA[Big or small-lets save them all- Making Data Management Decisions]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/big-or-small-lets-save-them-all-making-data-management-decisions/" />
  <id>https://duttashi.github.io/blog/big-or-small-lets-save-them-all-making-data-management-decisions</id>
  <published>2016-01-15T00:00:00+00:00</published>
  <updated>2016-01-15T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;So far I have discussed the data-set, the research question, introduced the variables to analyze and performed some exploratory data analysis in which I showed how to get a brief overview of the data using python. Continuing further, I have now reached a stage wherein I must ‘dive into’ the data-set and make some strategic data management decisions. This stage cannot be taken lightly because it lays the foundation of the entire project. A misjudgment here can spell doom to the entire data analysis cycle.&lt;/p&gt;

&lt;p&gt;The first step is to see, if the data is complete or not? By completeness, I mean to check the rows and the columns of the data-set for any missing values or junk values. (&lt;em&gt;Do note, here I have asked two questions. In this post I will answer the first question only. In another post i will answer the second question&lt;/em&gt;); a) How to deal with missing values and b) How to deal with junk values.&lt;/p&gt;

&lt;p&gt;To answer the first question, I use the following code to get the sum of missing values by rows thereafter I use the is.null().sum() as given to display the column count of the missing values.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Create a copy of the original dataset as sub4
sub4=data

print &quot;Missing data rows count: &amp;amp;amp;quot;,sum([True for idx,row in data.iterrows() if any(row.isnull())]) I would see that there are 48 rows of missing data as shown

Missing data rows count: 48 Now how about I want to see the columns that have missing data. For that I use the isnull().sum() function as given

print sub4.isnull().sum() This line of code will give me the column-vise missing data count as shown

country 0
breastcancerper100th 40
femaleemployrate 35
alcconsumption 26
dtype: int64
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So now, how to deal with this missing data? There are some excellent papers written that have addressed this issue. For interested reader, I refer to two such examples &lt;a href=&quot;http://www.unt.edu/rss/class/mike/6810/articles/roth.pdf&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://myweb.brooklyn.liu.edu/cortiz/PDF%20Files/Best%20practices%20for%20missing%20data%20management.pdf&quot;&gt;here&lt;/a&gt;.
&lt;span style=&quot;text-decoration:underline;&quot;&gt;&lt;strong&gt;Dealing with Missing Values&lt;/strong&gt;&lt;/span&gt;
So what do I do with a data set that has 3 continuous variables which off-course as always is dirty (&lt;em&gt;&lt;strong&gt;brief melodrama now: &lt;/strong&gt;hands high in air and I shout “Don’t you have any mercy on me! When will you give me that perfect data set. God laughs and tells his accountant pointing at ‘me’..”look at that earthly fool..while all fellows at his age ask for wine, women and fun he wants me to give him “clean data” which even I don’t have”&lt;/em&gt;). So how do I mop it clean? Do i remove the missing values? “Nah” that would be apocalyptic in data science ..hmmm..so what do I do? How about I code all the missing values as Zero. &lt;strong&gt;NO! Not to underestimate the Zero. &lt;/strong&gt;So what do I do?&lt;/p&gt;

&lt;p&gt;One solution is to impute the missing continuous variables with the mean of the neighboring values in the variable. Note: to impute the missing categorical values, one can try imputing the mode (highest occurring frequency value). Yeah..that should do the trick. So I code it as given;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;sub4.fillna(sub4[&apos;breastcancerper100th&apos;].mean(), inplace=True)
sub4.fillna(sub4[&apos;femaleemployrate&apos;].mean(), inplace=True)
sub4.fillna(sub4[&apos;alcconsumption&apos;].mean(), inplace=True)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So here, I have used the fillna() method of pandas library. You can see here the &lt;a href=&quot;http://pandas.pydata.org/pandas-docs/stable/missing_data.html&quot;&gt;documentation&lt;/a&gt; . Now I show the output before missing value imputation as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Missing data rows count: 48
country 0
breastcancerper100th 40
femaleemployrate 35
alcconsumption 26
dtype: int64 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and the output after the missing values were imputed using the fillna() function as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;country 0 breastcancerper100th 0 femaleemployrate 0 alcconsumption 0 dtype: int64
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Continuing further, I now categorize the quantitative variables based on customized splits using the cut function and why I am doing this because it will help me later to view a nice elegant frequency distribution.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# categorize quantitative variable based on customized splits using the cut function
sub4[&apos;alco&apos;]=pd.qcut(sub4.alcconsumption,6,labels=[&quot;0&quot;,&quot;1-4&quot;,&quot;5-9&quot;,&quot;10-14&quot;,&quot;15-19&quot;,&quot;20-24&quot;])
sub4[&apos;brst&apos;]=pd.qcut(sub4.breastcancerper100th,5,labels=[&quot;1-20&quot;,&quot;21-40&quot;,&quot;41-60&quot;,&quot;61-80&quot;,&quot;81-90&quot;])
sub4[&apos;emply&apos;]=pd.qcut(sub4.femaleemployrate,4,labels=[&quot;30-39&quot;,&quot;40-59&quot;,&quot;60-79&quot;,&quot;80-90&quot;])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;Now, that I that I have split the continuous variables, I will now show there frequency distributions so as to understand my data better.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;fd1=sub4[&apos;alco&apos;].value_counts(sort=False,dropna=False)
fd2=sub4[&apos;brst&apos;].value_counts(sort=False,dropna=False)
fd3=sub4[&apos;emply&apos;].value_counts(sort=False,dropna=False)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;I will now print the frequency distribution for alcohol consumption as given&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Alcohol Consumption
0 36
1-4 35
5-9 36
10-14 35
15-19 35
20-24 36
dtype: int64
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;then, the frequency distribution for breast cancer per 100th women as &lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Breast Cancer per 100th
1-20 43
21-40 43
41-60 65
61-80 19
81-90 43
dtype: int64 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;&lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&gt;and finally the female employee rate as &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Female Employee Rate
30-39 73
40-59 34
60-79 53
80-90 53
dtype: int64  &amp;lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&amp;gt;&amp;lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&amp;gt;&amp;lt;span style=&quot;font-family:Consolas, Monaco, monospace;line-height:1.7;&quot;&amp;gt;Now, this looks better. So if I have to summarize it the frequency distribution for alcohol consumption per liters among adults (age 15+). I will say that there are 36 women who drink no alcohol at all (and still they are breast cancer victims...hmmm ..nice find..will explore it further later). The count of women who drink between 5-9 liters and 20-24 liters of pure alcohol is similar! Then there are about 73% of women who have been employed in a certain year and roughly about 43 new breast cancer cases are reported per 100th female residents. &amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Stay tuned, next time I will provide a visual interpretation of these findings and more.&lt;/p&gt;

&lt;p&gt;Cheers!&lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Big or small-lets save them all-Exploratory Data Analysis]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/big-or-small-lets-save-them-all-exploratory-data-analysis/" />
  <id>https://duttashi.github.io/blog/big-or-small-lets-save-them-all-exploratory-data-analysis</id>
  <published>2016-01-09T00:00:00+00:00</published>
  <updated>2016-01-09T00:00:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;In my previous post, I had discussed at length on the research question, the dataset, the variables and the various research hypothesis.
For the sake of brevity, I will restate the research question and the variables of study.&lt;/p&gt;

&lt;p&gt;Research question: Can alcohol consumption increase the risk of breast cancer in working class women.
Variables to explore are:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;‘alcconsumption’- average alcohol consumption, adult (15+) per capita consumption in litres pure alcohol&lt;/li&gt;
	&lt;li&gt;‘breastcancerper100TH’- Number of new cases of breast cancer in 100,000 female residents during the certain year&lt;/li&gt;
	&lt;li&gt;‘femaleemployrate’- Percentage of female population, age above 15, that has been employed during the given year&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this post, I present to the readers an exploratory data analysis of the gapminder dataset.&lt;/p&gt;

&lt;p&gt;Although, for this course we are provided with the relevant dataset, however if you are not taking this course and are interested in the source of the data, then you can get it from &lt;a href=&quot;http://www.gapminder.org/data/&quot;&gt;here&lt;/a&gt;. In the List of indicators search box type “breast cancer, new cases per 100,000 women” to download the dataset.&lt;/p&gt;

&lt;p&gt;I will be using python for Exploratory Data Analysis (EDA). I begin by importing the libraries pandas and numpy as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Importing the libraries
import pandas as pd
import numpy as np
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I have already downloaded the dataset which is .csv (comma seperated value format) and will now load/read it in a variable called datausing pandas library as given&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Reading the data where low_memory=False increases the program efficiency
data = pd.read_csv(&apos;data/train.csv&apos;, low_memory=False)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To get a quick look at the number of rows and columns and the coulmn headers, you can do the following;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;print (len(data)) # shows the number of rows, here 213 rows
print (len(data.columns))# shows the number of cols, here 4 columns# Print the column headers/headings
names=data.columns.values
print names
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You will see the output as&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;213
4
213
[&apos;country&apos; &apos;breastcancerper100th&apos; &apos;femaleemployrate&apos; &apos;alcconsumption&apos;]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now, to see the frequency distribution of these four variables I use the &lt;strong&gt;value_counts() &lt;/strong&gt;function to generate the frequency counts of the breast cancer dependence variables. Note, if you want to see the data with the missing values then choose the flag &lt;strong&gt;dropna=False&lt;/strong&gt; as shown. For this dataset, majority of variable values have a frequency of 1.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;print &quot;\nAlcohol Consumption\nFrequency Distribution (in %)&quot;
c1=data[&apos;alcconsumption&apos;].value_counts(sort=False,dropna=False)
print c1
print &quot;\nBreast Cancer per 100th&quot;
c2=data[&apos;breastcancerper100th&apos;].value_counts(sort=False)
print c2
print &quot;\nFemale Employee Rate&quot;
c3=data[&apos;femaleemployrate&apos;].value_counts(sort=False)
print c3 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The output will be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Alcohol Consumption 5.25 1 9.75 1 0.50 1 9.50 1 9.60 1&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the above output, values 5.25,9.75,0.50,5.05 are the alcohol consumption in litres and the value 0.004695 is the percentage count of the value. The flag sort=False means that values will not be sorted according to their frequencies. Similarly, I show the frequency distribution for the other two variables&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Breast Cancer per 100th
23.5 2
70.5 1
31.5 1
62.5 1
19.5 6
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Female Employee Rate
45.900002 2
55.500000 1
35.500000 1
40.500000 1
45.500000 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I now subset the data to explore my research question in a bid to see if it requires any improvement or not. I want to see which countries are prone to greater risk of breast cancer among female employee where the average alcohol intake is 10L;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Creating a subset of the data
sub1=data[(data[&apos;femaleemployrate&apos;]&amp;gt;40) &amp;amp; (data[&apos;alcconsumption&apos;]&amp;gt;=20)&amp;amp; (data[&apos;breastcancerper100th&apos;]&amp;lt;50)]
# creating a copy of the subset. This copy will be used for subsequent analysis
sub2=sub1.copy()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and the result is;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;country breastcancerper100th femaleemployrate alcconsumption
9      Australia 83.2 54.599998 10.21
32     Canada 84.3 58.900002 10.20
50     Denmark 88.7 58.099998 12.02
63     Finland 84.7 53.400002 13.10
90     Ireland 74.9 51.000000 14.92
185    Switzerland 81.7 57.000000 11.41
202    United Kingdom 87.2 53.099998 13.24
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Interestingly, countries with stable economies like Australia, Canada, Denmark, Finland, Ireland, Switzerland &amp;amp; UK top the list of high breast cancer risk among working women class. These countries are liberal to women rights. Now, this can be an interesting question that will be explored later.&lt;/p&gt;

&lt;p&gt;How about countries with very low female employee rates- how much is there contribution to alcohol consumption and breast cancer risk? &lt;em&gt;(I set the threshold for high employee rate as greater than 40% and threshold for high alcohol consumption to be greater than 20 liters and breast cancer risk at less than 50%). And the winner is,&lt;/em&gt; &lt;strong&gt;Moldova &lt;/strong&gt;a landlocked country in Eastern Europe. Here we can see that Moldova contributes to approximately 50% of new breast cancer cases reported per 100,000th female residents with a per capita alcohol consumption of 23%. So with a low female employee rate of 43% (as compared to the threshold of 40%) this country does have a significant amount of new breast cancer cases reported because of high alcohol consumption by the relatively less number of adult female residents. ((on a side note: “Heaven’s! Moldavian working class women drink a lot :-) ))&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;print &quot;\nContries where Female Employee Rate is greater than 40 &amp;amp;&quot; \
  &quot; Alcohol Consumption is greater than 20L &amp;amp; new breast cancer cases reported are less than 50\n&quot;
print sub2
print &quot;\nContries where Female Employee Rate is greater than 50 &amp;amp;&quot; \
  &quot; Alcohol Consumption is greater than 10L &amp;amp; new breast cancer cases reported are greater than 70\n&quot;
sub3=data[(data[&apos;alcconsumption&apos;]&amp;gt;10)&amp;amp;(data[&apos;breastcancerper100th&apos;]&amp;gt;70)&amp;amp;(data[&apos;femaleemployrate&apos;]&amp;gt;50)]
print sub3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;the result is&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Contries where Female Employee Rate is greater than 40 &amp;amp; Alcohol Consumption is greater than 20L &amp;amp; new breast cancer cases reported are less than 50

     country   incomeperperson  alcconsumption armedforcesrate  \
126  Moldova  595.874534521728           23.01        .5415062   

     breastcancerper100th      co2emissions  femaleemployrate hivrate  \
126                  49.6  149904333.333333         43.599998      .4   

     internetuserate lifeexpectancy oilperperson polityscore  \
126  40.122234699607         69.317                        8   

    relectricperperson suicideper100th        employrate urbanrate  
126   304.940114846777        15.53849  44.2999992370606     41.76  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The complete python code is listed on my &lt;a href=&quot;https://github.com/duttashi/Data-Analysis-Visualization/blob/master/gapminder%20data%20analysis.ipynb&quot; target=&quot;_blank&quot;&gt;github account&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This series will be continued….&lt;/p&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[Batch Geo-coding in R]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/batch-geo-coding-in-r/" />
  <id>https://duttashi.github.io/blog/batch-geo-coding-in-r</id>
  <published>2015-07-05T02:34:00+00:00</published>
  <updated>2015-07-05T02:34:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;Geocoding (sometimes called forward &lt;b&gt;geocoding&lt;/b&gt;) is the process of enriching a description of a location, most typically a postal address or place name, with geographic coordinates from spatial reference data such as building polygons, land parcels, street addresses, postal codes (e.g. ZIP codes, CEDEX) and so on.&lt;/p&gt;

&lt;p&gt;Google API for Geo-coding restricts coordinates lookup to 2500 per IP address per day. So if you have more than this limit of addresses then searching for an alternative solution is cumbersome.&lt;/p&gt;

&lt;p&gt;The task at hand was to determine the coordinates of a huge number of addresses to the tune of over 10,000.&lt;/p&gt;

&lt;p&gt;The question was how to achieve this in R?&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; library(RgoogleMaps)
&amp;gt; DF &amp;lt;- with(caseLoc, data.frame(caseLoc, t(sapply(caseLoc$caseLocation, getGeoCode))))
 	#caseLoc is the address file and caseLocation is the column header
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</content>
</entry>


<entry>
  <title type="html"><![CDATA[To read multiple files from a directory and save to a data frame]]></title>
  <link rel="alternate" type="text/html" href="https://duttashi.github.io/blog/to-read-multiple-files-from-a-directory-and-save-to-a-data-frame/" />
  <id>https://duttashi.github.io/blog/to-read-multiple-files-from-a-directory-and-save-to-a-data-frame</id>
  <published>2015-06-23T16:16:00+00:00</published>
  <updated>2015-06-23T16:16:00+00:00</updated>
  <author>
    <name>Ashish Dutt</name>
    <uri>https://duttashi.github.io</uri>
    <email>ashishdutt@yahoo.com.my</email>
  </author>
  
    <category>blog</category>
  
  <content type="html">&lt;p&gt;There are various solution to this questions like these but I will attempt to answer the problems that I encountered with there working solution that either I found or created by my own.&lt;/p&gt;

&lt;p&gt;Question 1: My initial problem was how to read multiple .CSV files and store them into a single data frame.&lt;/p&gt;

&lt;p&gt;Solution: Use a lapply() function and rbind(). One of the working R code I found &lt;a href=&quot;http://stackoverflow.com/questions/23190280/issue-in-loading-multiple-csv-files-into-single-dataframe-in-r-using-rbind&quot;&gt;here&lt;/a&gt; provided by Hadley.&lt;/p&gt;

&lt;p&gt;The code is;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# The following code reads multiple csv files into a single data frame
load_data &amp;lt;- function(path) 
{ 
 		files &amp;lt;- dir(path, pattern = &apos;\\*.csv&apos;, full.names = TRUE)
 		tables &amp;lt;- lapply(files, read.csv)
 		do.call(rbind, tables)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And then use the function like&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; load_data(&quot;D://User//Temp&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</content>
</entry>

</feed>
