NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Machine Learning > Kaggle Competition: Building Algorithm to Predict Allstate Claim Severity

Kaggle Competition: Building Algorithm to Predict Allstate Claim Severity

Xinyuan Wu, Alex Yuan Li and Boyang Dai
Posted on Dec 5, 2016

1. Introduction

When a claim is made, a loss is incurred for an insurance company when the coverage is greater than the accumulated payment from the customer. Thus for these companies, it is valuable to "know" of the potential loss in advance. Allstate is currently developing automated methods of predicting the severity of car accident claims. As a result, an open competition is hosted on Kaggle.com. In this project, we are aiming to leverage our machine learning skill and build a prediction algorithm to link 130 variables to the outcome "loss", with the goal of minimizing the mean absolute error (MAE). All python and R scripts used for this project can be found here.

2. Exploratory Data Analysis

The number of observation in the training set is 188318. It has 116 categorical and 14 numerical variables, and all variables are not interpretable. Due to the high amount of features, it is necessary to perform exploratory data analysis to gain some insights of these variables.

cat_eda

Figure 1. Ten categorical features with the greatest number of levels

As shown above, some categorical variable has more than 100 levels, like cat110 and cat116. These features will cause trouble for building tree-based model. Thus encoding them to numeric variables are especially needed.

nun_eda

Figure 2. Correlation plot for all continuous variables

For 14 continuous variables, they all have values ranging from 0 to 1, meaning that some kinds of transformation is applied to each of them. Some variables are highly correlated, which will increase the coefficient variance for regression models. The outcome "loss" shows strong skewness, therefore a log transformation is applied to this column throughout the work.

3. Data Processing

Given 116 categorical variables in the dataset and some of them have more than 100 levels, huge amount computation power is needed for training the model. To make the computation doable on our PC, it is necessary to encode these categorical features to numeric columns. In this project, we decided to apply three different encoding techniques to the original data. As you will see in the later section, we apply each machine learning algorithm on every encoded version and pick out the relatively strong predictors for the future model stacking.

3.1 Encoding I

encode_v1

Figure 3. Work flow of encoding version 1

As shown in the figure above, the idea of encoding 1 is to expand the multinomial features into binomial variables, after this transformation we filter out the variables with near-zero-variance and performed one-hot encoding to the remaining columns. After encoding 1 the final data contains 193 variables in total.

3.2 Encoding II

encode_v2

Figure 4. Workflow of encoding version 2

Instead of converting to binomial, the idea of encoding 2 is to directly perform one-hot encoding on all categorical variables. However, it should be noted that before transforming to numeric, it is important to identify all unmatched values between training and testing set, and set these values to the last level in this column. After encoding 2 we have 130 variables.

3.3 Encoding III

encode_v3

Figure 5. Workflow of encoding version 3

Encoding 3 is adapted from Kaggle kernel by modkzs. This method applies feature engineering to generate new variables and then perform encoding 2 to convert everything to numeric. 35 relatively important features were selected from XGBoost and Linear Regression, and the combination of any two features were generated as new columns. After pre-processing 595 new variables are created.

4. Exploratory Algorithm Selection

Since there are so many different supervised machine learning models to choose from, it is crucial to select the optimal models suited for this competition. This can be done by establishing a benchmark of viable models based on their MAE (mean absolute error). From this benchmark, we can choose the models with lowest MAEs for later process, such as experimenting different encoding method and model stacking. Ultimately, we select five distinct models to construct the baseline:

  • LASSO Regression
  • Ridge Regression
  • Decision Tree
  • Random Forest
  • eXtreme Gradient Boost (XGBoost)

For this exploration, the categorical features were converted to โ€œnumericalโ€ features via the method of one-hot encoding without any feature selection method to explore the dataset in its entirety, to ensure the viability of the generalized linear models, and to reduce computational handicap for the tree-based models.

Out of the five selected models, LASSO and Ridge regression was selected to serve as a generalization of linear regression model. Decision tree was selected because it is a suitable model for this dataset. Random Forest and XGBoost were selected because of their high accuracy and ensemble nature.

We also omitted models that we believe are not fit for this dataset, including k-Nearest Neighbor (k-NN) and Support Vector Regressor (SVR). The reason for the exclusion is that we did not feel distance-based models are viable for this dataset due to large amount of categorical features.

The minimum validation MAE is obtained through model parameter tuning. We decided to tune one critical parameter per model via 90%-10% train-test split validation. The MAE of each validation is then plotted against the tuning parameter; the models with the lowest MAEs will be ideal from the bias-variance trade-off. Since this is an exploratory analysis, a coarse estimation of MAE will be enough in distinguish models. No finer parameter tuning was necessary.

4.1 LASSO Regression

lasso

Figure 6. Exploratory Lasso regression

The LASSO regression was validated using the lambda parameter with ten values ranging from 100 to 0.001. The minimum MAE is 1304 with a corresponding lambda of 0.1668. This lambda represents the best lambda from the bias-variance tradeoff, a higher lambda will result in an increase in bias (underfit) while a lower lambda resulting in an increase in variance (overfit).

4.2 Ridge Regression

ridge

Figure 7. Exploratory Ridge regression

The Ridge regression was validated using the lambda parameter with fifteen values ranging from 10,000 to 0.001. The minimum MAE is 1306 with a corresponding lambda of 1000. Similar to LASSO regression, a higher lambda will result in an increase in bias while a lower lambda resulting in an increase in variance. Also the range of lambda was increase to [10000, 0.001] because of a local minimum occurring at lambda equals to 1. Since LASSO and Ridge regression are related (l1 and l2 norm), their MAEs are very close.

