Data For Testing: Predict Iowa Housing Prices

Posted on Dec 12, 2019
The skills I demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.


With 79 explanatory variables (36 is quantitative, 43 categorical) describing almost every aspect of residential homes in Ames, Iowa, this Kaggle competition challenges us to predict the final price of each home. There are 1460 instances of training data, as well as 1460 of test data.  We intend to generate the submission data set for the Kaggle House Price competition by the following workflow:

We used MLflow, which is an open source platform for the machine learning lifecycle, to record models, track and visualize results for easy model comparison and hyperparameter tuning. For this project, we run models and record locally. The platform also provides a solution to collaborate as a team, which is an option for our future work.

The main page of ML Flow which automatically records the results of machine learning models.
ML Flow provides visualization of results given metrics.

Exploratory Data Analysis (EDA)

  • Understand the problem. We first look at the data and each variable about their meaning and importance for this problem.

  • Univariable study. We focus on the dependent variable ('SalePrice'). 

    • We made the histogram for Sale Price. We found that the distribution of the sale price is right-skewed.

    • We also made the Quantile-Quantile (Q-Q) Plot. The points are not around the linear line. It means that the sale price is not normally distributed.

    • We decided to take the log of the sale price. Logarithmic price scales are better than linear price scale at showing price increase or decrease in this case because sale prices are far apart in the data. In addition, as shown below, after taking log, the sale price is more normally distributed.

  • Multivariate study. We try to understand how the dependent variable and independent variables are related.

    • In order to understand how the dependent variable and independent variables are related, we prepare a correlation matrix heatmap to visualize the correlation between features. The correlation heatmap below shows how strongly pairs of features are related. We found that most numeric features are positively correlated with the sale price. OverallQual (Overall Quality) has the highest correlation with the sale price.

    • In addition, we are curious if there are multicollinearity among independent variables. Multicollinearity means there is high intercorrelations among the independent variables. When some of the features are multicollinear the model coefficients can become ambiguous. We will need to do feature engineering for the pairs with high multicollinearity later. We created the correlation matrix heatmap with top 10 correlated pairs.  That revealed a number of key correlations. For example, GarageYrBlt (year garage was built) is highly correlated with YearBuilt(original construction date). TotRmsAbvGrd (total rooms above grade) and GrLivArea (Above ground living area) are highly correlated. GarageCars(size of garage in car capacity) and GarageArea (size of garage in square feet) are highly correlated. 1stFlrSF(first floor square feet) and TotalBsmtSF (total square feet of basement area) are highly correlated. TotRmsAbvGrd (total rooms above ground) and GrLivArea (above ground living area) are highly correlated.

  • Basic cleaning. We clean the dataset and handle the missing data, outliers and both numeric and categorical variables.

    • For missing data, we handle the missing values on a case by case basis. For example, we found a pattern that basement related columns have missing values when there is no basement. Therefore, we fill the missing value with ‘None.’ For MSZoning(the general zoning classification), it is a categorical column. We fill the missing values with the mode of the values in this column.

    • For outliers, we identified some outliers from scatter plots between independent variable and dependent variables.

      • Example 1:  for GrLivArea (Ground Living Area), the two observations in the bottom could be agricultural area which could explain the low price. We consider these two observations outliers and removed them. The two observations in the top look like two special cases. However, they seem to follow the trend. Therefore, we keep these two observations. 

      • Example 2: In scatter plot of TotalBsmtSF (total basement square feet) and sale price, there is one observation is far from the rest of the observations in the scatter plot. We considered this observation as an outlier. Therefore, it is removed as well.

    • We clean the data so that columns have correct data types (nominal, ordinal or numerical).  We converted numerical data to categorical data in a column because the column should be categorical. The ‘MSSubClass’ columns have numerical values. But these values do not have mathematical meaning, and adding them does not make sense. Therefore, we convert the number to strings, so that ML model recognizes this column as categorical.  We also encode values in the nominal column as ordered numbers when there is information available so that ML models recognize that data in this column have order. 

  • Test assumptions. We check if our data meet the assumptions of multiple linear regression model. 

    • Assumption 1: the relationship between the independent variable and the dependent variable is linear. 

      • We created a scatter plot between independent variables and dependent variables. We found a lot of numerical columns show a linear relationship with sale price, especially OverallQual, GrLivArea, GarageArea, TotalBsmtSF and FullBath as shown below.

    • Assumption 2: The error is normally distributed.

      • We plot the histogram and Q-Q plot of the error.

      • After removing outliers which are hard to fit in the models,  the distribution of the error is more normal. 

    • Assumption 3 &4 : errors are independent, and errors have constant variance. 

      • If errors obey the same distribution, we should obtain very similar probability density plot when we randomly choose a large enough subset from the observations. Below, we compare the probability density plot of the normal distributions obtained from errors of all samples and half samples. The distribution for all sample and half samples are almost perfectly aligned. We confirmed that errors are independent with constant variance.

  • Feature Engineering.

     We use domain knowledge of the data to create features that make machine learning algorithms work. 

      • For categorical features, we did one hot encoding/ label encoding for different models

      • We also split feature features. For example, we split MSSubclass because it contains duplicate information with other features. 

      • We combine features to created a new feature. For example, we combine “YrSold” and “YearBuilt” to a new feature called “YearOld.” We combined “YrSold” and “YearRemodAdd” to a new feature “YearSinceRemodel.” 

  • Function. The findings in this data exploration will be summarized in a data processing function. 

    • We created data processing functions that  handle the missing values, outliers, log transformation, feature engineering. This function has switches, so that data are cleaned differently prior feeding to different machine learning models. For example, we use label encoder for categorical features while using Random Forest model, and we use one hot encoding for categorical features while using multiple linear regression model. 


