Data Analysis on Ames Housing Sale Price Prediction

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

No comments found.

View Posts by Categories


Our Recent Popular Posts


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 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 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 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