4.3 Decision Tree

dtree

Figure 8. Exploratory Decision tree

The decision tree model was validated using the tree depth parameter ranging from 1 to 20. The minimum MAE is 1364 with a tree depth of 11. The bias-variance off is also observed here. Since the decision tree tends to overfit easily, it is no surprise that the MAE is higher.

4.4 Random Forest

rf

Figure 9. Exploratory Random Forest

The random forest model was validated using the number of trees parameter ranging from 10 to 500. The minimum MAE approaching 1240 at max number of trees of 500. Due to the nature of random forest model being an ensemble model and its unique property of inducing randomness in observation and feature, it is practically impossible to overfit. Thus, it is nearly impossible to find a global minimum of MAE, but the MAE will eventually approach an asymptote and reach a limit.

4.5 eXtreme Gradient Boost (XGBoost)

xgb

Figure 10. Exploratory XGboost

The XGBoost model was validated using the number of boosted models parameter ranging from 10 to 1500. The minimum MAE approaching 1200 at max number of trees of 1500. Similar to random forest, XGBoost is also an ensemble model, therefore it is more robust to overfitting compared to non-ensemble models. Also, ensemble models generally perform better than non-ensemble models, which is true in this analysis, random forest and XGBoost both yield a MAE in the 1200, whereas all the non-ensemble models scored 1300 and more.

4.6 Neural Network

The neural network with three hidden layer was chosen to build the model since it significantly out-performs the one and two-layer derivatives. Cross-validation was applied during the training process. The workflow can be summarized as the following steps:

  • Create dummy variables
  • Generate sparse matrix
  • Normalize continuous variables
  • Set parameters for neural network
  • Stack using 10-fold cross-validation and bagging
  • Use MAE to evaluate the performance
nn

Figure 11. Structure of neural network model

Our final neural network model was obtained after several rounds of parameter tuning. By changing the number of nodes in each layer, number of hidden layer, and regularization method, our final model has the structure shown above. The neural network is relatively computational expensive to build. However, it shows relatively better performance than most of other algorithms we tested.

4.7 Model Summary

Model MAE
LASSO 1304.6
Ridge 1306.0
CART 1363.9
Random Forest ~1240
XGBoost ~1200
Neural Network ~1200

The main objective of the exploratory model selection is to select the models with most potential for this dataset. From the summary table, we can conclude that XGBoost and Neural Network models produced the lowest MAEs, thus we selected these two models for further analysis and model stacking.

5. Model Stacking

With the strategy in mind, we started to validate each model on all three encoded dataset. At this moment, our top-3 strongest single predictors are XGBoost on encoding 2, 3, and Neural Network on original dataset. To further boost the performance, model stacking is necessary.

stacking_1

Figure 12. Stacking workflow

Above is the workflow of the model stacking. First, we randomly split the training set to two subsets. For each algorithm, two parallel models are built using different subsets. The parameters used in each training process were tuned via cross-validation. After training process, each model is used to predict the complementary data to avoid bias. Finally two predictions are bind together and used as a variable ready for building the stacking model.

Once we collect multiple predictions, a second-layer model is built using all predictions as variables. Three candidates for stacking model were examined - General Additive, Gradient Boosting and XGBoost. Among all three algorithms, Gradient Boosting generally performs better in every combination of predictors, therefore is selected as our stacking algorithm.

Figure 13. Current result (measured in MAE)

As shown above, the performance for three individual predictors shows MAE of 1114 and 1108 for two XGBoost models, and 1128 for neural network. The improvement is significant, as we were able to drop the MAE as low as 1103.82 after model stacking.

6. Milestone and Future Plan

By the time we submit the project, we were able to reach 6% on the global leaderboard. After exposure to this competition for two weeks, our findings are:

  • Feature engineering is very necessary before model building.
  • XGBoost and Neural Network are two algorithms that performs the best on this dataset.
  • Stronger the individual predictor, better the stacking results.

Currently we keep working on more in depth feature engineering along with building more neural network models for each of the encoding method. After seeing the performance boost on the encoded dataset for every algorithm, we hope to see a increasing performance for neural network as well. By combining more strong predictors in our stacking model, hopefully we can climb higher on the leaderboard.

About Authors

Xinyuan Wu

Xinyuan recently obtained his Ph.D. from North Carolina State University. He gained quantitative analysis, statistical knowledge and critical thinking from years of research on magnetic and photophysical chemistry. His belief in the trend of predictive analysis, along with...
View all posts by Xinyuan Wu >

Alex Yuan Li

Alex Li received his Master of Science in Mechanical Engineering at Columbia University and Bachelor of Science in Chemical Engineering at University of Utah with professional experience in Research and Development in the Medical Device industry. He discovered...
View all posts by Alex Yuan Li >

Boyang Dai

Eat and pray, love the data.
View all posts by Boyang Dai >

Related Articles

Data Analysis
Injury Analysis of Soccer Players with Python
Machine Learning
Ames House Prices Predictions
Python
US Honey Production Analysis With Python (1998-2012)
Machine Learning
The Ames Data Set: Sales Price Tackled With Diverse Models
Python
EDA and machine learning Ames housing price prediction project

Leave a Comment

Cancel reply

You must be logged in to post a comment.

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application