Journey of Analytics

Deep dive into data analysis tools, theory and projects

Tag: machine learning and predictive analytics data

Machine Learning Model for Predictive Analytics in 6 easy steps

In this post, we are going to learn how to apply a machine learning model for predictive analytics. We will create 5 models using different algorithms and test the results to compare which model gives the most accurate results. You can use this approach to compete on Kaggle or make predictions using your own datasets.

Dataset – For this experiment, we will use the birth_weight dataset from Delaware State Open Data Portal, which includes data from infants born in the period 2009-2016, including place of delivery (hospital/ birthing center/ home), gestation period (premature/ normal) and details about mother’s health conditions. You can download the data directly from the Open Data Link ( or use the file provided with the code.

Step 1 – Prepare the Workspace.

  1. We clean up the memory of current R session, load some standard library packages (data.table, ggplot, sqldf, etc).
  2. We load the dataset “Births.csv”.



Step 2 – Data Exploration.

  1. This step helps us understand the dataset – the range of values for variables, most common occurrences, etc. For our dataset, we look at a summary of birth years, birth weight and number of unique values.

2.  This is the point where we process for missing values and make a decision whether to ignore (entire column with large number of missing data), delete (very few records) or possibly replace it with median values. In this set however, there are no missing values that need to be processed.

3. Check how many unique values exist for each column.



Step 3 – Test and Training Set

If you’ve ever competed on Kaggle, you will realize that the “training” set is the datafile used to create the machine learning model and the “test” set is the one where we use our model to predict the target variables.

In our case, we only have 1 file, so we will manually divide our set into 3 sets – one training set and one 2 test sets. (70% ,15%, 15% split) Why 2 test sets? Because it helps us better understand how the model reacts to new data. You can work with just one if you like. Just use one sequence command and stop with testdf command.


Step 4 – Hypothesis Testing

statistical functions

statistical functions

In this step , we try to understand which predictors most affect our target variable using statistical functions such as ANOVA, chisquare, correlation, etc. The exact function you use can be determined using the table alongside.

Irrespective of which function we use, we assume the following hypothesis:
a) Ho (null hypothesis) – no relation exists. Ho is accepted if p-values if >= 0.05
b) Ha (alternate hypothesis) – relation exists. Ha is accepted if p-value < 0.05. If Ha is found true, then we conduct posthoc tests (for Anova and chisquare tests ONLY) to understand which sub-categories show significant differences in the relationship.


(1) Relation between birth_weight and mom’s_ethnicity exists since p-value < 0.05.

Using BONFERRONI adjustment and posthoc tests, we realize that mothers with “unknown” race are more likely to have babies with low birth weight, as compared to women of other races.

We also see this from the frequency table (below). Clearly only 70% of babies born to mothers of “unknown” race are of normal weight (2500 gms or above) compared to 92% babies from “other” race moms and 93% babies of White-race origins.

mom ethnicity

mom ethnicity

(2) Relation between birth_weight and when prenatal_care started (first trimester, second, third or none) Although we see p-value < 0.05 Ha cannot be accepted because the posthoc tests do NOT show significant differences among prenatal care subsets.


(3) Relation between birth_weight and gestation period:

Posthoc tests show that babies in the groups POSTTERM 42+ WKS and TERM 37-41 WKS are similar and have higher birth weights than premature babies.
(4) We perform similar tests between birth_weight and multiple-babies (single, twins or triplets) and gender.



Step 5 – Model Creation

We create 5 models:

  • LDA (linear discriminant analysis) model with just 3 variables:
  • LDA model with just 7 variables:
  • Decision tree model:
  • Model using Naïve Bayes theorem.
  • Model using Neural Network theorem.


(1) Simple LDA model:

Model formula:

Make predictions with test1 file.

Examine how well the model performed.

lda_model prediction-accuracy


From alongside table, we see that number of correct predictions (highlighted in green)

= (32+166+4150) / 5000

= 4348 / 50

= 0.8696

Thus, 86.96% predictions were correctly identified for test1! (Note, we will use the same process for checking all 5 models.)

Using a similar process, we get 88.4% correct predictions for test2.


(2) LDA model with just 7 variables:


Make predictions for test1 and test2 files:

We get 87.6% correct predictions for test1 file and 88.57% correct for test2.


(3) Decision Tree Model

For the tree model, we first modify the birth weight variable to be treated as a “factor” rather than a string variable.

Model Formula:

Make predictions for test1 and test2 files:

We get 91.16% correct predictions for test1 file and 91.6% correct for test2. However, the sensitivity of this model is little low, since it has predicted that all babies will be of normal weight i.e “2500+” category. This is one of the disadvantages of tree models. If the target variable has a highly popular option which accounts for 80% or more records, then the model basically assigns everyone to it. (sort of brute force algorithm)


(4) Naive Bayes Theorem :

Model Formula:

Make predictions for test1 and test2 files:

Again we get model accuracy of 91.16% 91.6% respectively for test1 and test2 files. However, this model also suffers from a “brute-force” approach and has marked all babies with normal weight i.e “2500+” category. This reminds us that we must be careful about both accuracy and sensitivity of the model when applying an algorithm for forecasting purposes.


(5) Neural Net Algorithm Model :

Model Formula:

In the above formula, the “maxit” operation specifies a stop after maximum number of iterations, so that the program doesn’t go into an infinite loop trying to converge values. Since we have set the seed to 270, our formula converges after 330 iterations. With other “seed value” this number may be higher or lower.

Make predictions for test1 file:

Validation table (below) shows that total number of correct observations = 4592. Hence model forecast accuracy = 91.84%



Test with second file:

