Chapter 4 Data Pre-processing

The goal of this project is to predict the sale price of houses using a large set of house features by applying advanced regression techniques. However, before we jump into building a highly accurate prediction model, an extensive amount of data pre-processing has to be done. The major pre-processing tasks employed in this project are: data cleaning, to address missing values and noisy data; data transformation via smoothing, attribute construction, aggregation, discretization and hierarchy generation in order to transform the data into appropriate forms for mining; and feature selection by removing redundant features and features with near zero variability.

The first step is to explore the data and identify any discrepancies or opportunities for improvement by examining the following:

  • Missing Values

  • Attribute types

  • Distribution, Skewness and Relationships

  • Dimensionality

4.1 Identifying and Correcting Missing Values

4.1.1 Detect Missing Values

We can see from the heatmap in 4.1, that about 6% of the data is “missing”. A simple strategy to deal with missing values is to eliminate the features or examples containing missing values. However, given that there are a total of 13965 missing values spread across 34 features, dropping these data points could mean loss of data critical to the analysis. Instead, we will deal with missing values by imputation using a variety of methods.

Missing Values Heatmap

Figure 4.1: Missing Values Heatmap

Figure 4.2 shows that the features “PoolQC”, “MiscFeature”, “Alley”, and “Fence” have a high number of missing values. It might be tempting to drop these features, but with one quick look at the data description provided with the data (De Cock 2011a) we learn that “NA” in these cases means that the feature is not applicable, so it should be either “0” or “None”.

Number of Missing Values per Column

Figure 4.2: Number of Missing Values per Column

Table 4.1 shows the number and percentge of missing values per column in the combined dataset.

Table 4.1: Summary of Missing Values per Column
variable n_miss pct_miss
PoolQC 2909 99.6574169
MiscFeature 2814 96.4028777
Alley 2721 93.2168551
Fence 2348 80.4385063
FireplaceQu 1420 48.6467968
LotFrontage 486 16.6495375
GarageCond 159 5.4470709
GarageQual 159 5.4470709
GarageFinish 159 5.4470709
GarageYrBlt 159 5.4470709
GarageType 157 5.3785543
BsmtExposure 82 2.8091812
BsmtCond 82 2.8091812
BsmtQual 81 2.7749229
BsmtFinType2 80 2.7406646
BsmtFinType1 79 2.7064063
MasVnrType 24 0.8221994
MasVnrArea 23 0.7879411
MSZoning 4 0.1370332
Functional 2 0.0685166
BsmtHalfBath 2 0.0685166
BsmtFullBath 2 0.0685166
Utilities 2 0.0685166
SaleType 1 0.0342583
GarageArea 1 0.0342583
GarageCars 1 0.0342583
KitchenQual 1 0.0342583
Electrical 1 0.0342583
TotalBsmtSF 1 0.0342583
BsmtUnfSF 1 0.0342583
BsmtFinSF2 1 0.0342583
BsmtFinSF1 1 0.0342583
Exterior2nd 1 0.0342583
Exterior1st 1 0.0342583

4.1.2 Dealing With Missing Values

There are two types of missing values in this data-set, some values classified as “NA” are truly missing from the data, the information was not collected. The second type of “NA” means that the feature is not present, so “NA” in this case means either ‘Zero’ for numerical features, ‘None’ for categorical features, or ‘No’ for binary features. By examining the data and reading the data description provided (De Cock 2011a), we are able to determine each case.

4.1.2.1 Manual Imputation of NAs due to Inconsistent Values

Starting with groups of related features for garage, basement, pool and masonry attributes to explore the columns containing missing values, we discover that there are a few inconsistencies in the raw data, for example for the feature MasVnrType, there is a missing value for row ID=2611, but the column “MasVnrArea” shows a value, this obviously indicates that there is a MasVnrType associated with this instance, so instead of replacing it with “None”, we will impute the missing value with the most common value for this feature.

##      MasVnrType MasVnrArea
## 2611       <NA>        198

For features containing inconsistent values, listed in table 4.2, we will impute the missing values mannually according to each case.

