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 > Using Data Algorithms to Predict Housing Prices

Using Data Algorithms to Predict Housing Prices

Yulia Norenko, Howard Chang, Lavanya Gupta and Silvia Lu
Posted on Aug 28, 2018
The skills the author demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Using Data Algorithms to Predict Housing Prices

Intuitively, which of the four houses in the picture do you think is the most expensive?

Most people will say the blue one on the right, because it is the biggest and the newest. However, you might have a different answer after reading this blog post and discover a more precise approach to predicting prices. In this blog post, we discuss how we use machine learning techniques and data to predict house prices.  

The dataset can be found on Kaggle. The dataset is divided into the training and test datasets. In total, there are about 2,600 rows and 79 columns which contain descriptive information on different houses (e.g. number of bedrooms, square feet of the first floor, etc.). The training dataset contains the actual house prices while the test dataset doesnโ€™t.

Dependent Variable

Exhibit 1: Distribution of House Prices 

Using Data Algorithms to Predict Housing Prices

The house prices are right-skewed with a mean and a median around $200,000. Most houses are in the range of 100k to 250k; the high end is around 550k to 750k with a sparse distribution.

Exhibit 2: Descriptive Statistics

Using Data Algorithms to Predict Housing Prices

Data on Independent Variables

Categorical Variables

Exhibit 3: Overall Quality vs. House Sale Price 

Most of the variables in the dataset (51 out of 79) are categorical.  They include things like the neighborhood of the house, the overall quality, the house style, etc. The most predictive variables for the sale price are the quality variables. For example, the overall quality turns out to be the strongest predictor for the sale price. Quality on particular aspect of the house, like the pool quality, the garage quality, and the basement quality, also show high correlation with the sale price.

Numeric Variables

Exhibit 4: Above Grade (Ground) Living Area Square Feet vs. House Sale Price 

Exhibit 5: Total  Feet vs. House Sale Price 

The numeric variables in the dataset are mostly the area of the house, including the first-floor area, pool area, number of bedrooms, garage area, etc. Most of the variables show a correlation with the sale price.

Missingness and Imputation

Exhibit 6: Missing Values in Train and Test Datasets 

One challenge of this dataset is the missing data. For missing data, such as pool quality and pool area - where a missing value means there is no pool in this house - we replace the missing value with 0 for numeric variables and โ€œNoneโ€ for categorical variables. However, for missing data that are missing at random, we use other variables to impute the value.

Exhibit 7: Missing Values and Imputation 

Feature Engineering

Dealing with a large number of dirty features is always a challenge. This section focuses on the feature engineering (creating and dropping variables) and feature transformation (dummifying variables, removing skewness etc.) tasks.

Drop

Usually it makes sense to delete features that are highly correlated. In our analysis, we found out that GarageYrBlt (year the garage was built) and YrBlt (year the house was built) had a very strong positive correlation of 0.83. In fact, more than 75.8% of these values were exactly the same. Hence, we decided to drop GarageYrBlt since it had many missing values which could be compensated by YrBlt.

Creation 

It sometimes makes sense to engineer new features that can help increase the modelโ€™s performance. We created the following two new features:

  1. AgeWhenSold  = YrSold - YearBuilt
  2. YearsSinceRemod  = YrSold - YearRemodAdd

Feature Transformation

  1. We identified 11 ordinal categorical variables where we interpreted that there was some kind of inherent ordering from โ€˜Excellentโ€™ to โ€˜Moderateโ€™ to โ€˜Worstโ€™.
  2. For the other categorical variables, we used the pandas.get_dummies to get One-Hot Encoding.
  3. We identified 24 continuous numeric values which has a skew > 0.75 (right-skewed). We used log transformation to get rid of the skewness.

Exhibit 8: Feature Transformation  

Regularization

Because we have to work with so many variables, we introduced the use of regularization techniques to address the issue of multicollinearity found in our correlation matrix and the possibility of overfitting using the multiple linear regression model. We address that in the exploratory data analysis section. 

The great thing about regularization is that it reduces the model complexity, as it automatically does the feature selection for you. All the regularization models penalize for extra features.

Regularization models include (Lasso, Ridge and Elastic Net). The lasso model will set coefficients to zero, while the ridge model will minimize the coefficients, making some of them very close to zero. Elastic net is a hybrid of both the lasso and ridge model. It groups correlated variables together, and if one of the variables in the group is a strong predictor, then it will include the entire group into the model.

The next step is to tune the hyperparameters of each model through the use of cross-validation.

We choose alpha = .0005 for the Lasso model and alpha = 2.8 for the Ridge model. We choose alpha = .0005 and L1_Ratio = 0.9 for Elastic Net. Because Elastic Net, with a L1_Ratio of 0.9 is very similar to the Lasso model which has a default L1_Ratio of 1, we do not depict it here.

Exhibit 9: Hyperparameters in Lasso and Ridge Regressions

Data on Feature Selection

Exhibit 10: Coefficients in Lasso and Ridge Regressions 

Lasso Model

Positive coefficients for Sale Price: Above Grade Living Area, Overall Condition and the Neighborhoods (Stone Bridge, North Ridge and Crawford).

Negative coefficients for Sale Price: MS Zoning, Neighborhood Edwards and Above Ground Kitchen.

Ridge Model

Positive coefficients for Sale Price: General Living Area, Roofing Material (Wood Shingle), Overall Condition.

Negative coefficients for Sale Price: The General Zoning requirements, Proximity to Main Road or Railroad and the Pool Quality being in Good condition.

