1 Background

As a statistical consultant working for a real estate investment firm, your task is to develop a model to predict the selling price of a given home in Ames, Iowa. Your employer hopes to use this information to help assess whether the asking price of a house is higher or lower than the true value of the house. If the home is undervalued, it may be a good investment for the firm.

2 Training Data and relevant packages

In order to better assess the quality of the model you will produce, the data have been randomly divided into three separate pieces: a training data set, a testing data set, and a validation data set. For now we will load the training data set, the others will be loaded and used later.

load("ames_train.Rdata")
library(dplyr)
## Warning: package 'dplyr' was built under R version 3.3.3
ames_train$Overall.Qual<-as.factor(ames_train$Overall.Qual)
ames_train$Overall.Cond<-as.factor(ames_train$Overall.Cond)

am<-select(ames_train,price,area,Lot.Area,Year.Built,Overall.Qual,Land.Slope,Sale.Condition,Overall.Cond)
am<-data.frame(am) 

Use the code block below to load any necessary packages

library(statsr)
library(dplyr)
library(BAS)

library(MASS)
library(ggplot2)
library(devtools)
## Warning: package 'devtools' was built under R version 3.3.3
getwd()
## [1] "C:/Albert/Coursera Statitics with R/Statistics with R Capstone/Wk7"

2.1 Part 1 - Exploratory Data Analysis (EDA)

When you first get your data, it’s very tempting to immediately begin fitting models and assessing how they perform. However, before you begin modeling, it’s absolutely essential to explore the structure of the data and the relationships between the variables in the data set.

Do a detailed EDA of the ames_train data set, to learn about the structure of the data and the relationships between the variables in the data set (refer to Introduction to Probability and Data, Week 2, for a reminder about EDA if needed). Your EDA should involve creating and reviewing many plots/graphs and considering the patterns and relationships you see.

After you have explored completely, submit the three graphs/plots that you found most informative during your EDA process, and briefly explain what you learned from each (why you found each informative).


2.1.1 Labeled Histogram and Data Description

The data was analyized and the following statistics were determined :

  • Least expensive house is $12,789 (9.5 log units) and is the 428th row of the data table
  • Most expensive house is $615,000 (13.3 log units) and is the 66th row of the data table
  • There are more expensive houses and fewer cheaper houses (left skewed)
  • The distribution is unimodal with a median price of $159467 (12.0 log units) indicated by the red line
  • The mean house price is $181190 (12.1 log units) indicated by the purple line
  • The largest number of houses are between $100,000 - $200,000 (11.7-12.2 log units) price range

The histogram, In Fig. I, depicts a disribution of the Ames Iowa houses by natural log of the price in US Dollars. There are 30 bins, each increasingly logarithymically, indicating the natural log of the price for each interval. The total span of the histogram is roughly $700,000 or(13.5 log units). The total count for each bin is located near the top of the bin column.

The blue shaded region for each bar in the histogram indicate the house was purchase under normal sale conditions. The salmon colored regions indicate other than normal sale conditions. The preponderance of the other than normal sale conditions occur for the higher priced houses.

## [1] "Table I:  Highest, Lowest, Median and Mean Priced Houses in Ames Training Data"
##                    Price LogPrice Index Count Neighborhood
## Least Expensive  12789.0      9.5   428     1      OldTown
## Most Expensive  615000.0     13.3    66     1      NridgHt
## Median          159467.0     12.0     0     0            0
## Mean            181190.1     12.1     0     0            0

2.1.2 Neighborhood Statistical Summary

The statistical summary is provided using individual boxplots for each Neighborhood in the Ames training data with respect to price. In order to better understand the statistical summary, a detailed explanation of Figure II is provided in the following section.

The boxplots are plotted sideways to reveal the information in a form much like a distribution. Each boxplot has units of price dollars (in thousands) with the following characteristics:

  • Box width corresponds to the price Inter Quartile Range or IQR

  • Box center bar is the median price value

  • Left and right box whisker(sometimes outliers) corresponds to the min(inverted triangle) and max(upright triangle) price values, correspondingly,

  • X in the box is the price mean

  • The red o corresponds to the price standard deviation

  • The NeighborhoodLabel maps the neighborhood name to its numerical value on the boxplot.

A red o represents the price standard deviation for each boxplot. By examination it is easy for you to see that the right-handedness of the red o decreases as you move your view upward from boxplot 1. The Neighboorhood associated with boxplot 1 is StoneBr and it has a maximum house price of $591587, a minimum price of $180000 and it has a price standard deviation of $123459. Correspondingly, the Neighborhood associated with boxplot 27 is Blueste and it has a maximum house price of $137000, a minimum price of $116500 it has a price standard deviation of $10381. Therfore the price standard deviation range or heterogenocity is from $10,000 to $123,000 when grouped by Neighborhood.

2.1.3 500 Lowest Priced Houses Scatter Plot

Figure III is a scatter plot of 500 lowest prices in the ames_train data set. The ordinate is the natural log of the selling price and the abscissa is the living space. The points are characterized by each house’s overall Quality and fro this reason it is needed. I choose to use this plot since the under priced holmes may be more likely to be in the lower half.


2.2 Part 2 - Development and assessment of an initial model, following a semi-guided process of analysis

2.2.1 Section 2.1 An Initial Model