Thus, Neural Net models are accurate at 91.84% and 92.57% respectively for test1 and test2 respectively.



Step 6 – Comparison of models

We take a quick look at how our models fared using a tabular comparison:  We conclude that neural network algorithm gives us the best accuracy and sensitivity.

compare data models

compare data models


The code and datafiles for this tutorial are added to the New Projects page under “Jan” section. If you found this useful, please do share with your friends and colleagues. Feel free to share your thoughts and feedback in the comments section.


US Presidential Elections – Roundup of Final Forecasts

With barely 48 hours remaining for the US Presidential Elections, I thought a roundup post curating the “forecasts” seemed inevitable.

So here are the analysis from 3 Top Forecasters, known for their accurate predictions:

US Presidential Elections 2016

US Presidential Elections 2016


(1) Nate Silver, FiveThirtyEight:

This website has been giving a running status of the elections and has been accounting for the numerous pendulum swing (and shocking) changes that have characterized this election. Currently, it shows Hillary Clinton to be the clear winner with a ~70% chance of being the next President. You can check out the state-wise stats and electoral vote breakdown in their webpage here.  If you are interested you can also view their forecasts using 3 different models: polls only, polls+forecast and now-cast (current sentiment) and how they have changed over the last 12  months.

Their analytics are pretty amazing, so do take a look as a learning exercise, even if you do not agree with the forecast itself!


(2) 270towin:

Predictions and forecasts from Larry Sabato and the team at the University of Virginia Center for Politics. The final forecast from this team also puts Ms. Clinton as the clear winner.  They also expect Democrats to take control over the Senate. You can view their statewise electoral vote predictions here.


(3) Dr. Lichtman’s 13-key system:

Unlike other statistical teams and political analysts, this distinguished professor of history at American University, rose to fame using a simplified 13-key system for predicting the Presidential Elections. According to Dr. Allan J. Lichtman’s theory, if six or more questions are answered true, then the party holding the White House will be toppled from power. His system has been proven right for the past 30 years, so please do take a look at it before you scoff that it does not contain the mathematical proof and complex computations touted by media houses and political analytics teams. Dr. Allan J. Lichtman predicts  Trump to be the winner,  as he shows six of the questions are currently TRUE. Read more about this system and the analysis here.



Finally, looking at the overall sentiment on Twitter and news media, it does look like Hillary’s win is imminent.

But until the final vote is cast, who knows what may change?

50 free Datasets for Data Science Projects

50 free datasets for Data Science projects

50+ free datasets

50+ free datasets

Here are top 50 websites to gather datasets to use for your data science projects in R, Python, SAS, Excel or other programming language or statistical software. Best part, these are all free, free, free!

The datasets are divided into 5 broad categories as below:

  1. Government & UN/ Global Organizations
  2. Academic Websites
  3. Kaggle & Data Science Websites
  4. Curated Lists
  5. Miscellaneous


Government and UN/World Bank websites:


Academic websites:

  • Yelp academic data – link
  • Univ of California, Irvine – link
  • Harvard Univ: link
  • Harvard Dataverse database: link 
  • MIT – link1 and  link2
  • Univ of North Carolina, adolescent health – link
  • Mars Crater Study, a global database that includes over 300,000 Mars craters 1 km or larger. Link to Descriptive guide and dataset.
  • Click Dataset from Indiana University (~2.5TB dataset) – link .
  • Pew Research Data – Pew Research is an organization focused on research on topics of public interest. Their studies gauge trends in multiple areas such as  internet, technology trends, global attitudes, religion  and social/ demographic trends. Astonishingly, they not only publish these reports but also make all their datasets publicly available for download!
  • Million Song Dataset from Columbia University , including data related to the song tracks and their artist/ composers.


Kaggle & Datascience resources:

Few of my favourite datasets from Kaggle Website are listed here. Please note that Kaggle recently announced an Open Data platform, so you may see many new datasets there in the coming months.

  • Walmart recruting at stores – link
  • Airbnb new user booking predictions – link
  • US dept of education scorecard – link
  • Titanic Survival Analysis – link
  • – link
  • Edx – link
  • Airbnb – link
  • Datasets on Climate information, human genome data, Enron email information, etc – link
  • Gapminder – link


Curated Lists:

  • KDnuggets provides a great list of datasets from almost every field imaginable – space, music, books, etc. May repeat some datasets from the list above. link
  • An eclectic mix of datasets about gun ownership, NYPD crime rates, college student study habits and caffeine concentrations in popular beverages – link
  • Data Science Central has also curated many datasets for free – link
  • List of open datasets from DataFloq – link
  • Sammy Chen (@transwarpio ) curated list of datasets. This list is categorized by topic, so definitely take a look.



  • MRI brain scan images and data – link
  • Economic, education, Health and other datasets from Quandl. Please note this site also has a premium version of other datasets .
  • Google repository of digitized books and ngram viewer – link.  Sample chart shown below:

  • Database with geographical information – link
  • Loan information from Lending Club – link
  • Google Public Data – Google has a search engine specifically for searching publicly available data. This is a good place to start as you can search a large amount of datasets in one place.
  • Statista – This site aggregates thousands of data sets and offers access as a paid service. However, some of the data sets are available for free.
  • Internet Usage Data from the Center for Applied Internet Data Analysis –link .
  • Yahoo offers some interesting datasets, the caveat being that you need to be affiliated with an accredited educational organization. (student or professor) – you can view the datasets here.
  • Enron Emails aggregated as a dataset.
  • Public datasets from Amazon – see link.

This post builds on an earlier post published on our old blog site. You can view the post here listing 25 sites.