Comparison of our predicted price vs. the actual price on the training data

The two graphs below show how accurate our model prediction is for the sales price vs the actual price. Dots closer to or on the red line show how accurate the model prediction was. There are some outliers that we should investigate as future work on the model. 

Exhibit 11: Model Predictions vs. Actual Price  

Gradient Boosting Regressor 

Gradient Boosting Regressor was one of our best performing algorithms. We first trained gradient boosting machine using the entire set of features (baseline model). We performed cross-validation with parameter tuning using GridSearchCV function from scikit-learn package for Python. Our best model parameters were: learning rate of 0.05, 2,000 estimators and max depth of 3.  

We created a relative importance chart to visualize feature importance in gradient boosting. Feature importance scores indicate how useful each feature is in the construction of the boosted decision tree. Above Grade Living Area Square Feet, Kitchen Quality, Total Square Feet of Basement Area, and Size of Garage in Car Capacity were among most valuable features.  

Exhibit 12: Relative Importance

PCA + Gradient Boosting Regressor

We then attempted to improve our baseline model performance by reducing the feature dimensionality. High dimensional data can be sparse or spread out, which makes it harder for certain algorithms to train effective models. In general, predictive algorithms benefit from optimal, non-redundant subset of features that improve the rate of training as well as enhance interpretability and generalization.

We managed our machine learning workflows with scikit-learn Pipelines. Scikit-learn Pipeline class allows us to apply a series of data transformations followed by the application of an estimator.

We built several pipelines, each with different estimator (e.g. Gradient Boosting Regressor, Linear Regression, etc.) For Gradient Boosting Machine our pipeline included:

  • Feature scaling, using Standard Scaler from scikit-learn package for Python
  • Dimensionality reduction, using PCA (retained 150 principal components)

After we completed feature engineering, we had over 200 features and about 1,500 rows in our training set. We decided to keep 150 principal components after examining cumulative percentage of variance chart. 150 components accounted for over 85% of variance of our data. Variance measures how spread out the dataset is.

Exhibit 13: Cumulative Percentage of Variance

Not all tweaks improve results. After we implemented PCA, our cross validation scores did not improve. In fact, our scores deteriorated (cross validation score declined to 0.87 from 0.91 for baseline model). We believe that reducing dimensions caused loss of some important information. PCA not only removed random noise in our data but also some valuable inputs.

PCA + Multivariate Linear Regression

For Multivariate Linear Regression our pipeline included:

  • Feature scaling, using Standard Scaler from scikit-learn package for Python
  • Dimensionality reduction, using PCA (retained 150 principal components)

Using PCA with Multivariate Linear Regression did not produce good results as well. Our cross validation score decreased as compared to a baseline model (training Multivariate Linear Regression using the entire set of features).  

Model Data Comparison

XG Boost model was our best performing model, while multivariate linear regression was our worst performing model. The results were similar among Ridge, Lasso and Elastic Net models.

Exhibit 14: Comparison of Different Models 

Using single isolated models gives us a decent result. But usually all real life problems do not have a direct linear or non-linear relationship with the target variable that can be captured alone by a single model. An ensemble of conservative and aggressive, linear and non-linear models best describes the housing price prediction problem.

Stacking and Ensembling

To begin with, we tried a simple ensemble model of XGBoost (non-linear) and ENet (linear) with a 50-50 weightage.

Next, following the standard stacking approach, we stacked different models to see if we could do better. Our stacked model consisted of the linear ENet model, a conservative random forest of short depth, a fully-grown aggressive random forest, a conservative gradient boosting of short depth, and, finally, a fully-grown aggressive gradient boosting model.

The performance has been recorded below:

Exhibit 15: Model Performance 

Conclusion

The below correlation heatmap shows our predicted sale prices for some of the models used. We can see that Elastic Net, Lasso and Ridge were very similar in nature, whilst Ensembling and Stacking was also very similar. The one standalone model with distinctly different results was the XGBoost one.

Exhibit 16: Prediction Similarities 

Further Exploration

  1. Explore the correlation between independent variables
  2. Investigate more feature engineering
  3. Apply clustering analysis to create new features
  4. Use different feature selection methods for different models: drop certain features for linear models while keeping most of features for tree-based models

About Authors

Yulia Norenko

View all posts by Yulia Norenko >

Howard Chang

Howard is currently a NYC Data Science Academy Fellow with a MS in Applied Math and Statistics from Stony Brook University. He has work experience in Portfolio Finance and Margin at a billion dollar multi-strategy hedge fund and...
View all posts by Howard Chang >

Lavanya Gupta

View all posts by Lavanya Gupta >

Silvia Lu

Silvia is currently working as a Data Analysis Intern at the Aviation Planning Department of Port Authority of New York and New Jersey. She also has a Psychology background and is a second-year graduate student in New York...
View all posts by Silvia Lu >

Related Articles

Capstone
Catching Fraud in the Healthcare System
Capstone
The Convenience Factor: How Grocery Stores Impact Property Values
Capstone
Acquisition Due Dilligence Automation for Smaller Firms
Machine Learning
Pandemic Effects on the Ames Housing Market and Lifestyle
Machine Learning
The Ames Data Set: Sales Price Tackled With Diverse Models

Leave a Comment

Cancel reply

You must be logged in to post a comment.

Predicting House Prices with Machine Learning Algorithms - IntelliNova November 1, 2018
[โ€ฆ] Read More [โ€ฆ]

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