In building a model, it is often useful to start by creating a simple, intuitive initial model based on the results of the exploratory data analysis. (Note: The goal at this stage is not to identify the “best” possible model but rather to choose a reasonable and understandable starting point. Later you will expand and revise this model to create your final model.

Based on your EDA, select at most 10 predictor variables from “ames_train” and create a linear model for price (or a transformed version of price) using those variables. Provide the R code and the summary output table for your model, a brief justification for the variables you have chosen, and a brief discussion of the model results in context (focused on the variables that appear to be important predictors and how they relate to sales price).

2.2.1.1 Building the Initial Model

Using the results from the previous tests and exercises, I chose to predict log(price) using: log(area),log(Lot.Area),Year.Built,Overall.Qual,Land.Slope,Sale.Condition and Overall.Cond as explanatory variables. The Summary Table is provided below.


lmt<-lm(log(price)~log(area)+log(Lot.Area)+Year.Built+Overall.Qual+Land.Slope+Sale.Condition+Overall.Cond,data=am)  
summary(lmt)
## 
## Call:
## lm(formula = log(price) ~ log(area) + log(Lot.Area) + Year.Built + 
##     Overall.Qual + Land.Slope + Sale.Condition + Overall.Cond, 
##     data = am)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.22149 -0.07744  0.00569  0.07971  0.51061 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           -2.1452887  0.5307581  -4.042 5.72e-05 ***
## log(area)              0.4302531  0.0206191  20.867  < 2e-16 ***
## log(Lot.Area)          0.1321209  0.0103694  12.741  < 2e-16 ***
## Year.Built             0.0044944  0.0002433  18.473  < 2e-16 ***
## Overall.Qual2         -0.0860992  0.1701970  -0.506 0.613056    
## Overall.Qual3          0.1916530  0.1675348   1.144 0.252922    
## Overall.Qual4          0.2204961  0.1625802   1.356 0.175341    
## Overall.Qual5          0.3370413  0.1625063   2.074 0.038340 *  
## Overall.Qual6          0.3950216  0.1636567   2.414 0.015975 *  
## Overall.Qual7          0.4834109  0.1646523   2.936 0.003404 ** 
## Overall.Qual8          0.6645371  0.1652945   4.020 6.26e-05 ***
## Overall.Qual9          0.9000187  0.1670059   5.389 8.89e-08 ***
## Overall.Qual10         0.8496341  0.1735984   4.894 1.15e-06 ***
## Land.SlopeMod          0.1106070  0.0278139   3.977 7.51e-05 ***
## Land.SlopeSev          0.0573191  0.0704731   0.813 0.416218    
## Sale.ConditionAdjLand  0.0257437  0.1091905   0.236 0.813662    
## Sale.ConditionAlloca   0.1035572  0.0786033   1.317 0.187993    
## Sale.ConditionFamily  -0.0468022  0.0421544  -1.110 0.267163    
## Sale.ConditionNormal   0.1028103  0.0205927   4.993 7.06e-07 ***
## Sale.ConditionPartial  0.1652425  0.0275197   6.005 2.71e-09 ***
## Overall.Cond2         -0.0513395  0.1264797  -0.406 0.684898    
## Overall.Cond3          0.1392521  0.0991735   1.404 0.160601    
## Overall.Cond4          0.3429733  0.0933342   3.675 0.000251 ***
## Overall.Cond5          0.4223981  0.0918664   4.598 4.83e-06 ***
## Overall.Cond6          0.4678932  0.0917506   5.100 4.09e-07 ***
## Overall.Cond7          0.5346745  0.0919470   5.815 8.22e-09 ***
## Overall.Cond8          0.5877952  0.0936210   6.278 5.15e-10 ***
## Overall.Cond9          0.5741573  0.1011981   5.674 1.84e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.1514 on 972 degrees of freedom
## Multiple R-squared:  0.8739, Adjusted R-squared:  0.8704 
## F-statistic: 249.4 on 27 and 972 DF,  p-value: < 2.2e-16

2.2.1.2 Model Variable Explanation/Discussion

  • log(area) - Size of house important to price prediction - Coefficient Estimate = ($0.4302531) - log chosen to make square footage less right skewed
  • log(Lot.Area) - Size of lot important to price prediction - - Coefficient Estimate = ($0.1321209) log chosen to make square footage less right skewed
  • Year.Built - Coefficient Estimate = ($0.0044944) House age can be important for many reasons, some like older house and some like newer
  • Overall.Qual - - Coefficient Estimate = ($-0.0860992, 0.191653, 0.2204961, 0.3370413, 0.3950216, 0.4834109, 0.6645371, 0.9000187, 0.8496341) - price is directly dependent on this which can lead to undervalue
  • Land.Slope - Coefficient Estimate = ($0.110607, 0.0573191)- Some like flat lots, other like a hill for water drainage
  • Sale.Condition - Coefficient Estimate = ($0.0257437, 0.1035572, -0.0468022, 0.1028103, 0.1652425)- Emergency situations can reduce selling price
  • Overall.Cond - - Coefficient Estimate = ($-0.0513395, 0.1392521, 0.3429733, 0.4223981, 0.4678932, 0.5346745, 0.5877952, 0.5741573) House Condition can be a major cause of undervalued price

The Adjusted R Squared value is $0.8703772 , which is a good starting point.


2.2.2 Section 2.2 Model Selection

Now either using BAS another stepwise selection procedure choose the “best” model you can, using your initial model as your starting point. Try at least two different model selection methods and compare their results. Do they both arrive at the same model or do they disagree? What do you think this means?


2.2.2.1 Using Bayesian Adaptive Sampling (BAS) and Akaike Information Criterion (AIC)

The Bayesian adaptive sampling algorithm (BAS), samples models without replacement from the space of models. For problems that permit enumeration of all models, BAS is guaranteed to enumerate the model space in 2p iterations where p is the number of potential variables under consideration. For larger problems where sampling is required, we provide conditions under which BAS provides perfect samples without replacement. When the sampling probabilities in the algorithm are the marginal variable inclusion probabilities, BAS may be viewed as sampling models “near” the median probability model of Barbieri and Berger. As marginal inclusion probabilities are not known in advance, we discuss several strategies to estimate adaptively the marginal inclusion probabilities within BAS. We illustrate the performance of the algorithm using simulated and real data and show that BAS can outperform Markov chain Monte Carlo methods.[3]

The BAS model is constructed and analysed. The corrections are implemented and applied to a second model, lmtA. The AIC model is applied to bothe models, lmt and lmtA.

model.bas <- bas.lm(log(price) ~log(area)+log(Lot.Area)+Bedroom.AbvGr+Overall.Qual+Land.Slope+ Sale.Condition+Overall.Cond, data = am, prior = "ZS-null", modelprior=uniform(),initprobs="eplogp")

plot(model.bas, ask=F)

2.2.2.2 BAS Graphical Summaries (4 Plots Shown Above)

  • \(\bf{Residuals}\) \(\bf{and}\) \(\bf{Fitted}\) \(\bf{Values}\) - As rendered under Bayesian Model Averaging. Ideally, of our model assumptions hold, we will not see outliers or non-constant variance.[1]

  • \(\bf{Model}\) \(\bf{Probabilities}\) - the cumulative probability of the models in the order that they are sampled. This plot indicates that the cumulative probability is leveling off as each additional model adds only a small increment to the cumulative probability, which earlier, there are larger jumps corresponding to sampling high probability models.[1]

  • \(\bf{Model}\) \(\bf{Complexity}\) - the dimension of each model (the number of regression coefficients including the intercept) versus the log of the marginal likelihood of the model.[1]

  • \(\bf{Inclusion}\) \(\bf{Probabilities}\) - the marginal posterior inclusion probabilities (pip) for each of the covariates, with marginal pips greater than 0.5 shown in red. The variables with pip > 0.5 correspond to what is known as the median probability model. Variables with high inclusion probabilities are generally important for explaining the data or prediction, but marginal inclusion probabilities may be small if there predictors are correlated, similar to how p-values may be large in the presence of mullticollinearity.[1]

model.bas
## 
## Call:
## bas.lm(formula = log(price) ~ log(area) + log(Lot.Area) + Bedroom.AbvGr +     Overall.Qual + Land.Slope + Sale.Condition + Overall.Cond,     data = am, prior = "ZS-null", modelprior = uniform(), initprobs = "eplogp")
## 
## 
##  Marginal Posterior Inclusion Probabilities: 
##             Intercept              log(area)          log(Lot.Area)  
##               1.00000                1.00000                1.00000  
##         Bedroom.AbvGr          Overall.Qual2          Overall.Qual3  
##               0.99999                0.65996                0.39087  
##         Overall.Qual4          Overall.Qual5          Overall.Qual6  
##               0.66525                0.95781                0.98650  
##         Overall.Qual7          Overall.Qual8          Overall.Qual9  
##               0.99793                0.99991                1.00000  
##        Overall.Qual10          Land.SlopeMod          Land.SlopeSev  
##               0.99996                0.94772                0.05862  
## Sale.ConditionAdjLand   Sale.ConditionAlloca   Sale.ConditionFamily  
##               0.06120                0.19337                0.21024  
##  Sale.ConditionNormal  Sale.ConditionPartial          Overall.Cond2  
##               0.99978                1.00000                0.07655  
##         Overall.Cond3          Overall.Cond4          Overall.Cond5  
##               0.63539                0.99992                0.99999  
##         Overall.Cond6          Overall.Cond7          Overall.Cond8  
##               0.99999                0.99999                0.99999  
##         Overall.Cond9  
##               0.99994

2.2.2.3 Marginal Posterior Inclusion Probabilities (Above)

options(width = 80)
summary(model.bas)
##      Intercept log(area) log(Lot.Area) Bedroom.AbvGr Overall.Qual2
## [1,]         1         1             1             1             0
## [2,]         1         1             1             1             1
## [3,]         1         1             1             1             0
## [4,]         1         1             1             1             1
## [5,]         1         1             1             1             1
##      Overall.Qual3 Overall.Qual4 Overall.Qual5 Overall.Qual6 Overall.Qual7
## [1,]             0             1             1             1             1
## [2,]             0             1             1             1             1
## [3,]             1             1             1             1             1
## [4,]             0             1             1             1             1
## [5,]             0             0             1             1             1
##      Overall.Qual8 Overall.Qual9 Overall.Qual10 Land.SlopeMod Land.SlopeSev
## [1,]             1             1              1             1             0
## [2,]             1             1              1             1             0
## [3,]             1             1              1             1             0
## [4,]             1             1              1             1             0
## [5,]             1             1              1             1             0
##      Sale.ConditionAdjLand Sale.ConditionAlloca Sale.ConditionFamily
## [1,]                     0                    0                    0
## [2,]                     0                    0                    0
## [3,]                     0                    0                    0
## [4,]                     0                    0                    0
## [5,]                     0                    0                    0
##      Sale.ConditionNormal Sale.ConditionPartial Overall.Cond2 Overall.Cond3
## [1,]                    1                     1             0             1
## [2,]                    1                     1             0             1
## [3,]                    1                     1             0             1
## [4,]                    1                     1             0             0
## [5,]                    1                     1             0             0
##      Overall.Cond4 Overall.Cond5 Overall.Cond6 Overall.Cond7 Overall.Cond8
## [1,]             1             1             1             1             1
## [2,]             1             1             1             1             1
## [3,]             1             1             1             1             1
## [4,]             1             1             1             1             1
## [5,]             1             1             1             1             1
##      Overall.Cond9        BF PostProbs     R2 dim  logmarg
## [1,]             1 1.0000000    0.0810 0.8326  21 825.2650
## [2,]             1 0.8763448    0.0710 0.8335  22 825.1330
## [3,]             1 0.7577469    0.0614 0.8335  22 824.9876
## [4,]             1 0.6316691    0.0512 0.8325  21 824.8056
## [5,]             1 0.6020303    0.0488 0.8315  20 824.7576

2.2.2.4 BAS Top 5 Models (in terms of posterior probability)

Listed above with the zero-one indicators for variable inclusion. The other columns in the summary are the Bayes factor of each model to the highest probability model (hence its Bayes factor is 1), the posterior probabilities of the models, the ordinary \(R^2\) of the models, the dimension of the models (number of coefficients including the intercept) and the log marginal likelihood under the selected prior distribution.[1]

image(model.bas, rotate=F)

2.2.2.5 Model Space Visualisation (Above)

This image has rows that correspond to each of the variables and intercept, with labels for the variables on the y-axis. The x-axis corresponds to the possible models. These are sorted by their posterior probability from best at the left to worst at the right with the rank on the top x-axis.

Each column represents one of the 20 models. The variables that are excluded in a model are shown in black for each column, while the variables that are included are colored, with the color related to the log posterior probability. The color of each column is proportional to the log of the posterior probabilities (the lower x-axis) of that model.

Models that are the same color have similar log posterior probabilities which allows us to view models that are clustered together that have marginal likelihoods where the differences are not “worth a bare mention”. This plot indicates that the police expenditure in the two years do not enter the model together, and is an indication of the high correlation between the two variables.[1]

am1<- ames_train %>% filter(Sale.Condition == "Normal"| Sale.Condition == "Partial")
am1<- am1 %>% filter(Overall.Qual!=2| Overall.Qual != 3)
am1<- am1 %>% filter(Overall.Cond!=2)
am1<- am1 %>% filter(Land.Slope!='Sev')

lmtA<-lm(log(price)~log(area)+log(Lot.Area)+Year.Built+Overall.Qual+Land.Slope+Sale.Condition+Overall.Cond,data=am1) 

2.2.2.6 Base Model with BAS Adjustments (lmtA Above)

The base model, lmt, has been adjusted for BAS Model 1 conditions. This will yield a more effective predictive model.

model.AIC <- stepAIC(lmt, k = 2)
## Start:  AIC=-3747.67
## log(price) ~ log(area) + log(Lot.Area) + Year.Built + Overall.Qual + 
##     Land.Slope + Sale.Condition + Overall.Cond
## 
##                  Df Sum of Sq    RSS     AIC
## <none>                        22.289 -3747.7
## - Land.Slope      2    0.3729 22.662 -3735.1
## - Sale.Condition  5    1.1987 23.488 -3705.3
## - log(Lot.Area)   1    3.7227 26.011 -3595.2
## - Overall.Cond    8    4.2762 26.565 -3588.2
## - Year.Built      1    7.8249 30.114 -3448.8
## - log(area)       1    9.9845 32.273 -3379.5
## - Overall.Qual    9   11.4955 33.784 -3349.8

2.2.2.7 AIC Model using Base Explanatory variables

The Akaike information criterion (AIC) is a measure of the relative quality of statistical models for a given set of data. Given a collection of models for the data, AIC estimates the quality of each model, relative to each of the other models. Hence, AIC provides a means for model selection. AIC is founded on information theory: it offers a relative estimate of the information lost when a given model is used to represent the process that generates the data. In doing so, it deals with the trade-off between the goodness of fit of the model and the complexity of the model. AIC does not provide a test of a model in the sense of testing a null hypothesis, so it can tell nothing about the quality of the model in an absolute sense. If all the candidate models fit poorly, AIC will not give any warning of that.[2] The Bayesian information criterion (BIC) or Schwarz criterion (also SBC, SBIC) is a criterion for model selection among a finite set tof models; the model with the lowest BIC is preferred. It is based, in part, on the likelihood function and it is closely related to the Akaike information criterion (AIC).[2]

model.AICA <- stepAIC(lmtA, k = 2)
## Start:  AIC=-3601.75
## log(price) ~ log(area) + log(Lot.Area) + Year.Built + Overall.Qual + 
##     Land.Slope + Sale.Condition + Overall.Cond
## 
##                  Df Sum of Sq    RSS     AIC
## <none>                        16.654 -3601.8
## - Sale.Condition  1    0.1878 16.841 -3593.5
## - Land.Slope      1    0.3438 16.997 -3585.1
## - Overall.Cond    7    3.1691 19.823 -3457.1
## - log(Lot.Area)   1    3.4789 20.132 -3430.9
## - Year.Built      1    6.7889 23.442 -3292.3
## - log(area)       1    8.8289 25.482 -3216.2
## - Overall.Qual    9    9.8018 26.455 -3198.1

2.2.2.8 AIC Model using BAS Adjusted Explanatory variables


2.2.3 Section 2.3 Initial Model Residuals

One way to assess the performance of a model is to examine the model’s residuals. In the space below, create a residual plot for your preferred model from above and use it to assess whether your model appears to fit the data well. Comment on any interesting structure in the residual plot (trend, outliers, etc.) and briefly discuss potential implications it may have for your model and inference / prediction you might produce.


2.2.3.1 Residuals and Errors

In statistics and optimization, errors and residuals are two closely related and easily confused measures of the deviation of an observed value of an element of a statistical sample from its “theoretical value”. The error (or disturbance) of an observed value is the deviation of the observed value from the (unobservable) true value of a quantity of interest (for example, a population mean), and the residual of an observed value is the difference between the observed value and the estimated value of the quantity of interest (for example, a sample mean). The distinction is most important in regression analysis, where the concepts are sometimes called the regression errors and regression residuals and where they lead to the concept of studentized residuals.[4]

plot(lmt$residuals, main="Base Model Residuals vs Collective Index")

plot(lmtA$residuals, main="Base Model with BAS Adjustments Residuals vs Collective Index")

plot(model.AIC$residuals, main='Model AIC Residuals vs Collection Index')

plot(model.AICA$residuals, main='Model AIC with BAS adjustments Residuals vs Collection Index')

2.2.3.2 Analysis of the Residual Plots Above

The difference between the observed value of the dependent variable (y) and the predicted value (y) is called the residual (e). Each data point has one residual.

Residual = Observed value - Predicted value (\(e = y - y\))

Both the sum and the mean of the residuals are equal to zero. That is, \(\sum_{i=1}^{n} e_i\) = 0 and e = 0.

A residual plot is a graph that shows the residuals on the vertical axis and the independent variable on the horizontal axis. If the points in a residual plot are randomly dispersed around the horizontal axis, a linear regression model is appropriate for the data; otherwise, a non-linear model is more appropriate.[5]

The points of interest for the residuals is that all four plots appear to be uniformly distributed and the number of \(\bf {outliers}\) is substantially reduced by using the BAS for both the Base and the AIC models.


2.2.4 Section 2.4 Initial Model RMSE

You can calculate it directly based on the model output. Be specific about the units of your RMSE (depending on whether you transformed your response variable). The value you report will be more meaningful if it is in the original units (dollars).


In statistics, the mean squared error (MSE) or mean squared deviation (MSD) of an estimator (of a procedure for estimating an unobserved quantity) measures the average of the squares of the errors or deviations-that is, the difference between the estimator and what is estimated. MSE is a risk function, corresponding to the expected value of the squared error loss or quadratic loss. The difference occurs because of randomness or because the estimator doesn’t account for information that could produce a more accurate estimate.[7]

The MSE is a measure of the quality of an estimator-it is always non-negative, and values closer to zero are better. The MSE is the second moment (about the origin) of the error, and thus incorporates both the variance of the estimator and its bias. For an unbiased estimator, the MSE is the variance of the estimator. Like the variance, MSE has the same units of measurement as the square of the quantity being estimated. In an analogy to standard deviation, taking the square root of MSE yields the root-mean-square error or root-mean-square deviation (RMSE or RMSD), which has the same units as the quantity being estimated; for an unbiased estimator, the RMSE is the square root of the variance, known as the standard deviation.[6]

## [1] "   31817 US Dollars"

2.2.4.1 RMSE Value for Base Training Model (Above)

sprintf("%8.0f US Dollars",rmse.fullAloneA)
## [1] "   31350 US Dollars"

2.2.4.2 RMSE Value for Base Training Model with BAS Adjustment (Above)

sprintf("%8.0f US Dollars",rmse.AICAlone)
## [1] "   31817 US Dollars"

2.2.4.3 RMSE Value for AIC Training Model (Above)

sprintf("%8.0f US Dollars",rmse.AICAloneA)
## [1] "   31350 US Dollars"

2.2.4.4 RMSE Value for AIC Training Model with BAS Adjustment (Above)

2.2.4.5 Analysis of the RMSE Above

It is obvios that applying the BAS adjustments to both the Base and AIC model lowers the RMSE (much lower than the 100,000 dollar limit). Since there is nod difference between RMSE results for the Base and AIC model, the AIC model will be no longer deployed.


2.2.5 Section 2.5 Overfitting

The process of building a model generally involves starting with an initial model (as you have done above), identifying its shortcomings, and adapting the model accordingly. This process may be repeated several times until the model fits the data reasonably well. However, the model may do well on training data but perform poorly out-of-sample (meaning, on a dataset other than the original training data) because the model is overly-tuned to specifically fit the training data. This is called “overfitting.” To determine whether overfitting is occurring on a model, compare the performance of a model on both in-sample and out-of-sample data sets. To look at performance of your initial model on out-of-sample data, you will use the data set ames_test.

library(dplyr)
load("ames_test.Rdata")
ames_test$Overall.Qual<-as.factor(ames_test$Overall.Qual)
ames_test$Overall.Cond<-as.factor(ames_test$Overall.Cond)
at<-ames_test

at1<- at %>% filter(Sale.Condition == "Normal"| Sale.Condition == "Partial")
at1<- at1 %>% filter(Overall.Qual!=2| Overall.Qual != 3)
at1<- at1 %>% filter(Overall.Cond!=2)
at1<- at1 %>% filter(Land.Slope!='Sev')


############## TO BE USED IN LATER SECTIONS ############################

tLSet<-dplyr::select(ames_test,price,Overall.Qual,Lot.Area,
Year.Built,Sale.Condition,area,MS.Zoning,Year.Remod.Add,Land.Slope,
Exter.Qual,Lot.Shape,Land.Contour,Lot.Config,Street,
Bsmt.Qual,Bsmt.Cond,Bsmt.Exposure,BsmtFin.Type.1,Bldg.Type,
BsmtFin.SF.1,BsmtFin.Type.2,BsmtFin.SF.2,Bsmt.Unf.SF,
Total.Bsmt.SF,Heating.QC,Central.Air,House.Style,
Electrical,X1st.Flr.SF,X2nd.Flr.SF,
Bsmt.Full.Bath,Bsmt.Half.Bath,Full.Bath,Half.Bath,
Bedroom.AbvGr,Kitchen.AbvGr,TotRms.AbvGrd,
Functional,Fireplaces,
Garage.Yr.Blt,Garage.Finish,Garage.Cars,Garage.Area,
Paved.Drive,Wood.Deck.SF,
Open.Porch.SF,Enclosed.Porch,X3Ssn.Porch,Screen.Porch,
Fence,Misc.Val,Mo.Sold,Yr.Sold,Sale.Type)

tLSet<-data.frame(tLSet)
tLSet$logarea<-log(tLSet$area+1)
tLSet$logLot.Area<-log(tLSet$Lot.Area+1)
tLSet$logGarage.Area<-log(tLSet$Garage.Area+1)
tLSet$logX2nd.Flr.SF<-log(tLSet$X2nd.Flr.SF+1)
tLSet$logBsmtFin.SF.1<-log(tLSet$BsmtFin.SF.1+1)
tLSet$logBsmtFin.SF.2<-log(tLSet$BsmtFin.SF.2+1)
tLSet$logBsmt.Unf.SF<-log(tLSet$Bsmt.Unf.SF+1)
tLSet$logTotal.Bsmt.SF<-log(tLSet$Total.Bsmt.SF+1)
tLSet$logWood.Deck.SF<-log(tLSet$Wood.Deck.SF+1)
tLSet$logOpen.Porch.SF<-log(tLSet$Open.Porch.SF+1)
tLSet$logX1st.Flr.SF<-log(tLSet$X1st.Flr.SF+1)

 tLSet<-tLSet[-c(3,6,20,22,23,24,29,30,43,45,46)]


atLSet<-dplyr::select(tLSet,1,2,44,3,45,48,4,19,5,6,31,54,16,39,30,34,18,29,14,28,13)

atSet1<-dplyr::select(ames_test,price,Overall.Qual,Neighborhood,area,BsmtFin.SF.1, 
Overall.Cond,Garage.Yr.Blt,Bldg.Type,Total.Bsmt.SF,Year.Built,
Land.Slope,Sale.Condition,Central.Air,Lot.Shape,Kitchen.Qual,
Garage.Cars,Fireplaces,Year.Remod.Add,MS.Zoning)

amLSet<-ames_train
amLSet<-data.frame(amLSet)
amLSet$logarea<-log(amLSet$area+1)
amLSet$logLot.Area<-log(amLSet$Lot.Area+1)
amLSet$logX2nd.Flr.SF<-log(amLSet$X2nd.Flr.SF+1)
amLSet$logBsmtFin.SF.1<-log(amLSet$BsmtFin.SF.1+1)
 


# Extract Predictions
predict.full <- exp(predict(lmt, ames_test))
predict.fullA <- exp(predict(lmtA, at1))

# Extract Residuals
resid.full <- ames_test$price - predict.full
resid.fullA <- at1$price - predict.fullA

# Calculate RMSE
rmse.full <- sqrt(mean(resid.full^2))
rmse.fullA <- sqrt(mean(resid.fullA^2))
plot(resid.full, main="Base Model Residuals for Test Data")

plot(resid.fullA, main="Base Model Residuals w/BAS for Test Data")

2.2.5.1 Test Data Residuals (Above)

print('RMSE Value for Base Training Model on Test Data');sprintf("%8.0f US Dollars",rmse.full)
## [1] "RMSE Value for Base Training Model on Test Data"
## [1] "   27330 US Dollars"
print('RMSE Value for Base Training Model w/BAS Adjustment on Test Data');sprintf("%8.0f US Dollars",rmse.fullA)
## [1] "RMSE Value for Base Training Model w/BAS Adjustment on Test Data"
## [1] "   27232 US Dollars"

2.2.5.2 Test Data RMSE (Above)

Use your model from above to generate predictions for the housing prices in the test data set. Are the predictions significantly more accurate (compared to the actual sales prices) for the training data than the test data? Why or why not? Briefly explain how you determined that (what steps or processes did you use)?


NOTE: Write your written response to section 2.5 here. Delete this note before you submit your work.

plmt<-predict(lmt,ames_test,interval='predict')
pplmt<-predict(lmt,ames_train,interval='predict')
plmt<-data.frame(plmt)
pplmt<-data.frame(pplmt)
plmtA<-predict(lmtA,at1,interval='predict')
plmtA<-data.frame(plmtA)
pplmtA<-predict(lmtA,am1,interval='predict')
pplmtA<-data.frame(pplmtA)



pr01<- ggplot(ames_train, aes(ames_train$price/1000, log(ames_train$price)))+
 geom_point()+
 
 geom_line(data=pplmt, aes(y=fit),colour='blue')+
 geom_ribbon(data=pplmt,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="red")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. IV  Training Data:  Predicted Natural Log of Price using Base Model ')
    


pr1<- ggplot(ames_test, aes(ames_test$price/1000, log(ames_test$price)))+
 geom_point()+
 
 geom_line(data=plmt, aes(y=fit),colour='red')+
 geom_ribbon(data=plmt,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="blue")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. V  Test Data:  Predicted Natural Log of Price using Base Model ')
    
pr03<- ggplot(am1, aes(am1$price/1000, log(am1$price)))+
 geom_point()+
 
 geom_line(data=pplmtA, aes(y=fit),colour='blue')+
 geom_ribbon(data=pplmtA,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="red")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. VI  Training Data: Predicted Natural Log of Price using Base w/BAS Adjustment Model ')

pr3<- ggplot(at1, aes(at1$price/1000, log(at1$price)))+
 geom_point()+
 
 geom_line(data=plmtA, aes(y=fit),colour='red')+
 geom_ribbon(data=plmtA,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="blue")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. VII Test Data:  Predicted Natural Log of Price using Base w/BAS Adjustment Mode ')

2.2.5.3 Prediction Intvervals

In statistical inference, specifically predictive inference, a prediction interval is an estimate of an interval in which future observations will fall, with a certain probability, given what has already been observed. Prediction intervals are often used in regression analysis. Prediction intervals are used in both frequentist statistics and Bayesian statistics: a prediction interval bears the same relationship to a future observation that a frequentist confidence interval or Bayesian credible interval bears to an unobservable population parameter: prediction intervals predict the distribution of individual future points, whereas confidence intervals and credible intervals of parameters predict the distribution of estimates of the true population mean or other quantity of interest that cannot be observed.[8]

plot(pr01)

plot(pr1) 

2.2.5.4 Base Model 95 percent prediction interval for Training and Test data (above)

In Fig. IV Training Data: Predicted Natural Log of Price using Base Model, a 95% confidence interval is provided for the Training Data. The characteristics of the graph are as follows:

  • The black plotted points represents the Natural Log of the price as a function of price, for the Training Data. in other words \(P = log(price)\)
  • The blue jagged line represents the predicted price from the model, using the Training Data.
  • The pink region bounded by black borders is 95% prediction interval, for the Traing Data.

In Fig. V Test Data: Predicted Natural Log of Price using Base Model, a 95% confidence interval is provided for the Test Data. The characteristics of the graph are as follows:

  • The black plotted points represents the Natural Log of the price as a function of price. in other words \(P= log(price)\)
  • The red jagged line represents the predicted price from the model, using the Test Data.
  • The light blue region bounded by black borders is 95% prediction interval, for the Test Data.
plot(pr03)

plot(pr3)

2.2.5.5 Base Model w/BAS 95 percent prediction interval for Training and Test data (above)

Fig. VI Training Data: Predicted Natural Log of Price using Base w/BAS Adjustment Model and Fig. VII Test Data: Predicted Natural Log of Price using Base w/BAS Adjustment Mode, are similar to Figs. VI-V, with the exception that both the Training Data and the Test Data have been adjusted for BAS modeling.

Through the remainder of this report the Training Data, Test Data and the Validation Data will be presented with 95% prediction intervals that have the same characteristics as Figs. IV-VII above.

2.2.5.6 Summary of Overfitting Analysis

Although the RMSE is, in general, smaller for the Test Data than it is for the Training Data, other observations indicate there is overfitting inherent in the models.

An examination of the prediction intervals indicate that the models are overfitted. The width of the Training Data interval ribbon (pink) is smaller than that of the Test Data interval ribbon (blue).


Note to the learner: If in real-life practice this out-of-sample analysis shows evidence that the training data fits your model a lot better than the test data, it is probably a good idea to go back and revise the model (usually by simplifying the model) to reduce this overfitting. For simplicity, we do not ask you to do this on the assignment, however.

2.3 Part 3 Development of a Final Model

Now that you have developed an initial model to use as a baseline, create a final model with at most 20 variables to predict housing prices in Ames, IA, selecting from the full array of variables in the dataset and using any of the tools that we introduced in this specialization.

Carefully document the process that you used to come up with your final model, so that you can answer the questions below.

2.3.1 Section 3.1 Final Model

Provide the summary table for your model.


lmt2<-lm(log(price)~.,data=amSet2)
summary(lmt2)
## 
## Call:
## lm(formula = log(price) ~ ., data = amSet2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.94926 -0.05776  0.00000  0.05984  0.70644 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)            0.4093426  0.8433774   0.485 0.627542    
## Overall.Qual3          0.2413662  0.0735454   3.282 0.001072 ** 
## Overall.Qual4          0.2361168  0.0553481   4.266 2.21e-05 ***
## Overall.Qual5          0.2975756  0.0552434   5.387 9.24e-08 ***
## Overall.Qual6          0.3387620  0.0561994   6.028 2.45e-09 ***
## Overall.Qual7          0.3842385  0.0573111   6.704 3.63e-11 ***
## Overall.Qual8          0.4684324  0.0592602   7.905 8.10e-15 ***
## Overall.Qual9          0.6070963  0.0636849   9.533  < 2e-16 ***
## Overall.Qual10         0.5084214  0.0748270   6.795 2.01e-11 ***
## NeighborhoodBlueste   -0.0101583  0.0829924  -0.122 0.902610    
## NeighborhoodBrDale    -0.0486502  0.0631804  -0.770 0.441497    
## NeighborhoodBrkSide    0.0144927  0.0528052   0.274 0.783800    
## NeighborhoodClearCr    0.0170327  0.0565497   0.301 0.763335    
## NeighborhoodCollgCr   -0.0483617  0.0419806  -1.152 0.249637    
## NeighborhoodCrawfor    0.1067629  0.0488828   2.184 0.029224 *  
## NeighborhoodEdwards   -0.0895386  0.0451598  -1.983 0.047714 *  
## NeighborhoodGilbert   -0.0557172  0.0443872  -1.255 0.209723    
## NeighborhoodGreens     0.0908631  0.0719725   1.262 0.207118    
## NeighborhoodGrnHill    0.4659321  0.0939963   4.957 8.61e-07 ***
## NeighborhoodIDOTRR    -0.0224757  0.0595765  -0.377 0.706074    
## NeighborhoodMeadowV   -0.0640907  0.0605857  -1.058 0.290416    
## NeighborhoodMitchel   -0.0414130  0.0456429  -0.907 0.364485    
## NeighborhoodNAmes     -0.0565996  0.0439313  -1.288 0.197960    
## NeighborhoodNoRidge    0.0189062  0.0468603   0.403 0.686709    
## NeighborhoodNPkVill   -0.0125109  0.0727264  -0.172 0.863456    
## NeighborhoodNridgHt    0.0537581  0.0426906   1.259 0.208278    
## NeighborhoodNWAmes    -0.0816746  0.0456361  -1.790 0.073851 .  
## NeighborhoodOldTown   -0.0243807  0.0538092  -0.453 0.650594    
## NeighborhoodSawyer    -0.0577363  0.0455006  -1.269 0.204812    
## NeighborhoodSawyerW   -0.0859561  0.0437971  -1.963 0.050011 .  
## NeighborhoodSomerst    0.0239373  0.0483926   0.495 0.620974    
## NeighborhoodStoneBr    0.1402145  0.0477321   2.938 0.003396 ** 
## NeighborhoodSWISU      0.0441471  0.0596902   0.740 0.459740    
## NeighborhoodTimber    -0.0332594  0.0488457  -0.681 0.496111    
## NeighborhoodVeenker   -0.0384263  0.0556731  -0.690 0.490245    
## logarea                0.4828078  0.0255767  18.877  < 2e-16 ***
## Overall.Cond2         -0.4556562  0.1195799  -3.810 0.000148 ***
## Overall.Cond3          0.0935078  0.0963635   0.970 0.332134    
## Overall.Cond4          0.3234968  0.0899068   3.598 0.000339 ***
## Overall.Cond5          0.3810298  0.0887022   4.296 1.94e-05 ***
## Overall.Cond6          0.4164271  0.0889175   4.683 3.27e-06 ***
## Overall.Cond7          0.4637333  0.0893287   5.191 2.60e-07 ***
## Overall.Cond8          0.5160493  0.0902970   5.715 1.51e-08 ***
## Overall.Cond9          0.5063729  0.0991142   5.109 3.98e-07 ***
## Year.Built             0.0032384  0.0003906   8.291 4.24e-16 ***
## logLot.Area            0.0536255  0.0140169   3.826 0.000140 ***
## Bsmt.Full.Bath         0.0552444  0.0098413   5.614 2.67e-08 ***
## Garage.TypeAttchd      0.0903717  0.0404740   2.233 0.025813 *  
## Garage.TypeBasment     0.0711752  0.0543982   1.308 0.191079    
## Garage.TypeBuiltIn     0.0437027  0.0440806   0.991 0.321752    
## Garage.TypeCarPort     0.1380744  0.1243464   1.110 0.267133    
## Garage.TypeDetchd      0.0814603  0.0409791   1.988 0.047141 *  
## Sale.ConditionAlloca   0.0687086  0.0872469   0.788 0.431192    
## Sale.ConditionFamily  -0.0431031  0.0338258  -1.274 0.202908    
## Sale.ConditionNormal   0.0612006  0.0175302   3.491 0.000505 ***
## Sale.ConditionPartial  0.1061395  0.0233165   4.552 6.07e-06 ***
## logX2nd.Flr.SF        -0.0097551  0.0019462  -5.012 6.51e-07 ***
## Bldg.Type2fmCon       -0.0145113  0.0332368  -0.437 0.662507    
## Bldg.TypeDuplex       -0.1114858  0.0273217  -4.080 4.91e-05 ***
## Bldg.TypeTwnhs        -0.0832951  0.0326159  -2.554 0.010824 *  
## Bldg.TypeTwnhsE       -0.0652101  0.0208212  -3.132 0.001795 ** 
## Heating.QCFa          -0.1013832  0.0322409  -3.145 0.001720 ** 
## Heating.QCGd          -0.0121925  0.0123505  -0.987 0.323817    
## Heating.QCPo          -0.0753739  0.1237244  -0.609 0.542546    
## Heating.QCTA          -0.0383967  0.0118180  -3.249 0.001202 ** 
## logBsmtFin.SF.1        0.0079189  0.0018092   4.377 1.35e-05 ***
## Garage.Cars            0.0460759  0.0093889   4.907 1.10e-06 ***
## MS.ZoningFV            0.2356943  0.0659649   3.573 0.000372 ***
## MS.ZoningI (all)       0.3520327  0.1569748   2.243 0.025173 *  
## MS.ZoningRH            0.2134236  0.0751650   2.839 0.004625 ** 
## MS.ZoningRL            0.2424180  0.0574667   4.218 2.72e-05 ***
## MS.ZoningRM            0.2060368  0.0536963   3.837 0.000133 ***
## Kitchen.QualFa        -0.1183259  0.0417538  -2.834 0.004705 ** 
## Kitchen.QualGd        -0.0664175  0.0217866  -3.049 0.002369 ** 
## Kitchen.QualPo         0.2710723  0.1318450   2.056 0.040081 *  
## Kitchen.QualTA        -0.1027327  0.0240710  -4.268 2.19e-05 ***
## HeatingGasW            0.2196726  0.0496209   4.427 1.08e-05 ***
## HeatingGrav            0.1000076  0.1246115   0.803 0.422451    
## HeatingWall            0.2051034  0.1378680   1.488 0.137197    
## Central.AirY           0.1151093  0.0267394   4.305 1.86e-05 ***
## Fireplaces             0.0285111  0.0076769   3.714 0.000217 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.1156 on 871 degrees of freedom
##   (48 observations deleted due to missingness)
## Multiple R-squared:  0.9261, Adjusted R-squared:  0.9193 
## F-statistic: 136.5 on 80 and 871 DF,  p-value: < 2.2e-16

2.3.2 Section 3.2 Transformation

Did you decide to transform any variables? Why or why not? Explain in a few sentences.


2.3.2.1 Training Data Transformations

The only data transfromations that were rendered was a conversion of area, in square units, to natural log of area. The independent predictor variables that were transformed are provided in the code below.

The transformation came as a consequence of observing the area,in units squared, being right skewed on a histogram plots.

The response variable, price, was also rendered using the natural log function.

amLSet<-ames_train
amLSet<-data.frame(amLSet)
amLSet$logarea<-log(amLSet$area+1)
amLSet$logLot.Area<-log(amLSet$Lot.Area+1)
amLSet$logX2nd.Flr.SF<-log(amLSet$X2nd.Flr.SF+1)
amLSet$logBsmtFin.SF.1<-log(amLSet$BsmtFin.SF.1+1)

amSet2<-dplyr::select(amLSet,price,Overall.Qual,Neighborhood,logarea,       
Overall.Cond,Year.Built,logLot.Area,Bsmt.Full.Bath,
Garage.Type,Sale.Condition,logX2nd.Flr.SF,Bldg.Type,     
Heating.QC,logBsmtFin.SF.1,Garage.Cars,MS.Zoning,   
Kitchen.Qual,Heating,Central.Air,   
Fireplaces)

2.3.3 Section 3.3 Variable Interaction

Did you decide to include any variable interactions? Why or why not? Explain in a few sentences.


2.3.3.1 Colinearity of Data

The variables that contribute the most to the final Adjusted \(R^2\)are chosen from their F-Statistic value determined by an anova model analysis. The colinearity between these variables is investigated and it was determined that no such relationship exists.

pairs(~Overall.Qual+logarea+Year.Built+logLot.Area+Bsmt.Full.Bath+Neighborhood+logX2nd.Flr.SF,
      data=ames, 
   main="Colinearity Check")

2.3.3.2 Nearly Normal Residuals with zero mean

par(mfrow=c(1,2))
hist(lmf2$residuals)
qqnorm(lmf2$residuals)
qqline(lmf2$residuals)

par(mfrow=c(1,1))

2.3.4 Section 3.4 Variable Selection

2.3.4.1 Forward Selection - Adjusted R Squared with BAS Adjustments

The forward-selection technique begins with no variables in the model. For each of the independent variables, the Forward method calculates statistics that reflect the variable’s contribution to the model if it is included. The variable with the highest Adjusted \(R^2\) value is chosen and added to the set. The FORWARD method then calculates statistics again for the variables still remaining outside the model, and the evaluation process is repeated. Thus, variables are added one by one to the model until no remaining variable produces a significant statistic. Once a variable is in the model, it stays.

print('Table I  Model Selection Results Derived from Adjusted R Squared');sumStat
## [1] "Table I  Model Selection Results Derived from Adjusted R Squared"
##                 R.Squared Adj.R.Squared
## Overall.Qual    0.6953192     0.6925494
## Neighborhood    0.7779075     0.7698440
## logarea         0.8376505     0.8315814
## Overall.Cond    0.8606549     0.8542348
## Year.Built      0.8743366     0.8684091
## logLot.Area     0.8863358     0.8808493
## Bsmt.Full.Bath  0.8966699     0.8915631
## Garage.Type     0.9020662     0.8965227
## Sale.Condition  0.9056622     0.8998779
## logX2nd.Flr.SF  0.9084827     0.9027629
## Bldg.Type       0.9119799     0.9060592
## Heating.QC      0.9144920     0.9083293
## logBsmtFin.SF.1 0.9163570     0.9102276
## Garage.Cars     0.9181562     0.9120526
## MS.Zoning       0.9204967     0.9140822
## Kitchen.Qual    0.9222495     0.9155927
## Fireplaces      0.9233643     0.9167079
## Heating         0.9245588     0.9177242
## Central.Air     0.9261305     0.9193457

2.3.4.2 Model Selection Results (Above)

The model selection process proceeded with adding each varable to the model, in the order listed. At the end of each additive iteration both \(R^2\) and the Adjusted \(R^2\) where recorded. Upon completion, the values for the last entry reflect the overall model statistics for both \(R^2\) and the Adjusted \(R^2\) .

Once this process was completed a \(\bf {BAS}\) model was produced and the results of the Top model were applied to the model



2.3.5 Section 3.5 Model Testing

How did testing the model on out-of-sample data affect whether or how you changed your model? Explain in a few sentences.


2.3.5.1 Test Data RMSE

sprintf("%8.0f US Dollars",rmse.full)
## [1] "   17997 US Dollars"

2.3.5.2 Test Data Residuals

plot(resid.full, main="Residuals for Test Data")

2.3.5.3 Test Data 95 Per Cent Prediction Intervals

plot(tr3)
## Warning: Removed 1 rows containing missing values (geom_path).

2.3.5.4 Test Data Per Centage of Houses witin the Prediction Interval

sprintf("%7.0f Per Cent",round(100-(100*length(grep('TRUE',is.na(plmt$fit)))/length(plmt$fit)),2))
## [1] "     97 Per Cent"

2.3.5.5 Out of Sample Data Testing Summary

The ames_test, out of sample, data was analysized using the training model. The results are summarized by the following:

  1. RMSE is 18000 US Dollars which is about 500 dollars larger than the training data

  2. The residuals contain about 20 houses having prices such that: abs(residual) > 50,000 US dollars, indicating outliers.

  3. The 95% prediction interval ribbons are wider than those for the training data.

  4. 97% of the house prices are within the 95% prediction interval


2.4 Part 4 Final Model Assessment

2.4.1 Section 4.1 Final Model Residual

lmf2<-lm(log(price)~.,data=ames)
#summary(lmf2)

#summary(lmf2)$adj.r.square
plmf2<-predict(lmf2,ate,interval='predict')
plmf2<-data.frame(plmf2)
pplmf2<-predict(lmf2,ames,interval='predict')
pplmf2<-data.frame(pplmf2)

# Extract Predictions
predict.lmf2 <- exp(predict(lmf2, ames))
# Extract Residuals
resid.lmf2 <- ames$price - predict.lmf2
# Calculate RMSE
r2<-resid.lmf2
plot(r2, main='Final Model Residuals') 

For your final model, create and briefly interpret an informative plot of the residuals.


2.4.1.1 Final Model Residual Analysis

The final model residuals appear to be normally ditributed and contain about 10 outlier priced houses having prices such that: abs(residual) > 50,000 US dollars. This means that the residual outlier values either fell below -$50,000 or above +$50,000.


2.4.2 Section 4.2 Final Model RMSE

resid.lmf2<-data.frame(resid.lmf2)
resid.lmf2<-as.data.frame(lapply(resid.lmf2, na.omit))
rmse.lmf2<- sqrt(mean(resid.lmf2^2))

sprintf("%8.0f US Dollars",rmse.lmf2)
## [1] "   17530 US Dollars"

For your final model, calculate and briefly comment on the RMSE.

2.4.2.1 Final Model RMSE Analysis

The final model RMSE value is 17530 US Dollars which is a slightly larger than half of the original model value of 31350 US Dollars. This result is very pleasing.



2.4.3 Section 4.3 Final Model Evaluation

2.4.3.1 Final Model 95 Per Cent Prediction Intervals

pr00<- ggplot(ames, aes(ames$price/1000, log(ames$price)))+
 geom_point()+
 
 geom_line(data=pplmf2, aes(y=fit),colour='blue')+
 geom_ribbon(data=pplmf2,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="red")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. X Plot Training Data - Final Model - Predicted Natural Log of Price ')

plot(pr00);

sprintf("%7.0f Per Cent of the house prices are witin prediction interval",
        round(100-(100*length(grep('TRUE',is.na(plmf2$fit)))/length(plmf2$fit)),2))
## [1] "     97 Per Cent of the house prices are witin prediction interval"

What are some strengths and weaknesses of your model?

2.4.3.2 Final Model Strengths and Weaknesses Analysis

  • \(\bf Strengths\) - 95 % Prediction intervals are narrow - Very Few Outliers - Much smaller RMSE. This gives rise to a very strong model to validate other data.

  • \(\bf Weaknesses\) - Some of the data points were lost due to BAS filtering. Other weaknesses may come about from outliers witin the data and overall small size of the data samples.



2.4.4 Section 4.4 Final Model Validation

Testing your final model on a separate, validation data set is a great way to determine how your model will perform in real-life practice.

You will use the ames_validation dataset to do some additional assessment of your final model. Discuss your findings, be sure to mention:

  • What is the RMSE of your final model when applied to the validation data?

  • How does this value compare to that of the training data and/or testing data?

  • What percentage of the 95% predictive confidence (or credible) intervals contain the true price of the house in the validation data set?

  • From this result, does your final model properly reflect uncertainty?

load("ames_validation.Rdata")
#nrow(ames_validation)
aves<-ames
ames_validation$Overall.Qual<-as.factor(ames_validation$Overall.Qual)
ames_validation$Overall.Cond<-as.factor(ames_validation$Overall.Cond)
av<-ames_validation
plmfF<-predict(lmf2,ave,interval='predict')
plmfF<-data.frame(plmfF)
pplmfF<-predict(lmf2,aves,interval='predict')
pplmfF<-data.frame(pplmfF)

# Extract Predictions
predict.lmf2 <- exp(predict(lmf2, ave))
# Extract Residuals
resid.lmf2 <- ave$price - predict.lmf2
# Calculave RMSE
p2<-predict.lmf2
r2<-resid.lmf2

#round(100-(100*length(grep('TRUE',is.na(pplmf2$fit)))/length(ames_validation)),2)
resid.lmf2<-data.frame(resid.lmf2)
resid.lmf2<-as.data.frame(lapply(resid.lmf2, na.omit))
rmse.lmf3<- sqrt(mean(resid.lmf2^2))

pr001<- ggplot(ave, aes(ave$price/1000, log(ave$price)))+
 geom_point()+
 geom_line(data=plmfF, aes(y=fit),colour='red')+
 geom_ribbon(data=plmfF,aes(ymin=lwr,ymax=upr),alpha=0.1,colour='black',fill="blue")+
ylab("Natural Log Price")+
    scale_x_discrete(name ="Price (in $1000)"  ,
                limits=c(0,100,200,300,400,500,600)) +
    ggtitle('Fig. XI Plot Validation Data for Predicted Natural Log of Price ')

pcwi<-round(100-(100*length(grep('TRUE',is.na(pplmf2$fit)))/length(pplmf2$fit)),2)

2.4.4.1 Validation Data Residuals

The final model validation residuals contain about 12 outlier priced houses having prices such that: abs(residual) > 50,000 US dollars. This means that the residual outlier values either fell below -$50,000 or above +$50,000.

plot(r2, main='Validation Residuals ')

2.4.4.2 Validation Data RMSE

A comparison of the Validation, Test and Training RMSE values is provided below:

  • Validation Data RMSE is 17962 US Dollars
  • Test Data RMSE is US Dollars 17996 US Dollars
  • Training Data RMSE is 17530 US Dollars

The Validation Data RMSE is greater than Training Data RMSE, but, however, is less than the Test Data RMSE.

2.4.4.3 Validation Data Evaluation

\(\bf Validation\) \(\bf Data\) \(\bf 95\) \(\bf Per\) \(\bf Cent\) \(\bf Prediction\) \(\bf Interval\)

plot(pr001)
## Warning: Removed 1 rows containing missing values (geom_path).

\(\bf 95.68\) \(\bf Per\) \(\bf Cent\) \(\bf of\) \(\bf the\) \(\bf 95\) \(\bf Per\) \(\bf Cent\) \(\bf predictive\) \(\bf confidence\) \(\bf (or\) \(\bf credible)\) \(\bf intervals\) \(\bf contain\) \(\bf the\) \(\bf true\) \(\bf price\) \(\bf of\) \(\bf the\) \(\bf house\) \(\bf in\) \(\bf the\) \(\bf validation\) \(\bf data\) \(\bf set.\)

The model uncertainty appears to be minimized upon examination of the test data results in \(\bf section\) \(\bf {2.3.5.5}\) Out of Sample Data Testing Summary, listed above.


ovun<-ave
ovun$Resid<-r2
ovun$Predict<-p2
ovun<-data.frame(ovun)
ovun<-filter(ovun,Resid!='NA')
ovun<-filter(ovun,Predict!='NA')
ov<-filter(ovun,Resid>mean(ovun$Resid))
un<-filter(ovun,Resid<mean(ovun$Resid))
upredM<-mean(un$Predict)
upricM<-mean(un$price)
opredM<-mean(ov$Predict)
opricM<-mean(ov$price)
usd<-sd(un$Resid)
usd<- abs(usd)
umn<-mean(un$Resid)
un$Lim<-un$price+2*usd
osd<-sd(ov$Resid)
omn<-mean(ov$Resid)
ov$Lim<-ov$price-2*osd

p1<-ggplot(aes(x = log(Predict) ) , data = un) + 
geom_histogram(aes(fill=(log(Predict)>=log(price + 2*usd)) )) +
stat_bin( geom="text", aes(label=..count..) ,vjust = 0,hjust=0) +   
xlab('Natural log of Price (in US Dollars)')+
#geom_vline(data=un,xintercept=median(log(un$price)), color="red")+
geom_vline(data=un,xintercept=mean(log(un$price)), color="blue")+
#geom_vline(data=un,xintercept=median(log(un$Predict)), color="green")+
geom_vline(data=un,xintercept=mean(log(un$Predict)), color="yellow")+

 ggtitle("Fig XII. Log of Price Distribution of Undervalued Real Estate for Ames Iowa")

2.4.4.4 Validation Data Undervalued Houses: Residual Analysis

The histogram depicted in Fig. XII, below, can be summarized by the following

  1. The natural log of the houses having predicted prices residuals above the mean ($-9872), (red and blue regions)

  2. The blue regions represent all houses having predicted price residuals two standard deviations $19139 above the mean

  3. The yellow line is the mean value of the predicted price values $175820 - log(12.0772173)

  4. The blue line is the mean value of the actual price values $165947 - log(12.0194273

suppressMessages(print(p1))

The hosue prices falling into the blue-shaded region of the histogram, above, are boxplotted by Neighborhood and depicted in Fig.XIII, below. Each boxplot represents Neighborhood as a function of actual selling price. The symbols used in each boxplot are consistent with the description provided for Fig.II in section 2 above.

suppressWarnings(print(sdPlot))

The List below represents the top 15 undervalued houses that were identified by the model in the ames validation data.

  1. The \(\bf Neighborhood\) column is which of the 20 Neighborhoods where the house is located
  2. The \(\bf price\) column is the actual sale price in $US
  3. The \(\bf Predict\) column is the price, $US, predicted by the model
  4. The \(\bf Diff\) column is the difference in the predicted and actual price in $US. This column is a measuse of the \(\bf Undervaluedness\) for the house.
head(UU,15)
##    index Neighborhood  price  Predict     Diff
## 8     35      NridgHt 275000 330945.5 55945.49
## 2      5      CollgCr 239000 294815.6 55815.57
## 16    81      Veenker 275000 325565.6 50565.55
## 33   197      NoRidge 190000 238458.3 48458.31
## 28   165        SWISU 115000 151970.6 36970.64
## 26   148      Crawfor 158000 194102.7 36102.68
## 9     41      Crawfor 170000 204392.7 34392.74
## 20   110      NridgHt 266000 300371.2 34371.23
## 43   287      NridgHt 274900 308988.3 34088.34
## 39   254      CollgCr 211000 245087.1 34087.12
## 7     22      NridgHt 232698 265732.0 33034.01
## 27   154      NridgHt 280000 312534.7 32534.67
## 30   171       Timber 160000 192244.0 32244.04
## 50   343        NAmes 120000 151362.1 31362.11
## 17    87      NoRidge 260000 291256.2 31256.15

2.4.4.5 Validation Data Overvalued Houses: Residual Analysis

The histogram depicted in Fig. XIV, below, can be summarized by the following

  1. The natural log of the houses having predicted prices residuals below the mean ($15194), (red and blue regions)

  2. The blue regions represent all houses having predicted price residuals two standard deviations$31463 below the mean.

  3. The yellow line is the mean value of the predicted price values $175853 - log(12.0774048)

  4. The blue line is the mean value of the actual price values $191047 - log(12.1602795

suppressMessages(print(p2))

The hosue prices falling into the blue-shaded region of the histogram, above, are boxplotted by Neighborhood and depicted in Fig.XV, below. Each boxplot represents Neighborhood as a function of actual selling price. The symbols used in each boxplot are consistent with the description provided for Fig.II in section 2 above.

suppressWarnings(print(sd1Plot))

The List below represents the top 15 overvalued houses that were identified by the model in the ames validation data.

  1. The \(\bf Neighborhood\) column is which of the 20 Neighborhoods where the house is located
  2. The \(\bf price\) column is the actual sale price in $US
  3. The \(\bf Predict\) column is the price, $US, predicted by the model
  4. The \(\bf Diff\) column is the difference in the predicted and actual price in $US. This column is a measuse of the \(\bf Overvaluedness\) for the house.
head(OV,12)
##    index Neighborhood  price  Predict      Diff
## 27   265      StoneBr 441929 319304.5 122624.48
## 12   109      NoRidge 584500 465254.4 119245.57
## 14   136      Crawfor 311500 236255.8  75244.24
## 24   226      StoneBr 470000 401347.9  68652.13
## 25   232      ClearCr 328000 261394.4  66605.55
## 4     67      Veenker 373000 306434.1  66565.94
## 19   188      SawyerW 270000 204709.2  65290.82
## 10    97      SawyerW 275000 214861.0  60139.03
## 3     61      NridgHt 370000 310346.9  59653.13
## 31   306       Timber 335000 279253.5  55746.52
## 1     28      Edwards 216000 161622.0  54377.99
## 17   149      Veenker 279700 225969.6  53730.35

2.5 Part 5 Conclusion

Provide a brief summary of your results, and a brief discussion of what you have learned about the data and your model.


2.5.1 Results Summary

2.5.1.1 Log of Lowest House prices as a Function of Log of Living Space

The overvalued and undervalued houses, for the validation data, are partitioned into two subsets according to price. One subset groups lowest selling price houses together, while the other groups the houses with the highest price. A scatter plot for each is provided below.

For the 335 lowest priced houses in the scatter plot above 199 are under valued. The remaining 136 are overvalued.

2.5.1.2 Log of Highest House prices as a Function of Log of Living Space

For the 335 highest priced houses in the scatter plot above 161 are under valued. The remaining 175 are overvalued.

2.5.2 Learned Findings

2.5.2.1 Exploratory Data Analysis (EDA) and Modeling

The EDA was used to examine undervalued and overvalued homes with respect to contibuting data factors. The factors that were examined included Condition of Sale, Neighborhood and overall quality. Attention was initially spent on the lower priced houses. It became evident that all ranges of house prices were subject to being both undervalued as well as overvalued.

Examining different types of models for the final model involved using BAS, AIC/BIC and data transformations.
The final model was selected from a subset containing all usable data items using the forward selection method with adjusted R squared. This along with BAS filtering and data transformations produced the highly effective final model.

2.5.2.2 Analysis and Outcome

Using the final model, the validation model data was analyzed in terms of residuals, RMSE and prediction. The final model residuals were close examined to determine the houses in the validation set that were either overvalued or undervalued. Statistical analysis was performed on hte residual data to produce a list of undervalued and overvalued houses.