Models & Feature Engineering 

Domain knowledge plays an important role in machine learning process. Now that we have an overall understanding of all features, it’s highly possible that the house price is in linear relationship with its key features in this case, for example, a house with a larger number of rooms has  higher price, as does a house with a larger garage. 

Linear Models : 

Based on the above understanding, we did our feature engineering in a dynamic way by testing linear models after train/test split. Our findings are:

  • Addressing the hard to fit outlier points materially improved model scores since outliers can greatly affect linear model performance. 

  • Feature engineering like log transformation, handling ordinal features make significant improvement.

  • All models have overfitting issues due to unrecognized multicollinearity, and further regularization is needed.   



Below are the hyperparameters and model performance after cross validation:

Ridge: alphas = [14.5, 14.6, 14.7, 14.8, 14.9, 15, 15.1, 15.2, 15.3, 15.4, 15.5]

Lasso: alphas = [5e-05, 0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008]

ElasticNet: alphas = [0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007]

      ratio = [0.8, 0.85, 0.9, 0.95, 0.99, 1]




Score std











  • Lasso consistently performed better than Ridge. 

  • ElasticNet’s result is better than Ridge and Lasso. The best rho is near 0 but not 0.   


Random Forest & Gradient Boost:

  • Data processing

    • For Random Forest, we used labelencoder from sklearn to transform columns with categorical data to integers. We did not use onehotencoder or dummification because the tree generally tend to grow in one direction if we use dummified data. 

    • For gradient boost, we also used labelencoder.

  • Tuning hyperparameters with randomized search and grid search from sklearn

    • We did hyperparameter tuning with both random search and grid search. Grid search is an exhaustive search. For each combination of hyperparameters, model will be trained, and score will be computed on the test data. In other words, grid search takes a lot of time. In contrast to grid search, random search only select random combinations to train the model and score. Randomized search takes a shorter time to run than grid search. 

    • We have a large dataset, which make it inefficient to use gridsearch when we want to test various hyperparameter values. Therefore, we first use random search to narrow down the possible best combination of hyperparameters. Once we found the best hyperparameter combinations from random search, we set up a grid search around the found hyperparameters to find the best hyperparameters.

  • Finding:

    • Random ForestTest RMSE is 0.1591. 

    • Gradient Boosting Test RMSE is 0.122

    • Ridge, Lasso and Elastic Net performs better than Random Forest and Gradient Boosting. 

    • Gradient Boosting performs better than Random Forest

  • Feature Importance

    • OverallQual (Overall Quality), GrLivArea (Above Ground Living Area), ExterQual (Quality of Material on the Exterior), YearsOld, GarageCars(size of garage in car capacity) and KitchenQual (Kitchen Quality) are the features that are shown as important in both Random Forest and Gradient Boost. 

    • Overall Quality is very important for sale price. 

    • TotaBsmtSF (Total Basement Square Feet) shows up in Random Forest Feature Importance, but it is not shown in the Gradient Boost Feature Importance. 

    • YearSinceRemodel shows in Gradient Boost Feature Importance, but it does not show up in the Random Forest Feature Importance. 


To boost our model score, we also tried stacking different combinations of models with StackingCVRegrassor from sklearn, and found out that a combination of different kinds such as linear models, tree models can generate better results, even though some of the models do not perform well by running individually. The reason behind this is stacking works by combining the best performance part of all models. A forest is smarter than a smart tree. Our Result:

(RMSLE score on train data: 0.08024. Kaggle Public Score on test data: 0.11961. 

Rank: top 18%) 

About Authors

Huimin Ou

Huimin Ou is NYC Data Science Fellow with a Bachelor's Degree in Industrial Engineering from University of Wisconsin-Madison. Before coming to NYCDSA, Huimin is an industrial engineer with experience in business data analytics, process improvement and project management....
View all posts by Huimin Ou >

Hanxiao Zhang

Hanxiao(Mia) Zhang is NYC Data Science Fellow with a Master's Degree in Finance from Fordham University. Before enrolling in the NYCDSA, she worked in the finance and business sector for over 4 years with extensive client interactions on...
View all posts by Hanxiao Zhang >

Related Articles

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