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 > Data Analysis on Ames Housing Sale Price Prediction

Data Analysis on Ames Housing Sale Price Prediction

Chung-Hsuan Huang, Katherine Treadwell and Laura Elliott
Posted on Sep 2, 2019
The skills I demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Introduction

Figure 1. Ames on Google map

The purpose of this project was to build an accurate model to predict sale prices for houses in the city of Ames, Iowa (Fig. 1). Using a dataset provided from a Kaggle competition, our team, SurrealEstates, conducted an in-depth exploratory data analysis (EDA), data pre-processing, and model building to accurately predict the sale price of a house based on certain variables. The data set contained about 81 features that accounted for various house characteristics, garage characteristics, and many other attributes that may influence the sale price of a home in Ames, Iowa. 

We generated a complete process of machine learning from EDA to prediction. Using various Python modules and scikit-learn, we solidified our understanding of data manipulation, model selection, and model improvement. The source code is available in our Github repository.

Motivation

Figure 2.  Formula for Root Mean Square Error (Root Mean Square Deviation).

In this specific project we sought to optimize for root mean square error (RMSE), as shown in Fig. 2. In order to select the correct inputs, we focused our research along three paths: data manipulation/EDA (exploratory data analysis), model selection/search, and refining of our models. Each of these three paths allowed us to better understand and adjust our model to reduce the RMSE.

The EDA phase allowed us to not only understand the composition of the data, but also to understand how the data related to each other.  We looked at missing data and imputed it depending on both the type of missingness and the type of data. We worked through different methodologies, as well, when refining our model. Those iterations allowed us to see how the different types of imputation changed the RMSE. 

The RMSE was also significantly impacted by our model selection and model search. We used a combination of grid search and ensembling to refine, test, and validate our results. We worked through multiple hyperparameters with each of our models. When the best model was chosen, we used ensembling to weight those models and determine the best overall score for the prediction.  Multiple pass throughs and changes in our tuning methodologies allowed us to continue to decrease our RMSE.

Preprocessing

Data exploration

We began the process of machine learning by exploring the linear relationships between sale price and the continuous input variables in the dataset. We produced a correlation matrix (see Fig. 3) to give a visual snapshot of the magnitude of these relationships.

Figure 3. Top ten correlation features with sale price

We observed strong linear relationships between our outcome, sale price, and overall quality, great living area, number of cars a garage can manage, the area of the garage, total basement square feet, first floor square feet, number of full baths, number of rooms above ground, and year built. The relationships were further analyzed with scatter plots to further observe the observations in each variable and look at possible outliers that may be biasing correlation values. 

Remove outliers

Figure 4. Example of outliers removing

Many outliers were observed within the continuous variables. Instead of removing just based on the scatterplot visualizations, outliers were systematically removed by using z-scores. The z-score method identifies outliers by finding the relationship with the standard deviation and mean of a given group of data points and scales them to follow a normal distribution where the standard deviation = 1 and mean = 0. Outliers are considered to be the observations furthest from the mean. In practice, the threshold for removal of outliers is if a data point is greater than 3 standard deviations away from the mean or less than -3 standard deviation of the mean. 

For example, two outliers were removed from the great living area feature, shown in Figure 4.

Missing data

Once the exploration was complete, the train and test data from Kaggle were merged into a larger set for further engineering. The variable โ€˜Salepriceโ€™ was saved as its own separate data frame and removed from the larger dataset. 

The merged dataset showed an abundance of missing values, as shown in Figure 5. 

Figure 5. The number of missing data of the categories, and the type of the features.

Many variables had more than 50% of their values missing. These values were imputed based on the nature of the variable. Some variables, such as PoolQC, MiscFeature, Alley, Fence, and FireplaceQu that contained a large NaN count, had meaning in the  NAN values. For these variables, the NaNs indicated the lack of the feature at a particular house for sale. These NaN values were important to the analysis and were imputed with 'None.' Other imputation methods included: imputing with zeros (float type variables), the median (float type variables), and the mode (categorical variables).

Reduce skewness, Outcome

After imputation was complete, we set off to normalize all of the continuous variables to be included in the machine learning model to reduce any possible bias in the analysis.

Figure 6. (Left) The density plot of the sale price. (Right) The probability plot of the sale price.

Skewness is asymmetry in the distribution of numerical distribution in which the curve appears distorted either to the left or to the right. Skewness can be quantified to define the extent to which a distribution differs from a normal distribution. Sale price was the first to be normalized. A density plot of sale price showed that the outcome was skewed to the right and had some deviations from the line on the probability plot, as shown in Figure 6. The extremely skewed data would introduce bias in the results of our model.  So we decided to use the logarithm of sale price to train our mode in order to reduce bias. In Fig. 7, the curve after taking logarithm is much closer to a normal distribution and shows little deviation from the line in the probability plot.

Figure 7. (Left) The density plot of the sale price after taking logarithm. (Right) The probability plot of the sale price after taking logarithm.

Reduce skewness, Inputs

Many of the continuous features were skewed in the data set. Instead of taking the logarithm of all of these features, the box cox method of normalization made all  the difference in the success of our model.

Figure 8. Equations of box-cox method
Figure 9. (Left) The density plot of the garage area before using box-cox. (Right) The density plot of the garage area after using box-cox

In order to normalize all numerical features, we applied box-cox method built in Python on the features with skewness greater than 0.75. The equation of box-cox is shown in Fig. 8. The ideal lambda value of each numerical feature was obtained by using the built in function in Python. Fig. 9 shows the distribution of garage area before and after box-cox transform.