Table 4.2: Inconsistent Values
Feature Method
BsmtQual Manual Imputation
BsmtCond Manual Imputation
GarageQual Manual Imputation
GarageFinish Manual Imputation
GarageCond Manual Imputation
GarageYrBlt Manual Imputation
BsmtCond Manual Imputation
PoolQC Manual Imputation
MasVnrArea Manual Imputation

Garage Features

Row 2127 has a garage, given that it has values for “GarageArea” (360), “GarageType” (Detchd), and “GarageCars” (1), so fill in the ‘GarageQual’,‘GarageFinish’, and ‘GarageCond’ with most the common for those features values.

GarageType GarageYrBlt GarageFinish GarageCars GarageArea GarageQual GarageCond
2127 Detchd NA NA 1 360 NA NA
Most Common Value per Feature
GarageType.Detchd
GarageYrBlt.1920
GarageFinish.Unf
GarageCars.1
GarageArea.240
GarageQual.TA
GarageCond.TA

Likewise, we can see that row 2577 has no garage, so we can fill in garage type with none.

There is an error in GarageYrBlt, from the summary we see a year 2207. We will update to 2007.

For the missing values in GarageYrBlt, we will fill in NAs with with the year the house was built.

Basement Features

From viewing at all the basement columns we can see that basement condition is missing in rows 2041, 2186, 2525, and will replace with most the common feature for each column.

Pool Features

There are three pools where values for the ‘quality’ are missing, so we will fill in with the most common value based on the area of the pool.

MasVnrType Features

There is a missing value for row ID=2611 in the MasVnrType column, we will replace with most common “MasVnrType”.

4.1.2.2 Imputation with Mode for Categorical Features with a Few NAs

For some of the categorical features only missing a few values, we filled in the missing values with the most commonly occurring attribute value. Specially because for many of these the most frequent category was already over-represented, so it is pretty safe to assume that the missing values are more likely to be in the most common category.

1

Categorical Features with Few NAs

Figure 4.3: Categorical Features with Few NAs

Table 4.3: Few NAs
Feature Method
Utilities Mode
Functional Mode
Exterior1st Mode
Exterior2nd Mode
Electrical Mode
KitchenQual Mode
SaleType Mode

4.1.2.3 Imputation with “None” for Categorical Features

According to the data description file (De Cock 2011a) for the categorical features listed in MissValsSumm, NA means that the feature is not present in the house. For example, the house doesn’t have a garage. For these features the NA values were replaced with “None”.

Table 4.4: Categorical Features where NA means ‘None’
Feature Method
GarageFinish None
GarageQual None
GarageType None
GarageCond None
BsmtCond None
BsmtExposure None
BsmtQual None
BsmtFinType1 None
BsmtFinType2 None
FireplaceQu None
EnclosedPorch None
MiscFeature None
Alley None
Fence None
MasVnrType None

4.1.2.4 Imputation with Zero (0) for Numerical Features where NA means Feature is not Present

According to the data description file (De Cock 2011a) for the numerical features listed in table 4.5. NA means that the feature is not present in the house, so we replaced NA with the number zero for these features.

Table 4.5: NA means ‘0’
Feature Method
BsmtFinSF1 0
BsmtFinSF2 0
BsmtUnfSF 0
TotalBsmtSF 0
BsmtFullBath 0
BsmtHalfBath 0
GarageCars 0
GarageArea 0
MasVnrArea 0

4.1.2.5 Imputation with estimation for Features with Large Number of Missing Values

Lastly, we were left with two features as seen in 4.4. LotFrontage, which captures the linear feet of street-connected to the property; and MSZoning, which indicates the different zoning classifications ranging from agricultural to residential. Because these features had a large percentage of missing values, it might be better to estimate their value based on other attributes. I used the mice package(van Buuren and Groothuis-Oudshoorn 2011), which uses a Random Forest algorithm to estimate the missing values.

Remaining Missing Values

Figure 4.4: Remaining Missing Values

2

Table 4.6: Large Number of Missing Values
Feature Method
LotFrontage Prediction
MSZoning Prediction

After imputing values for all NA’s, confirm all missing values are now cleared.

Final Missing Values HeatMap

Figure 4.5: Final Missing Values HeatMap

4.2 Correct Data Types

The next step in pre-processing, after all the NA values have been cleared, is to identify and correct data type inconsistencies. The raw data shows that there are 43 factors, 37 integers, and 1 numeric data types.

## 
##  factor integer 
##      43      38
## 
##  factor integer numeric 
##      43      37       1

Our current dataset looks like this:

## Integer Features (int): Id MSSubClass LotFrontage LotArea OverallQual OverallCond YearBuilt YearRemodAdd X1stFlrSF X2ndFlrSF LowQualFinSF GrLivArea FullBath HalfBath BedroomAbvGr KitchenAbvGr TotRmsAbvGrd Fireplaces WoodDeckSF OpenPorchSF X3SsnPorch ScreenPorch PoolArea MiscVal MoSold YrSold
## Categorical Features: MSZoning Street LotShape LandContour LotConfig LandSlope Neighborhood Condition1 Condition2 BldgType HouseStyle RoofStyle RoofMatl ExterQual ExterCond Foundation Heating HeatingQC CentralAir PavedDrive SaleCondition
## Character features: Alley Utilities Exterior1st Exterior2nd MasVnrType BsmtQual BsmtCond BsmtExposure BsmtFinType1 BsmtFinType2 Electrical KitchenQual Functional FireplaceQu GarageType GarageFinish GarageQual GarageCond EnclosedPorch PoolQC Fence MiscFeature SaleType
## Numerical Features(num): MasVnrArea BsmtFinSF1 BsmtFinSF2 BsmtUnfSF TotalBsmtSF BsmtFullBath BsmtHalfBath GarageYrBlt GarageCars GarageArea SalePrice

However, the documentation on the data (De Cock 2011a) says that the data-set consist of 20 continuous features that refer to area dimensions, 14 discrete features that quantify the number of items in the house, 23 nominal categorical features that refer to types of dwellings, materials and conditions, and 23 ordinal categorical features that rate various property related items. After correcting the data types according to the documentstion, it should look as shown in table 4.7.

Table 4.7: How the Data Should Look
Cont_Features_20 Disc_Features_14 Nom_Categorical_23 Ord_Categorical_23
LotFrontage BsmtFullBath Neighborhood Utilities
MasVnrArea BsmtHalfBath SaleCondition LandSlope
BsmtFinSF1 FullBath HouseStyle ExterQual
BsmtFinSF2 HalfBath Street ExterCond
BsmtUnfSF BedroomAbvGr Alley BsmtQual
TotalBsmtSF KitchenAbvGr CentralAir BsmtCond
GarageArea TotRmsAbvGrd LandContour BsmtExposure
X1stFlrSF Fireplaces Condition1 BsmtFinType1
X2ndFlrSF GarageCars Condition2 BsmtFinType2
LowQualFinSF GarageYrBlt BldgType HeatingQC
GrLivArea YearBuilt RoofStyle Electrical
X3SsnPorch YearRemodAdd RoofMatl KitchenQual
PoolArea MoSold Exterior1st Functional
WoodDeckSF YrSold Exterior2nd FireplaceQu
SalePrice Foundation GarageFinish
EnclosedPorch Heating GarageQual
ScreenPorch GarageType GarageCond
LotArea MiscFeature PavedDrive
MiscVal SaleType PoolQC
OpenPorchSF MSSubClass Fence
MSZoning OverallQual
MasVnrType OverallCond
LotConfig LotShape

The first step is to convert the numeric features to the appropriate data type.

The second step, is to convert missclassified numeric features to categorical.

The third step is to add levels to ordinal categorical features.

data_full$Utilities<-factor(data_full$Utilities,levels=c("ELO","NoSeWa","NoSewr","AllPub"), ordered=TRUE)