Add additional features

At the end of our data pre-processing, the categorical features were dummified in order to pass them through the machine learning model, and a couple of new features were introduced into the data. Two variables, โ€˜TotalSFโ€™ and  โ€˜Total_Bathโ€™, were engineered by aggregating all of the features that quantify the square feet of a home and features containing the number of bathrooms in a house. Furthermore, โ€˜hasbasementโ€™ and โ€˜has2ndfloorโ€™ were engineered by turning the โ€˜2ndFlrSFโ€™ feature and โ€˜BsmntSFโ€™ feature into binary variables. All features used to make the new variables were dropped from the larger data set to reduce the dimensionality of the data.

Model fitting

Procedure

Figure 10. Model fitting workflow

Fig. 10 shows the workflow of model fitting. After finishing the preliminary data preprocessing, we first fitted the basic linear models (Ridge, Lasso, ElasticNet). We used the grid search cross-validation method to find the best model and parameters with full data. Because tuning hyperparameters of basic models were fast compared to high-end models, it allowed us to refine the preprocessing part with less time.  We then split the data into training and testing data set and compared the root mean square error between them. This procedure helped us have a better idea of how models performed when they faced unknown data.  

We tried different combinations of processes in the preprocessing part and fitted models to examine which combination gave us the smallest test RMSE and Kaggle score. We found that reducing the skewness of the numerical feature played a critical role in getting a smaller RMSE. This results showed that normalized numerical features would improve the performance of the linear models.

Figure 11. Schematic of the averaged model.

After refining the preprocessing procedure with basic linear models, we used the grid search method to tune the hyperparameters of the gradient boost model (GBM), XGboost (XGB), and support vector regressor (SVR). In the end, we used averaged models by putting different weight on the predictions to improve the housing sale price predictions further, as shown in Fig. 11.

Results

Figure 12. The table R^2, training and test root mean square error (RMSE), the difference between RMSE, and Kaggle score of each model.

Fig. 12 displays the results of each model. The GBM and XGB had higher R^2 values (score_grid), and lower train RMSE compared to other models. However, they had the highest test RMSE among all models. These results clearly showed that these two models overfitted the data. As a result, they had higher Kaggle RMSE score compared to other models. 

As can be seen in Fig. 12, the simple linear models performed better than those "high-end" models based on the Kaggle score. There are fewer hyperparameters of simple linear models, so it is easier to find their best model.  We might need to tune hyperparameters of those more complex models better since there are more hyperparameters for the GBM or XGB. However, this requires more study on the influence on different hyperparameters, which can be done in the future.

As mentioned in the previous session, we used the averaged model to improve the model predictions further. The best combination of weight of each model is 0.25*Ridge + 0.2*Lasso + 0.2*ElNet + 0.15*XGB + 0.2 *GBM, which gave us the best Kaggle score 0.11653. This score put us at the top 16% among all teams in this Kaggle competition.

Feature importance

Figure 13. (Left) The top ten important features from gradient boost model (GBM). (Right) The top ten important features from XGBoost model (XGB).

Figure 13 demonstrates the top ten crucial features from the GBM and XGB models. The feature importance can help us understand which variables have more influence (either positive or negative) on the housing sale price. 

GBM showed that the living space, the quality of the house, year built, garage area, and the numbers of bathrooms were essential features. This result was consistent with the top ten correlated variables with the sale price. However, there are some discrepancies with the top ten critical features between XGB and GBM. XGB shows that the size of the garage is the most vital feature, which is unexpected. This result might indicate that more hyperparameter tuning is required for the XGB to obtain a more accurate prediction.

Summary

We continued to refine our models until we reached a peak score of 0.11653, which placed us at top 16% in this competition. This score was due to the choice not only of the individual models and hyperparameters, but also on the chosen weights for ensembling our models. We determined a few key factors which reduced our RMSE. 

The most important areas we determined for reducing the model consisted of: method of imputation, removal of outliers, data normalization, feature engineering (adding/removing), and hyperparameter tuning. While we did ensemble our different models, our best stand alone model was ridge.

Future work

There are many ways in which we would choose to further explore this data and change our models in order to continue to reduce our RMSE. We could continue to tune our models, add more models, or even change our methodologies on imputation and normalization. Another option would be to do additional feature engineering. 

The additional model tuning could be approached in a few different ways. We would like to add additional models outside of the ones we have already tested. Since we did not find the best hyperparameters for XGB and GBM, we would continue to iterate with our grid search to find higher performing values. Adding additional values from outside sources such as the Census Bureau, US Fed, and other economic indicators would also allow us to predict the purchase cost of homes.

About Authors

Chung-Hsuan Huang

Chung-Hsuan is an NYC Data Science Academy Fellow with a PhD in Chemical Engineering from University of Minnesota Twin Cities. His study includes developing & validating the computational models to improve the liquid transfer in the process of...
View all posts by Chung-Hsuan Huang >

Katherine Treadwell

Analytics professional passionate about empowering teams to make well-informed, data-driven decisions. Proven leader and strategic partner in developing long-term plans for success. Strong foundation in technology and business applications. Teacher, developer, and mentor of team members and the...
View all posts by Katherine Treadwell >

Laura Elliott

Laura Elliott is an experienced data analyst and epidemiologist who specialized in the distribution of mental health disorders, specifically adolescent anxiety. Now pursuing data science, Ms. Elliott intends to improve business practices through her extensive knowledge of mental...
View all posts by Laura Elliott >

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