data_full$ExterQual<-factor(data_full$ExterQual, levels=c("Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$ExterCond<-factor(data_full$ExterCond, levels=c("Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$FireplaceQu<-factor(data_full$FireplaceQu, levels=c("None","Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$Functional<-factor(data_full$Functional,levels=c("Sal", "Sev", "Maj2", "Maj1","Mod","Min2","Min1","Typ"), ordered=TRUE)

data_full$PoolQC<-factor(data_full$PoolQC,levels=c("None","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$BsmtCond<-factor(data_full$BsmtCond, levels=c("None","Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$BsmtQual<-factor(data_full$BsmtQual,levels=c("None","Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$BsmtExposure<-factor(data_full$BsmtExposure, levels=c("None", "No", "Mn", "Av", "Gd"), ordered=TRUE)

data_full$BsmtFinType1<-factor(data_full$BsmtFinType1, levels=c("None","Unf","LwQ","Rec","BLQ","ALQ","GLQ"), ordered=TRUE)

data_full$BsmtFinType2<-factor(data_full$BsmtFinType2, levels=c("None","Unf","LwQ","Rec","BLQ","ALQ","GLQ"), ordered=TRUE)

data_full$HeatingQC<-factor(data_full$HeatingQC, levels=c("Po", "Fa", "TA", "Gd", "Ex"), ordered=TRUE)

data_full$KitchenQual<-factor(data_full$KitchenQual, levels=c("Po", "Fa", "TA", "Gd", "Ex"), ordered=TRUE)

data_full$GarageQual<-factor(data_full$GarageQual, levels=c("None","Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$GarageCond<-factor(data_full$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"), ordered=TRUE)

data_full$Electrical<-factor(data_full$Electrical, levels=c("Mix","FuseP","FuseF","FuseA","SBrkr"), ordered=TRUE)

data_full$GarageFinish<-factor(data_full$GarageFinish, levels=c("None","Unf","RFn","Fin"), ordered=TRUE)

data_full$PavedDrive<-factor(data_full$PavedDrive, levels=c("N","P","Y"), ordered=TRUE)

data_full$Fence<-factor(data_full$Fence, levels=c("None","MnWw","GdWo", "MnPrv", "GdPrv"), ordered=TRUE)

data_full$OverallQual<-factor(data_full$OverallQual, levels=c("1", "2","3","4", "5", "6", "7", "8", "9", "10"), ordered=TRUE)

data_full$OverallCond<-factor(data_full$OverallCond, levels=c("1", "2","3","4", "5", "6", "7", "8", "9", "10"), ordered=TRUE)

data_full$GarageType<-factor(data_full$GarageType, levels=c("None","2Types","Attchd", "Basment","BuiltIn","CarPort","Detchd" ), ordered=FALSE)

data_full$LandSlope<-factor(data_full$LandSlope, levels=c("Gtl","Mod","Sev" ), ordered=TRUE)

data_full$LotShape<-factor(data_full$LotShape, levels=c("IR1","IR2", "IR3", "Reg" ), ordered=TRUE)

Confirm all features are now approrpiately classified by their data type.

*** 15 Discrete Features: Id YearBuilt YearRemodAdd BsmtFullBath BsmtHalfBath FullBath HalfBath BedroomAbvGr KitchenAbvGr TotRmsAbvGrd Fireplaces GarageYrBlt GarageCars MoSold YrSold
*** 20 Continous Feature: LotFrontage LotArea MasVnrArea BsmtFinSF1 BsmtFinSF2 BsmtUnfSF TotalBsmtSF X1stFlrSF X2ndFlrSF LowQualFinSF GrLivArea GarageArea WoodDeckSF OpenPorchSF EnclosedPorch X3SsnPorch ScreenPorch PoolArea MiscVal SalePrice
*** 23 Nominal Categorical Features: MSSubClass MSZoning Street Alley LandContour LotConfig Neighborhood Condition1 Condition2 BldgType HouseStyle RoofStyle RoofMatl Exterior1st Exterior2nd MasVnrType Foundation Heating CentralAir GarageType MiscFeature SaleType SaleCondition
*** 23 Ordered Categorical Features: LotShape Utilities LandSlope OverallQual OverallCond ExterQual ExterCond BsmtQual BsmtCond BsmtExposure BsmtFinType1 BsmtFinType2 HeatingQC Electrical KitchenQual Functional FireplaceQu GarageFinish GarageQual GarageCond PavedDrive PoolQC Fence

4.3 Feature Transformation

With clean data in the correct form, it is time to start the Exploratory Data Analysis (EDA). By visualizing the data we hope to uncover interesting patterns and relationships which we could use to enhance the predictive value of the features via transformation or new feature creation.

4.3.1 Visualizing the Distribution and Spread of Target Feature: SalesPrice

The histogram of the “SalesPrice” feature in figure 4.6 shows a few very large values on the right, making the distribution of the data right skewed. Since the goal is to predict the continuous numerical variable “SalesPrice” with regression models, it might be useful to transform it, since one of the assumptions of regression analysis is that the error between the observed and expected values (the residuals) should be normally distributed, and violations of this assumption often stem from a skewed response variable. We can make the distribution more normal by taking the natural logarithm, since in a right-skewed distribution where there are a few very large values, the log transformation helps bring these values into the center. After applying the log transformation, as seen in 4.7, the distribution looks more symmetrical.

Target Feature: SalesPrice

Figure 4.6: Target Feature: SalesPrice

Log-Transformed SalesPrice

Figure 4.7: Log-Transformed SalesPrice

4.3.2 Features Highly Correlated with Sales Price

Given the large number of features in the data-set, we will focus our data engineering efforts on those features which are highly correlated with our variable of interest.

For continuous features, the correlation plot shows Garage Area, Great Living Room Area, First Floor SF, Total Basement SF, and Masonry Veneer Area have a strong positive correlation with Sale Price.

Continous Features and Sale Price Correlation Plot

Figure 4.8: Continous Features and Sale Price Correlation Plot

3

From the histograms we can see that many of the continuous independent variables are right skewed, similar to the response, so it might be a good idea to normalize these prior to modeling, since many algorithms perform better with normalized data because it improves the numerical stability of the model and reduces training time (Zhang_2019).

Continous Features Distribution Plots

Figure 4.9: Continous Features Distribution Plots

4

The correlation plot for the discrete features in 4.10 shows that YearBuilt, YearRemodAdd, GarageYearBuilt, GarageCars, FullBath, FirePlaces, and TotRmsAbvGrd are strongly and positively correlated with SalePrice:

Discrete Features and Sale Price Correlation Plot

Figure 4.10: Discrete Features and Sale Price Correlation Plot

5

4.3.3 Attribute Construction from Year Features

The barplot of Year Built shows a clear distinction between the number of houses built and sold in the 2000s vs the number built and sold in before that time. The distribution is left skewed, as we can see that the mean of the distribution is less than the median. Most importantly, since there are so many unique years, it might be helpful to create a new “age” variable by subtracting the year built from 2010, which is the upper limit of year sold in the data-set. And we can further refine this new age variable later on by binning age groups into buckets from old to new, thereby reducing the number of levels.

Year Built vs Sales Price

Figure 4.11: Year Built vs Sales Price

6

Curiously, in the scatter plot shown in 4.12, where the dots have been colored in light blue by the YearRemodAdd feature, newer houses are displaying as having been remodeled, apparently if the house has not been remodeled the year remodeled defaults to the year built. To improve the value of this metric we can create a new binary feature for Remodeled: Yes or No. Also, it might be useful to create a feature to show how recently the house was remodeled, and bin these into categories from most recently remodeled.

Year Bult vs Sales Prie Colored by Year Remodeled

Figure 4.12: Year Bult vs Sales Prie Colored by Year Remodeled

7

In order to make the year features more meaningful, we created new attributes as indicated in the table below. In addition to the building age and time since remodeled features, we added a feature to indicate if the home is a new build, since it is likely that being a new home will have an impact on the sale’s price. We also added a feature for the year the house was sold, since macro economic events, like the economic depression in 2008, could also impact the sale price. Later, we simplify some of these newly created features by binning them into categories with fewer levels. Since all of the categorical features will have to be converted into numeric via dummy coding for modeling, having fewer levels will help with model performance and dimensionality reduction.

Attribute Construction from Year Features

New Feature Method
BldgAge 2010 - YearBuilt
NewBuild If YearBuilt or YearBuilt + 1 = YrSold then NewBuild = 1
Remod If YearBuilt = YearRemodAdd then Remod = 0
TimeSinceRemod 2010 - YearRemodAdd
LastSold 2010 - YrSold

4.3.4 Reducing Levels by Grouping Unrepresented Categories

Another way that we can improve the data for mining is to reduce the levels in categorical variables by merging under-represented categories. For example, in the case of the fireplaces, we can see in scatterplot 4.13 that there are only a few houses that have 3 fireplaces, and the scatter plot shows that the relationship between three fireplaces and price is not much different than between two fireplaces and price, so we can merge these into one level.

Fireplaces Scatter Plot

Figure 4.13: Fireplaces Scatter Plot

Grouping Fireplace Features

Fireplaces After Groupping

Figure 4.14: Fireplaces After Groupping

Similarly, the scatter plot in 4.15 of the “GarageCars” variable shows that few houses have more than three garages, so we could simplify the levels in this feature by keeping only three levels: 1,2, and 3+.

Discrete Features Scatter Plots

Figure 4.15: Discrete Features Scatter Plots

Garage Cars After Groupping

Figure 4.16: Garage Cars After Groupping

8

We applied this treatment to the features listed in the table below. This will make these features more robust for modeling.

Reducing Levels by Grouping

New Feature Method
GarageCars Merge 4 and 3
Fireplaces Merge 3 and 2
Electrical Merge FuseF and FuseA
Function Merge Maj1 and Mod, Min1 and Min2

Grouping Electrical Features

Electrical vs Sales Price Scatterplot

(#fig:GrouppingElectrical )Electrical vs Sales Price Scatterplot

Grouping Functional Features

Functional vs Sales Price Scatterplot

Figure 4.17: Functional vs Sales Price Scatterplot

4.3.5 Attribute Construction by Combining some Features to make New Features.

There are four different columns related to the number of bathrooms in different areas of the home. Individually these features may not carry as mush weight as combined into a single feature for total number baths.

bsmtFB<-ggplot(data_2_train)+aes(BsmtFullBath)+ labs(title="Basement Full Bath", subtitle="Training Data")+
geom_bar(fill="#053061", color="#F5F5F5")+  theme(
  panel.border = element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  axis.line = element_line(colour = "#053061"))+ scale_x_continuous(labels = function(x) format(x, scientific = FALSE)) 

BsmtHB<-ggplot(data_2_train)+aes(BsmtHalfBath)+ labs(title="Basement Half Bath", subtitle="Training Data")+
geom_bar(fill="#053061", color="#F5F5F5")+  theme(
  panel.border = element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  axis.line = element_line(colour = "#053061"))+ scale_x_continuous(labels = function(x) format(x, scientific = FALSE)) 

hFB<-ggplot(data_2_train)+aes(FullBath)+ labs(title="Number of Full Baths in the Home", subtitle="Training Data")+
geom_bar(fill="#053061", color="#F5F5F5")+  theme(
  panel.border = element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  axis.line = element_line(colour = "#053061"))+ scale_x_continuous(labels = function(x) format(x, scientific = FALSE))

hhB<-ggplot(data_2_train)+aes(HalfBath)+ labs(title="Number of Half Baths in the Home", subtitle="Training Data")+
geom_bar(fill="#053061", color="#F5F5F5")+  theme(
  panel.border = element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  axis.line = element_line(colour = "#053061"))+ scale_x_continuous(labels = function(x) format(x, scientific = FALSE)) 

grid.arrange(bsmtFB, BsmtHB, hFB, hhB, 
             ncol = 2, nrow = 2)
Bath Features

Figure 4.18: Bath Features

9

Close look at fullbath = 0 Some homes are showing as having zero baths, this might be a mistake, so it will be usefull to look closer are these examples. The nine rows which had zero full bath, did have other bathrooms in either the basement, or half bath, it is ok to leave them for now, since it will be better to combine all baths together and have one feature for the total baths.

missing_bath <- filter(data_2_train, FullBath ==0)
bath_features <- names(data_2_train)[sapply(names(data_full), function(x) str_detect(x, "Bath"))]

data_2_train[c(54, 189, 376, 598, 635, 917, 1164,1214, 1271),c("BsmtFullBath","BsmtHalfBath","FullBath","HalfBath")]

We will also combine the basement finished squared feet and the porch features. Furthermore, we created a new feature for total area by adding the living area square feet and the total basement square feet. The goal here is to create new features that might have a stronger predictive power than the individual original features. Prior to modeling, we will be removing all of the features rendered redundant by the feature creation process. The table below summarizes the features we constructed by adding the same type of feature together to form a total.

New Feature Construction by Combining Existing Features

New Feature Method
BSmtFinSFComb BsmtFinSF1 + BsmtFinSF2
TotalArea GrLivArea + TotalBsmtSF
TotalBaths FullBath + HalfBath + BsmtFullBath + BsmtHalfBath
TotalPorchSF OpenPorchSF + EnclosedPorch + X3SsnPorch + ScreenPorch

4.3.6 Attribute Construction by Binning

Some of the categorical variables have a large number of levels. For example, “Neighborhood”, one of the features most highly correlated with sale price, has 25 different levels.

Neighborhood vs Sale Price

Figure 4.19: Neighborhood vs Sale Price

Descretization and Binning-Neighboorhood Concept hirearchy discretization and binning is a way to reduce the the number of distinc values per attribute, we will group the neighborhoods together to create fewer categories. We can reference the SalePrice to find similar neighboorhoods.

Table 4.8: All Neighborhoods by Median Sales Price
Neighborhood mean_1 median_1 st_dev sum_gr range
NridgHt 316270.62 315000 96392.545 24352838 457657
NoRidge 335295.32 301500 121412.659 13747108 565000
StoneBr 310499.00 278000 112969.677 7762475 386581
Timber 242247.45 228475 64845.652 9205403 241000
Somerst 225379.84 225500 56177.556 19382666 278848
Veenker 238772.73 218000 72369.318 2626500 222500
Crawfor 210624.73 200624 68866.395 10741861 302150
ClearCr 212565.43 200250 50231.539 5951832 198000
CollgCr 197965.77 197200 51403.666 29694866 314870
Blmngtn 194870.88 191000 30393.229 3312805 104666
NWAmes 189050.07 182900 37172.218 13800655 217300
Gilbert 192854.51 181000 35986.779 15235506 236500
SawyerW 186555.80 179900 55651.998 11006792 244000
Mitchel 156270.12 153500 36486.625 7657236 186500
NPkVill 142694.44 146000 9377.315 1284250 27500
NAmes 145847.08 140000 33075.345 32815593 257500
SWISU 142591.36 139500 32622.918 3564784 140000
Blueste 137500.00 137500 19091.883 275000 27000
Sawyer 136793.14 135000 22345.129 10122692 127617
BrkSide 124834.05 124300 40348.689 7240375 184200
Edwards 128219.70 121750 43208.616 12821970 261500
OldTown 128225.30 119000 52650.583 14489459 437100
BrDale 104493.75 106000 14330.176 1671900 42000
IDOTRR 100123.78 103000 33376.710 3704580 134600
MeadowV 98576.47 88000 23491.050 1675800 76400
Table 4.9: The Most Heterogeneous Neighborhoods
Neighborhood mean_1 median_1 st_dev sum_gr range
Blmngtn 194870.88 191000 30393.229 3312805 104666
MeadowV 98576.47 88000 23491.050 1675800 76400
Sawyer 136793.14 135000 22345.129 10122692 127617
Blueste 137500.00 137500 19091.883 275000 27000
BrDale 104493.75 106000 14330.176 1671900 42000
NPkVill 142694.44 146000 9377.315 1284250 27500

Grouping Neighborhoods

## Picking joint bandwidth of 17200
Spread Based on Sale Price

Figure 4.20: Spread Based on Sale Price

In order to avoid data leakage we could use the “Overall Quality” feature, which shows a similar relationship with the neighborhoods, to create 5 bins for neighborhood categories ranging from low (1) to high (5). As we can see below grouping neighborhoods into 5 categorires looks similar whether we look at it by the “Overall Quality” feature or by SalePrice.

Neighborhood Category by Overal Quality

Figure 4.21: Neighborhood Category by Overal Quality

Neighborhood Category by SalePrice

Figure 4.22: Neighborhood Category by SalePrice

10

In addition to the “Neighborhood” feature, we also used binning as a means to reduce the number of unique levels for the “Month” feature. For the Month feature, we ploted the months, and put them into bins according to low, medium, or high season, based on the number of houses sold. The AgeCat and RemodelFromCat are new features based of other features we contructed previously from the year features. These features contain fewer levels, which is one of our goals here, to reduce the nuber of levels in categorical features, so that the prediction model is simpler, which as mentioned before reduces the error. The table below shows the attributes constructed by binning.

Attribute Construction by Binning

New Feature Method
AgeCat BldgAge into 4 age categories: Antique, Old, Mid, New
RemodelFromCat Max year in Data (2010) - YearRemodAdd into 4 categories
SeasonSale MoSold into 3 categories (Low, Mid & High)
NeighCat Neighborhood into 5 categories

Bin the age of the house into 4 categories

Bin the year-since-remodeled of the house into 4 categories

Bin the sale month into seasons from low season to high season based on sales

Update Categorical Features to have numerical value

4.3.7 New Variables by Interactions

The last type of feature engineering we attempted is attribute construction from interactions by multiplying certain features listed in the table below.

New Variables from Interactions

New Feature Method
OverallScore GarageQual * GarageCond
GarageScore OverallQual * OverallCond
ExterScore ExterQual * ExterCond
KitchenScore KitchenAbvGr * KitchenQual
GarageGrade GarageArea * GarageQual

4.4 Dimensionality and Numerosity Reduction

The last major step left in pre-processing is dimensionality and numerosity reduction through the following steps:

    1. Delete Redundant Features Due to Data Engineering
    1. Delete Outliers
    1. Delete Features with Near Zero Variability

4.4.1 Outliers

According to the data collector: “There are 5 observations that an instructor may wish to remove from the data set before giving it to students. Three of them are true outliers (Partial Sales that likely don’t represent actual market values) and two of them are simply unusual sales (very large houses priced relatively appropriately). I would recommend removing any houses with more than 4000 square feet from the data set (which eliminates these 5 unusual observations)”

As we can see from the scatterplot 4 of the outlier are in the training set, which means that one is in the test set, because we are using the test set to submit to Kaggle.com for evalueation, we can not remove any rows from the test set (or it would be incomplete). Here, we will only remove the outliers indicated by the data collector in the training set only. Additional outlier detection could be useful in the feature.

For now, we are only deleting the outliers in the training set.

View data shape after feature engineering

Export Pre-processed Data

References

De Cock, Dean. 2011a. “Ames, Iowa: Alternative to the Boston Housing Data as an End of Semester Regression Project.” Journal of Statistics Education 19 (3). Taylor & Francis.

van Buuren, Stef, and Karin Groothuis-Oudshoorn. 2011. “mice: Multivariate Imputation by Chained Equations in R.” Journal of Statistical Software 45 (3): 1–67. https://www.jstatsoft.org/v45/i03/.


  1. The graphs were produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  2. The graph was produced with function plot_missing() from package ‘DataExplorer’ (Cui 2020).↩

  3. The correlation plot was produced with the ggcorr() function from package ‘GGally’ (Schloerke et al. 2021).↩

  4. The histograms were produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  5. The correlation plot was produced with the ggcorr() function from package ‘GGally’ (Schloerke et al. 2021).↩

  6. The bar-plot was produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  7. The scatter plot was produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  8. The plots were produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  9. The plots were produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩

  10. The plots were produced with ggplot() function from package ‘ggplot2’ (Wickham 2016).↩