Introduction

About Our Dataset

The 2022 Manufactured Homes Survey (MHS) dataset, a regular study by the U.S. Census Bureau supported by the Department of Housing and Urban Development, offers monthly estimates on average sales prices and total shipments of new manufactured homes across diverse regions and sizes in 2022. Our team decided to work with this interesting data set and carried out several statistical analysis and machine learning methods to answer several research question.

You can find the original data source and more detailed informmation about the data set in here.

Also, a copy of the data set on a Google drive can be find here.

In addition, you can download the data set as an XLS-formmated file directly from here.

On this page, you can see the data dictionary and the first five observations of the data set at the bottom.

The dataset comprises 7024 observations and 17 variables, encompassing continuous numerical, binary, and categorical types. No cells were empty; instead, NA values were encoded as 9. Our team decided to remove all the rows that contain 9 (i.e., NA) since imputing the NAs would result in significant change in the result of our statistical analysis. This reduced our dataset size to approximately 4500 observations.

Data Dictionary

Data Sample

Multiple Regression

Multiple Regression

by Mehdi Hasanov

In this section, we will develop a multiple linear regression (MLR) model with the intent to find a model suitable for predicting the price. Choosing PRICE is natural as we intuitively know that features of a house affect it’s pricing. Also, we can imagine that this can be useful information for real world applications. However, the real question would be how much of the variance in the PRICE can be explained by the other variables.

To start, let’s visualize the scatter matrix of our data set to investigate further on the variables we have. For simplicity, we will only work with continuous and binary variables to build this model. However, we can possibly create dummy variables to include categorical variables if we want to.

ggpairs(dataset, columns = c("PRICE", "SQFT", "WEIGHT", "WGTADJ", "LEASE", "BEDROOMS"),
upper = list(continuous = "smooth"), lower = list(continuous = "cor") )

options(show.signif.stars = F)

Initial Model

You can see that PRICE and SQFT have the highest correlation, which is not surprising. Such relationships are intuitive. Though it was a slight concern that PRICE is not normally distributed.

Now, let’s build our full model.

modfit <- lm(PRICE ~ SQFT + WGTADJ + WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)

Next, we need to check the condition number of our model matrix to see if the model matrix has an issue of multicollinearity:

kappa( t(model.matrix(modfit)) %*% model.matrix(modfit) )
[1] 2426601703

The condition number is too big, which indicates that the estimator is having numerical instability. In other words, the model matrix is close to be singular, and therefore, there is a high chance of multicollinearity among the predictor variables.

To check further on the possibility of multicollinearity among the predictor variables, we can check their variance inflation factor (VIF):

VIF_values <- VIF(modfit)
print(VIF_values)
     SQFT    WGTADJ    WEIGHT     LEASE  BEDROOMS FINALDEST 
 1.296482  1.065540  1.071904  1.025100  1.255708  1.051118 

We can see that the VIF are all of an acceptable magnitude because they are all less than 5. Therefore, there is no issue of multicollinearity among the predictor variables. Otherwise the feature with the highest VIF would have been removed and VIF recalculated.

Let’s check the fitted model.

summary(modfit)

Call:
lm(formula = PRICE ~ SQFT + WGTADJ + WEIGHT + LEASE + BEDROOMS + 
    FINALDEST, data = dataset)

Residuals:
    Min      1Q  Median      3Q     Max 
-139728  -21136   -1202   12876  181520 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -92961.088  12753.212  -7.289 3.63e-13
SQFT            75.363      1.256  59.980  < 2e-16
WGTADJ       10109.434  12224.569   0.827   0.4083
WEIGHT        -496.040     27.464 -18.061  < 2e-16
LEASE2      126466.289   2243.082  56.381  < 2e-16
BEDROOMS3    -8138.099   1415.792  -5.748 9.59e-09
FINALDEST2   -2583.059   1024.634  -2.521   0.0117

Residual standard error: 33310 on 4735 degrees of freedom
Multiple R-squared:  0.6497,    Adjusted R-squared:  0.6493 
F-statistic:  1464 on 6 and 4735 DF,  p-value: < 2.2e-16

0.6497 is the R-squared value, the proportion of the variation explained by the model.

We can see that WGTADJ failed the test and will now be eliminated from the model and the model refited.

modfit <- lm(PRICE ~ SQFT + WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)

Let’s check the Residuals versus Fitted graph for any patterns.

plot(rstudent(modfit) ~ fitted(modfit), pch=19, las=1, xlab = "Fitted Values", ylab="Standardized Residuals")
abline(h=0)

It is hard to tell if there is curvature, so we will check if the residuals are normally distributed.

shapiro.test(modfit$residuals)

    Shapiro-Wilk normality test

data:  modfit$residuals
W = 0.90914, p-value < 2.2e-16

We failed the Shapiro-Wilk normality test. Therefore, a log transformation will be applied.

Log transformation is needed due the issue of heteroscedasticity and the existence of pattern in errors around the line of fit. This is also necessary due to PRICE not being normally distributed.

dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_WEIGHT <- log(dataset$WEIGHT)
dataset$log_PRICE <- log(dataset$PRICE)
dataset$log_WGTADJ <- log(dataset$WGTADJ)

modfit <- lm(log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)
summary(modfit)

Call:
lm(formula = log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + 
    LEASE + BEDROOMS + FINALDEST, data = dataset)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.85677 -0.13806  0.00151  0.12289  0.97103 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.751710   0.091200 -41.137  < 2e-16
log_SQFT     0.877925   0.012942  67.835  < 2e-16
log_WGTADJ   0.266499   0.083932   3.175  0.00151
log_WEIGHT  -0.097055   0.004642 -20.908  < 2e-16
LEASE2       9.479880   0.015128 626.638  < 2e-16
BEDROOMS3   -0.079144   0.009927  -7.973 1.93e-15
FINALDEST2  -0.013047   0.006919  -1.886  0.05940

Residual standard error: 0.2247 on 4735 degrees of freedom
Multiple R-squared:  0.9888,    Adjusted R-squared:  0.9888 
F-statistic: 6.954e+04 on 6 and 4735 DF,  p-value: < 2.2e-16

Due to the t-test we will remove FINALDEST.

modfit <- lm(log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + LEASE + BEDROOMS, data = dataset)
summary(modfit)

Call:
lm(formula = log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + 
    LEASE + BEDROOMS, data = dataset)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.85583 -0.13835  0.00139  0.12399  0.96777 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.746032   0.091175 -41.086  < 2e-16
log_SQFT     0.877640   0.012945  67.800  < 2e-16
log_WGTADJ   0.263850   0.083942   3.143  0.00168
log_WEIGHT  -0.098555   0.004574 -21.545  < 2e-16
LEASE2       9.476756   0.015041 630.050  < 2e-16
BEDROOMS3   -0.080612   0.009899  -8.144 4.86e-16

Residual standard error: 0.2247 on 4736 degrees of freedom
Multiple R-squared:  0.9888,    Adjusted R-squared:  0.9888 
F-statistic: 8.34e+04 on 5 and 4736 DF,  p-value: < 2.2e-16

The model has high R-sqaured and Adjusted R-squared values.

Our data looks significant.

reduced_modfit <- lm(log_PRICE ~ 1, data = dataset)
anova(reduced_modfit, modfit)
Analysis of Variance Table

Model 1: log_PRICE ~ 1
Model 2: log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + LEASE + BEDROOMS
  Res.Df     RSS Df Sum of Sq     F    Pr(>F)
1   4741 21300.7                             
2   4736   239.2  5     21062 83401 < 2.2e-16

Though it looks like taking into account categorical variables like SECTIONS could be relevant. Quite unusually the adjusted R-squared value kept growing as models with more features were being evaluated, without eventually dropping back down.

best_subsets_reg <- regsubsets(log_PRICE ~ .-PRICE, data = dataset)
Reordering variables and trying again:
best_subsets_results <- summary(best_subsets_reg)
data.frame(best_subsets_results$outmat,
"adjR2" = best_subsets_results$adjr2,
"Cp" = best_subsets_results$cp,
"BIC" = best_subsets_results$bic )
         WEIGHT STATUS2 FINALDEST2 FOOTINGS2 FOOTINGS3 FOOTINGS4 FOOTINGS5
1  ( 1 )                                                                  
2  ( 1 )                                                                  
3  ( 1 )                                                                  
4  ( 1 )                                                                  
5  ( 1 )                                                                  
6  ( 1 )                                                                  
7  ( 1 )                                                                  
8  ( 1 )                                                                  
9  ( 1 )                                                                  
         FOOTINGS9 LEASE2 LOCATION2 LOCATION3 LOCATION4 LOCATION9 REGION2
1  ( 1 )                *                                                
2  ( 1 )                *                                                
3  ( 1 )                *                                                
4  ( 1 )                *                                                
5  ( 1 )                *                                                
6  ( 1 )                *                                                
7  ( 1 )                *                                                
8  ( 1 )                *                                                
9  ( 1 )                *                                               *
         REGION3 REGION4 REGION5 PIERS1 PIERS2 PIERS3 PIERS4 PIERS9 SECURED1
1  ( 1 )                                                                    
2  ( 1 )                                                                    
3  ( 1 )                                                                    
4  ( 1 )               *                                                    
5  ( 1 )               *                                                    
6  ( 1 )               *                                                    
7  ( 1 )       *       *                                                    
8  ( 1 )       *       *                                                    
9  ( 1 )       *       *                                                    
         SECURED2 SECURED3 SECURED9 TITLED2 TITLED3 TITLED9 SECTIONS2 SECTIONS3
1  ( 1 )                                                                       
2  ( 1 )                                                                       
3  ( 1 )                                                            *          
4  ( 1 )                                                            *          
5  ( 1 )                                                            *         *
6  ( 1 )                                                            *         *
7  ( 1 )                                                            *         *
8  ( 1 )                                                            *         *
9  ( 1 )                                                            *         *
         SQFT BEDROOMS3 SHIPMONTHAug SHIPMONTHDec SHIPMONTHFeb SHIPMONTHJan
1  ( 1 )                                                                   
2  ( 1 )                                                                   
3  ( 1 )    *                                                              
4  ( 1 )    *                                                              
5  ( 1 )                                                                   
6  ( 1 )              *                                                    
7  ( 1 )              *                                                    
8  ( 1 )              *                                                   *
9  ( 1 )              *                                                   *
         SHIPMONTHJul SHIPMONTHJun SHIPMONTHMar SHIPMONTHMay SHIPMONTHNov
1  ( 1 )                                                                 
2  ( 1 )                                                                 
3  ( 1 )                                                                 
4  ( 1 )                                                                 
5  ( 1 )                                                                 
6  ( 1 )                                                                 
7  ( 1 )                                                                 
8  ( 1 )                                                                 
9  ( 1 )                                                                 
         SHIPMONTHOct SHIPMONTHSep WGTADJ log_SQFT log_WEIGHT log_WGTADJ
1  ( 1 )                                                                
2  ( 1 )                                         *                      
3  ( 1 )                                                                
4  ( 1 )                                                                
5  ( 1 )                                         *                      
6  ( 1 )                                         *                      
7  ( 1 )                                         *                      
8  ( 1 )                                         *                      
9  ( 1 )                                         *                      
             adjR2         Cp       BIC
1  ( 1 ) 0.9730043 9508.81437 -17112.55
2  ( 1 ) 0.9873930 1915.84888 -20715.77
3  ( 1 ) 0.9895598  773.43891 -21602.57
4  ( 1 ) 0.9901634  455.92822 -21877.52
5  ( 1 ) 0.9906680  190.75628 -22119.77
6  ( 1 ) 0.9907436  151.87525 -22150.87
7  ( 1 ) 0.9908015  122.28583 -22173.20
8  ( 1 ) 0.9908497   97.86575 -22190.65
9  ( 1 ) 0.9908888   78.24094 -22203.50

To conclude I would say that the model is effective at finding a relationship between the features and the PRICE.

kNN Regression

k-Nearest Neighbors Regression

by Mohammad Ali Beheshti

Correlation Analysis of Continuous Numerical Variables Using Scatterplot Matrix

In this part, we create a scatter plot matrix to investigate on any evidence of correlation between any of the four continuous numerical variables of PRICE, SQFT, WEIGHT, and WGTADJ.

# Create a partial scatterplot matrix for the dataset2
ggpairs(dataset2,
        columns = c("PRICE", "SQFT", "WEIGHT", "WGTADJ"),
        upper = list(continuous = "smooth"),
        lower = list(continuous = "cor") )

As you can see, among all the variables, PRICE and SQFT has the highest correlation (approximately +0.70).

The KNN Regression of Price vs. Square Footage of Homes

Now, let’s take a look at the scatter lot of PRICE vs. SQFT:

This scatter plot evidently shows a high positive correlation between the two variables.

Now, our research question would be: Given the SQFT, can we predict the PRICE using the kNN regression. If so, what would be an optical k for the regression.

First, let’s use kNN regression with k = 50 as the number of neighbors. The following is the R code chuck to conduct a kNN regression with PRICE variable (our response) being regressed on the SQFT variable (our explanatory variable) with k = 50:

# Set the seed for reproducibility
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7))

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

# Perform kNN regression using the 'knn.reg' function with 'SQFT'
# as predictor and 'PRICE' as the response variable, using a k-value of 50
y_pred_knn_reg <-
  knn.reg(
    train = training_df["SQFT"],
    test = training_df["SQFT"],
    y = training_df["PRICE"],
    k = 50
  )

# Create a data frame 'df_knn_reg_w_pred' containing 'SQFT' and predicted
# values 'yhat'
df_knn_reg_w_pred <-
  data.frame(x = training_df["SQFT"], yhat = y_pred_knn_reg$pred)

Our kNN regression worked not bad with k=50. However, it looks like it is over fitting some noises and the regression line is not smooth. To fix this issue, we should find the optimal k and avoid the over-fitting of the data. Now, to find the optimal value for k, let’s examine the bias-variance trade-off for the out-of-sample RMSE (root-mean-square error):

##--------------------------------------------------------------
## Examining Bias Variance Trade-Off for the Out-of-Sample RMSE
##--------------------------------------------------------------
# Set the seed for reproducibility
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7))

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

testing_PRICE <- testing_df %>% select(PRICE)
testing_SQFT <- testing_df %>% select(SQFT)

kset <- c(seq(2, nrow(testing_df), by = 10))

RMSE_OOS <- rep(NA, length(kset))

for (i in 1:length(kset)) {

  # Fit the model using the training set and make predictions for
  # y = PRICE using the testing x = SQFT
  homes_k_gen <- kknn(PRICE ~ SQFT,
                      train = training_df,
                      test = testing_SQFT,
                      k = kset[i],
                      kernel = "rectangular")

  RMSE_OOS[i] <- sqrt(sum((homes_k_gen$fitted.values
                           - testing_PRICE$PRICE)^2)
                      /nrow(testing_PRICE))

}

After running the bias-variance trade-off analysis on several testing data, we realized that our bias-variance trade-off for the out-of-sample RMSE shows the most optimal number of neighbors for this model is 142. However, you may not see k=142 as the most optimal k (i.e., number of neighbors) in every single bias-variance analysis, including the one shown above. On the contrary some of the bias-variance analysis suggested lower k value, which were not resolving the issue overfitting in the initial model with obtained.

Now, let’s plot the kNN regression with k=142:

As you can see in the new kNN regression fit with k=142, the overfitting issue is fixed, specially at the left bottom corner of the scatter plot, where the data points are bunched and very close to each other.

In conclusion, we were able to predict the PRICE with the SQFT using the kNN regression algorithm. The out-of-sample RMSE predictions shows that the optimal number of nearest neighbor (k) for this regression is 142.

 

 

 

Natural Cubic Spline

Natural Cubic Spline

By Mehdi Hasanov

Can we predict PRICE with SQFT (i.e., square footage)? In this section, we are trying to find the answer to this question through the model. This model will fit SQFT to PRICE. As the data seems to fan out it is typically recommended to do a Log transformation of these continuous variables. After applying this transformation the data set was broken up into training and testing data sets (70% and 30%).

dataset <- dataset[dataset$SQFT != 9, ]
dataset <- dataset[dataset$PRICE != 9, ]
#Price vs SQFT
plot(dataset$SQFT, dataset$PRICE, 
     xlab = "SQFT", 
     ylab = "PRICE",
     main = "Scatter Plot of SQFT vs PRICE")
#Log vs Log transformation
dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_PRICE <- log(dataset$PRICE)
#Breakup 70 vs 30
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]

Train Data

We can fit our model using a range of df to pick the best one (low SSE). We can also visualize this information to make the choice. From this visualization we picked the value 16 for df. While values greater than 16 have a lower SSE the change is mall and we don’t want to over fit.

calc_sse <- function(d_freedom) {
  model_bs <- lm(formula = log_PRICE ~ bs(log_SQFT, df = d_freedom, intercept = TRUE), data = train_data)
  residuals <- model_bs$residuals
  sse <- sum(residuals^2)
  return(sse)
}

results_dataset <- data.frame(d_freedom = 4:19, SSE = 0)

for (d_freedom in 4:19) {
  sse <- calc_sse(d_freedom)
  results_dataset[d_freedom - 3, "SSE"] <- sse
}

Test Data

We can repeat our approach to find a df. From this visualization we picked the value 11 for df. I would say that the approach was definitely somewhat successful, especially since we minimized SSE and looks good on the test set. A;though the shape of the data might not be ideal for this.

results_dataset <- data.frame(d_freedom = 4:19, SSE = 0)

for (d_freedom in 4:19) {
  best_model <- lm(log_PRICE ~ bs(log_SQFT, df = d_freedom, intercept = TRUE), data = test_data)
  predicted_values <- predict(best_model, newdata = test_data, type = "response")
  residuals_dataset <- test_data$log_PRICE - predicted_values
  sse_dataset <- sum(residuals_dataset^2)
  results_dataset[d_freedom - 3, "SSE"] <- sse_dataset
}
best_model <- lm(log_PRICE ~ bs(log_SQFT, df = 16, intercept = TRUE), data = train_data)

It is hard to comment here. We can visually see the line and where the mean given a QSFT value should be. It seems to be a good estimator, but our data shape makes the SSE feel abnormally big, yet this is still somewhat useful.

Ridge Regression Fit

Ridge Regression Fit

by Mohammad Ali Beheshti

In this section, we would like to predict the PRICE of a house using all available numerical variables, which are SQFT (i.e., square footage), WEIGHT (i.e., sample weight), and WGTADJ (i.e., weight adjustment), from the data set. We perform the regression on only the observations which have no NA values.

Before we choose any regression model to predict PRICE, first, let’s run a multiple linear regression (MLR) and check its condition number to see how numerically unstable our estimator is. If the condition number is very high, this indicates that our model matrix is close to be singular, and, therefore, our estimator is numerically unstable. In this situation, we can use a regression method, such as Ridge regression, that uses regularization to make our model matrix full-rank (i.e., non-singular), and, as a result, fix the issue of numerical instability in the estimator.

So, let’s check the condition number of the model matrix for the MLR model.

# Define the model matrix 
newlm <- lm(PRICE ~ SQFT + WEIGHT + WGTADJ, data=dataset2)

# Compute the condition number of the model matrix
kappa( t(model.matrix(newlm)) %*% model.matrix(newlm) )
[1] 4596037244

As you can see, the condition number is very high. This indicates that our model matrix is close to be singular and the estimator has the issue of numerical instability.

To fix this issue, we will use the Ridge regression, which uses Tikhonov regularization. We use R glmnet library for the Ridge regression.

# Define response variable
y <- dataset2$PRICE

# Define matrix of predictor variables
x <- data.matrix(dataset2[, c('SQFT', 'WEIGHT', 'WGTADJ')])

# Fit the Ridge regression model
# We choose `alpha = 0` for the Ridge regression. `alpha = 1` will perform a 
# LASSO regression. 
modfit_ridge <- glmnet(x, y, alpha = 0)

summary(modfit_ridge)
          Length Class     Mode   
a0        100    -none-    numeric
beta      300    dgCMatrix S4     
df        100    -none-    numeric
dim         2    -none-    numeric
lambda    100    -none-    numeric
dev.ratio 100    -none-    numeric
nulldev     1    -none-    numeric
npasses     1    -none-    numeric
jerr        1    -none-    numeric
offset      1    -none-    logical
call        4    -none-    call   
nobs        1    -none-    numeric

Now, let’s perform a k-fold cross validation to find the optimal lambda value for the penalty function of the Ridge regression.

# Perform k-fold cross-validation to find optimal lambda value
cv_model <- cv.glmnet(x, y, alpha = 0)

As you can see in the plot of MSE vs. \(log(\lambda)\), the best lambda value () is approximately equal to \(e^{8.13} \approx 3390.41\):

# Find the optimal lambda value that minimizes test MSE
best_lambda <- cv_model$lambda.min
best_lambda
[1] 3390.409

Now, let’s compute our Ridge regression model using \(\lambda = 3390.41\) and find its regression coefficients.

# Find coefficients of best model
best_modfit_ridge <- glmnet(x, y, alpha = 0, lambda = best_lambda)

# Print the coefficients of the best model 
coef(best_modfit_ridge)
4 x 1 sparse Matrix of class "dgCMatrix"
                     s0
(Intercept) 15337.99203
SQFT           69.84305
WEIGHT       -497.92052
WGTADJ      28260.08509

In conclustion, due to numerical instability of our estimator in the multiple linear regression model, we decided to use the Ridge regression with \(\lambda = 3390.41\) to predict the PRICE given SQFT, WEIGHT, and WGTADJ as our predictor variables. The obtained regression equation is:

\[ \widehat{PRICE} = 15337.99203 + 69.84305 \ SQFT - 497.92052 \ WEIGHT + 28260.08509 \ WGTADJ \]  

 

 

Naive Bayes Classification

Naive Bayes Classification

by Mehdi Hasanov

Here we will try and answer the following question: Can we predict whether a house is being leased using Naive Bayes Classification?

Once again we start by splitting the data into training and testing data sets. Then we fit the model using all features and examine the coefficient. We found something very interesting when examining the coefficients of the full model. Although by accident. The value 9 represents NA in this data set. Rows with 9 values were originally cleaned out, but those with 9 in the PRICE column were reintroduced here to catch something special. But first note how the model is doing well in some part, but has a huge problem miss classifying when the true value is 2.

sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]

nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))

 
   Cell Contents
|-------------------------|
|                       N |
|           N / Col Total |
|-------------------------|

 
Total Observations in Table:  1423 

 
             | actual 
   predicted |         1 |         2 | Row Total | 
-------------|-----------|-----------|-----------|
           1 |        74 |       776 |       850 | 
             |     1.000 |     0.575 |           | 
-------------|-----------|-----------|-----------|
           2 |         0 |       573 |       573 | 
             |     0.000 |     0.425 |           | 
-------------|-----------|-----------|-----------|
Column Total |        74 |      1349 |      1423 | 
             |     0.052 |     0.948 |           | 
-------------|-----------|-----------|-----------|

 

PRICENOT9

A natural follow up was to investigate the coefficients. The bellow model table caught my attention. At the time we replaced 9 with median values. We changed our approach and just removed those rows, but in the process something got uncovered. All values where Y is 1 have 9 (NA) for their price. This was obvious due to the variance being zero. Naturally this can be used to easily be used to eliminate some of these classifications. I did have some concern about this approach, since it feels weird to use and NA value in this way, after all this could be over fitting. But from a industry or business analysis stand of point one can argue that such and approach could be useful. It all depends on the application.
nb_model$tables[[11]]
   PRICE
Y       [,1]     [,2]
  1      9.0     0.00
  2 138828.5 49099.99
So we added a feature that captures this behavior. I called it PRICENOT9. As you can see this greatly improved the accuracy.
dataset$PRICENOT9 <- ifelse(dataset$PRICE != 9, 1, 0)
dataset$PRICENOT9 <- factor(dataset$PRICENOT9)
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]
nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))

 
   Cell Contents
|-------------------------|
|                       N |
|           N / Col Total |
|-------------------------|

 
Total Observations in Table:  1423 

 
             | actual 
   predicted |         1 |         2 | Row Total | 
-------------|-----------|-----------|-----------|
           1 |        73 |        40 |       113 | 
             |     1.000 |     0.030 |           | 
-------------|-----------|-----------|-----------|
           2 |         0 |      1310 |      1310 | 
             |     0.000 |     0.970 |           | 
-------------|-----------|-----------|-----------|
Column Total |        73 |      1350 |      1423 | 
             |     0.051 |     0.949 |           | 
-------------|-----------|-----------|-----------|

 

Less is more

In the end the continuous variables were removed from the model, since after testing several features we saw they didn’t contribute much and we didn’t want to over fit. The results were amazing, over 90% accuracy at the time when using our initial data cleaning approaches. So I would say the answer to our original question was yes. We can predict whether a house is being leased using Naive Bayes Classification, with extreme accuracy.

Footnote: Originally our data cleaning approach was different, we used medians to replace the 9/NA values and even then the new PRICENOT9 feature won’t a perfect collator to LEASE. But as we fixed our cleaning methodology at the very end these new relationships were uncovered. So the initial approach to this model was kept, but updated to give more honesty and transparency. Overall a great learning experience. This approach made a lot more sense before some of the discoveries discussed. As I believed that the PRICE having a certain value was indicative of a certain company and model that was the primary lease provider. Though such a possibility might still exist.

nb_model <- naiveBayes(LEASE ~ PRICENOT9, data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))

 
   Cell Contents
|-------------------------|
|                       N |
|           N / Col Total |
|-------------------------|

 
Total Observations in Table:  1423 

 
             | actual 
   predicted |         1 |         2 | Row Total | 
-------------|-----------|-----------|-----------|
           1 |        73 |         0 |        73 | 
             |     1.000 |     0.000 |           | 
-------------|-----------|-----------|-----------|
           2 |         0 |      1350 |      1350 | 
             |     0.000 |     1.000 |           | 
-------------|-----------|-----------|-----------|
Column Total |        73 |      1350 |      1423 | 
             |     0.051 |     0.949 |           | 
-------------|-----------|-----------|-----------|

 

What we should have done

To avoid criticism and demonstrate proper methodology bellow is a proper approach to the problem. Log transformations! Added bellow were the log transformations of some of the continuous features to the data set. Only 98 classifications out of 1252. Great results. Though it is concerning the more than half of the time the model is wrong when prediction a value of 1. Though this is still really good.

dataset$log_WEIGHT <- log(dataset$WEIGHT)
dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_PRICE <- log(dataset$PRICE)
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]
nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))

 
   Cell Contents
|-------------------------|
|                       N |
|           N / Col Total |
|-------------------------|

 
Total Observations in Table:  1423 

 
             | actual 
   predicted |         1 |         2 | Row Total | 
-------------|-----------|-----------|-----------|
           1 |        73 |        98 |       171 | 
             |     1.000 |     0.073 |           | 
-------------|-----------|-----------|-----------|
           2 |         0 |      1252 |      1252 | 
             |     0.000 |     0.927 |           | 
-------------|-----------|-----------|-----------|
Column Total |        73 |      1350 |      1423 | 
             |     0.051 |     0.949 |           | 
-------------|-----------|-----------|-----------|

 

Classification using Logistic Reg.

Classification using Logistic Regression

by Mohammad Ali Beheshti

In our dataset, FINALDEST is a binary variable that indicates whether a manufactured home is placed at its final destination or not. We would like classify a manufactured home on whether or not it was placed at its final destination using all available numerical variables in the dataset, which are PRICE, SQFT (i.e., square footage), WEIGHT (i.e., sample weight), and WGTADJ (i.e., weight adjustment). We use logistic regression to do this classification. For this model, we remove all the observations in our dataset that contain NA values.

First, let’s investigate on the FINALDEST variable by taking a look the frequency of its values (levels). A value of 1 means the home was placed at its final destination and a value of 2 means otherwise.

# Create a frequency table
freq_table <- table(dataset2$FINALDEST)

# Display the frequency table
print(freq_table)

   1    2 
2759 1746 

As you can see, there is no huge difference between the proportion of the two levels. Also, most of the homes were placed at their final destination.

Now, lets use the stepwise search as the selection method along with the BIC (Bayes information criterion) as the selection criterion to select the best model for our logistic regression.

# Set the seed for reproducibility 
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7)) 

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

# Define the null model for the logistic regression 
null <- glm(data = training_df, FINALDEST ~ 1, family = binomial)

# Define the full model for the logistic regression 
full <- glm(data = training_df, FINALDEST ~ PRICE + SQFT + WEIGHT + WGTADJ, family = binomial)

# Use stepwise search to select the best model 
step(null, 
     scope = list(lower = null, upper = full), 
     direction = "both", 
     k = log(nrow(training_df)), trace = 0)

Call:  glm(formula = FINALDEST ~ WEIGHT, family = binomial, data = training_df)

Coefficients:
(Intercept)       WEIGHT  
    0.86747     -0.01849  

Degrees of Freedom: 3153 Total (i.e. Null);  3152 Residual
Null Deviance:      4219 
Residual Deviance: 4132     AIC: 4136

As you can see, the best selected model using BIC as the selection criterion happens to only include WEIGHT.

Based on the result we obtained, the following is the logistic regression equation for the selected model:

\[ \widehat{\eta} = 0.86747 - 0.01849 \ * WEIGHT \] Now, let’s plot FINALDEST vs. WEIGHT along with the logistic curve that is obtained from the logistic regression model.

We want to use the logistic regression model we obtained to classify FINALDEST (i.e., if a produced house reached its final destination) as “Yes” (1) or “No” (0).

Now, the question is what would be the value of the decision boundary for WEIGHT. The decision boundary is a WEIGHT value that. If a produced house has a weight less than the decision boundary, it would be classified as 1 (i.e., reached its final destination) or 0 otherwise. The following is the condition statement for the classification decision-making process:

\[ \begin{cases} \text{0 (did not reach its final destination)} & \text{if } \text{`WEIGHT`} \geq \text{Decision Boundary}, \\ \text{1 (reached its final destination)} & \text{if } \text{`WEIGHT`} < \text{Decision Boundary}. \end{cases} \] Since we obtained a simple logistic regression model (i.e., a regression model with a single predictor), the decision boundary should be \(\geq -\frac{\beta_0}{\beta1}\). Therefore, for this model, the decision boundary should be the weight of \(\geq 46.916\). So, let’s visualize the decision boudary and a look at the plot of FINALDEST vs. WEIGHT with the logistic curve.

As you can see in the plot, the decision boundary happened to approximately intersect with the threshold of 0.5 or 50 percent in the probability of FINALDEST on the y-axis. So, we will use the threshold of 0.5 to classify our data points. Any data point with the probability of 0.5 or greater will be classified as “true” for the FINALDEST.

Now, let’s define the best model using logistic regression, and compute the predicted probabilities for the FINALDEST using the best model we obtained from the logistic regression.

# Define the best fitted model we obtained 
modfit_best <- glm(data = training_df, FINALDEST ~ WEIGHT, family = binomial)

# Compute the predicted values for the training dataset using the best fitted model 
pihat_train <- predict(modfit_best, 
                       newdata = training_df,
                       type = "response")

Next, we classify all the predicted values for the FINALDEST using a threshold of 70 percent. That being said, any FINALDEST that has a probability of more than 70 percent, will be classified as “Yes” or “reached the final destination”, and any FINALDEST that has a probability of 70 percent or less, will be classified as “No” or “did not reached the final destination.”

# Define the threshold
threshold <- 0.60

# Categorize all the predicted values for the training dataset to the binary values of yes and no 
training_predicted_category <- factor( ifelse(pihat_train > threshold, "Yes", "No") )

# Convert all the `FINALDEST` binary values to `Yes` and `No` instead of 1 and 0
reference_training <- factor( ifelse(training_df$FINALDEST == 1, "Yes", "No") )

Now, let’s look at the in-sample misclassification rate and see how well our best model from the logistic regression classified the data:

# Average Misclassification Rate
mean((as.numeric(training_df$FINALDEST)-1) != (pihat_train > 0.70))
[1] 0.390298

With a threshold of 70 percent, we have a misclassification rate of about 43%, which is high and not good. 70 percent is the best threshold value we can choose. This high misclassification rate makes sense since if you look at the last plot; the majority of the manufactured homes reached their destination no matter how heavy their weight.

Now, let’s look at the confusion matrix for the in-sample classification:

# Construct the confusion matrix for the in-sample classification
confusionMatrix(data = training_predicted_category,
                reference = (reference_training))
Confusion Matrix and Statistics

          Reference
Prediction   No  Yes
       No   546  536
       Yes  685 1387
                                          
               Accuracy : 0.6129          
                 95% CI : (0.5956, 0.6299)
    No Information Rate : 0.6097          
    P-Value [Acc > NIR] : 0.3648          
                                          
                  Kappa : 0.1685          
                                          
 Mcnemar's Test P-Value : 2.281e-05       
                                          
            Sensitivity : 0.4435          
            Specificity : 0.7213          
         Pos Pred Value : 0.5046          
         Neg Pred Value : 0.6694          
             Prevalence : 0.3903          
         Detection Rate : 0.1731          
   Detection Prevalence : 0.3431          
      Balanced Accuracy : 0.5824          
                                          
       'Positive' Class : No              
                                          

As the confusion matrix for the training data shows, the in-sampele accuracy rate is about 40 percent, which is very low. A high number of houses were falsely predicted that they did reached their destination, but they did.

Finally, let’s look at the out-of-sample misclassification rate:

# Compute the predicted values for the testing dataset using the best fitted model 
pihat_test <- predict(modfit_best, 
                       newdata = testing_df,
                       type = "response")

# Categorize all the predicted values for the testing dataset to the binary values of yes and no 
testing_predicted_category <- factor( ifelse(pihat_test > threshold, "Yes", "No") )

# Average Misclassification Rate
mean((as.numeric(testing_df$FINALDEST)-1) != (pihat_test > 0.70))
[1] 0.3811991

If we set the threshold to 70 percent, we have a misclassification rate of about 43%, which is close to what we get for the training dataset. This indicates that our model at least did a good job for out-of-sample classification.

Now, let’s look at the confusion matrix for the out-of-sample classification:

# Convert all the `FINALDEST` binary values to `Yes` and `No` instead of 1 and 0
reference_testing <- factor( ifelse(testing_df$FINALDEST == 1, "Yes", "No") )

# Construct the confusion matrix for the out-of-sample classification
confusionMatrix(data = testing_predicted_category,
                reference = (reference_testing))
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  227 225
       Yes 288 611
                                          
               Accuracy : 0.6203          
                 95% CI : (0.5938, 0.6462)
    No Information Rate : 0.6188          
    P-Value [Acc > NIR] : 0.467396        
                                          
                  Kappa : 0.1758          
                                          
 Mcnemar's Test P-Value : 0.006193        
                                          
            Sensitivity : 0.4408          
            Specificity : 0.7309          
         Pos Pred Value : 0.5022          
         Neg Pred Value : 0.6796          
             Prevalence : 0.3812          
         Detection Rate : 0.1680          
   Detection Prevalence : 0.3346          
      Balanced Accuracy : 0.5858          
                                          
       'Positive' Class : No              
                                          

As the confusion matrix for the testing data shows, the out-of-sample accuracy rate is about 37 percent, which is, again, very low. A high number of houses were falsely predicted that they did reached their destination, but they did.

In conclusion, were able to classify the FINALDEST of an observation using SQFT and WEIGHT with a very low in-sample and out-of-sample accuracy rate of about 40 percent using the logistic regression approach.

 

 

 

About Our Team

Column 1

About Our Team

This is Mohammad-Ali and Mehdi from Virginia Tech. We are senior undergraduate students, majoring in Computational Modeling and Data Analytics (CMDA). We are both taking the “Intermediate Data Analysis and Machine Learning” (CMDA 4654) course with Dr. Christian Lucero this semester, and we decided to work on this data science project together.

Here is more about each of us:

Column 2

Mohammad-Ali Beheshti

I am is originally from Tehran, Iran. I am perusing my bachelors in Computational Modeling and Data Analytics (CMDA) with a minor in Computer Science and a minor in Environmental Horticulture. My favorite pastime is group workout.

Email:

Mehdi Hasanov

I am originally from Baku, Azerbaijan. I am perusing my bachelors in Computational Modeling and Data Analytics (CMDA). My favorite pastime is hiking.

Email:

---
title: "Mobile Home Stat Squad"
author: "Mohammad Ali Beheshti & Mehdi Hasanov"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll 
    source_code: embed
---


```{r setup, include=FALSE}

# Load the necessary libraries in alphabetical order
library(caret) # Load caret for machine learning functions
library(corrplot) # Load corrplot for visualizing correlation matrices
library(dplyr) # Load dplyr for using the select() and pipeline functions  
library(DT) # Load DT for creating interactive tables
library(e1071) # Load e1071 for statistical functions
library(FNN) # Load FNN for k-Nearest Neighbors (kNN) functionality
library(flexdashboard) # Load flexdashboard for creating interactive dashboards
library(ggplot2) # Load ggplot2 for creating static plots
library(GGally) # Load GGally for extension to ggplot2
library(glmnet) # Load glmnet to access the glmnet() function for Ridge regression
library(gmodels) # Load gmodels for model fitting
library(heatmaply) # Load heatmaply for creating interactive heatmaps
library(kknn) # Load kknn for k-Nearest Neighbors (kNN) functionality
library(knitr) # Load knitr for accessing the `kable()` function
library(leaps) # Load leaps for access to some functions
library(nlme) # Load nlme for nonlinear mixed-effects models
library(pander) # Load pander for rendering tables nicely
library(plotly) # Load plotly for creating interactive plots
library(plyr) # Load plyr for data manipulation functions
library(purrr) # Load purrr for rendering tables nicely
library(readr) # Load readr for reading data files
library(readxl) # Load readxl for reading Excel files
library(regclass) # Load regclass for regression analysis
library(scales) # Load scales for functions related to scales
library(splines) # Load splines for functions related to spline
library(stringr) # Load stringr for string manipulation functions
library(tidyverse) # Load tidyverse for a collection of packages for data manipulation and visualization
library(xtable) # Load xtable for creating tables

# Although you can call functions from a library using the following notation
#  without loading the entire library.
knitr::opts_chunk$set(echo = TRUE, 
                      comment = NA, # Recommended
                      # Store all figures here in relative path
                      fig.path = "./figures/",  
                      fig.align = "center",
                      fig.width = 7,
                      fig.height = 7,
                      message = FALSE, # Turn off load messages
                      warning = FALSE # Turn off warnings,
                      )

# Set your working directory here: <---
dir = "~/Documents/تحصیلی/کارشناسی/پاییز ۲۰۲۳/CMDA 4654/Projects/Project 1"
setwd(dir)

# Set your path to the CSV "Data Set" file here: <---
data_filePath <- "~/Documents/تحصیلی/کارشناسی/پاییز ۲۰۲۳/CMDA 4654/Projects/Project 1/puf2022.csv"

# Set your path to the XLSX "Data Dictionary" file here: <---
data.dictionary_filePath <- "~/Documents/تحصیلی/کارشناسی/پاییز ۲۰۲۳/CMDA 4654/Projects/Project 1/cmda4654_project1_data_dictionary.xlsx"

# Load the dataset 
dataset <- read.csv(data_filePath, header = TRUE, check.names = FALSE)

# Create a duplicate of the dataset
dataset2 <- dataset

##--------------------
## Cleaning "dataset"
##--------------------

## "SHIPMONTH" Conversion 

# Extract and keep only the month part
dataset$SHIPMONTH <- substr(dataset$SHIPMONTH, 5, 6)

# Define a vector of month names
month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Use the month names vector to replace the month numbers
dataset$SHIPMONTH <- month_names[as.integer(dataset$SHIPMONTH)]

#Remove columns
dataset$jbedroom <- NULL
dataset$jfinaldest <- NULL
dataset$jfootings <- NULL
dataset$jlease <- NULL
dataset$jlocation <- NULL
dataset$jpiers <- NULL
dataset$jprice <- NULL
dataset$jsecured <- NULL
dataset$jsqft <- NULL
dataset$jstatus <- NULL
dataset$jtitle <- NULL

#Remove CONTROL
dataset$CONTROL <- NULL

#Remove rows with value 9
dataset <- dataset[dataset$LEASE != 9, ]
dataset <- dataset[dataset$FINALDEST != 9, ]
dataset <- dataset[dataset$BEDROOMS != 9, ]

#Encode categorical variables as factors
dataset$REGION <- factor(dataset$REGION)
dataset$SHIPMONTH <- factor(dataset$SHIPMONTH)
dataset$SECTIONS <- factor(dataset$SECTIONS)
dataset$STATUS <- factor(dataset$STATUS)
dataset$LEASE <- factor(dataset$LEASE)
dataset$FINALDEST <- factor(dataset$FINALDEST)
dataset$BEDROOMS <- factor(dataset$BEDROOMS)
dataset$TITLED <- factor(dataset$TITLED)
dataset$LOCATION <- factor(dataset$LOCATION)
dataset$FOOTINGS <- factor(dataset$FOOTINGS)
dataset$PIERS <- factor(dataset$PIERS)
dataset$SECURED <- factor(dataset$SECURED)

##--------------------
## Cleaning "dataset2"
##--------------------

dataset2 <- dataset2[complete.cases(dataset2), ]

# Count the number of rows with NA values
na_row_count <- sum(apply(dataset2, 1, function(row) any(is.na(row))))

# Display the count of rows with NA values
print(na_row_count)

# Count the number of columns with NA values
na_column_count <- sum(apply(dataset2, 2, function(col) any(is.na(col))))

# Display the count of columns with NA values
print(na_column_count)

# Remove all the imputed indicator variables 
dataset2 <- dataset2[, 1:17]

## `SHIPMONTH" Conversion 

# Extract and keep only the month part
dataset2$SHIPMONTH <- substr(dataset2$SHIPMONTH, 5, 6)

# # Convert the month part to an actual month name (optional)
# dataset2$SHIPMONTH <- format(as.Date(paste(df$column_variable, "01", sep = "-"), format = "%Y-%m-%d"), "%B")

# Define a vector of month names
month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Use the month names vector to replace the month numbers
dataset2$SHIPMONTH <- month_names[as.integer(dataset2$SHIPMONTH)]

## Checking on the frequency of "9" in all Categorical Variables 

# table_9_count <- sapply(
#   dataset2[, c('BEDROOMS', 'TITLED', 'LOCATION', 'SECURED', 'SQFT', 'PRICE')], 
#   function(x) sum(x == 9))
# 
# # Display the frequency table of "9" counts for each categorical variable
# print(table_9_count)

# Removing All Rows with NA Values
dataset2 <- dataset2[!dataset2$PRICE == 9, ]
dataset2 <- dataset2[!dataset2$SQFT == 9, ]
dataset2 <- dataset2[!dataset2$WEIGHT == 9, ]
dataset2 <- dataset2[!dataset2$WGTADJ == 9, ]

# Make the `CONTROL` variable (i.e., the ID variable) as the first column of the dataset
dataset2 <- dataset2[, c(ncol(dataset2), 1:(ncol(dataset2)-1))]

```

Introduction
=======================================================================
<!-- ## Column 1 {data-width==500} -->

### <span style="font-size: 30px; font-weight: bold;">About Our Dataset</span>

The 2022 Manufactured Homes Survey (MHS) dataset, a regular study by the U.S. Census Bureau supported by the Department of Housing and Urban Development, offers monthly estimates on average sales prices and total shipments of new manufactured homes across diverse regions and sizes in 2022. Our team decided to work with this interesting data set and carried out several statistical analysis and machine learning methods to answer several research question. 

You can find the original data source and more detailed informmation about the data set in [here](https://www.census.gov/data/datasets/2021/econ/MHS/puf.html). 

Also, a copy of the data set on a Google drive can be find [here](https://docs.google.com/spreadsheets/d/1YdxgpOTzW0fm6JX-ww0GIYDCvuJhyej_/edit?usp=sharing&ouid=113988950026087139119&rtpof=true&sd=true). 

In addition, you can download the data set as an XLS-formmated file directly from [here](https://www2.census.gov/programs-surveys/mhs/tables/2022/puf2022.xls).

On this page, you can see the data dictionary and the first five observations of the data set at the bottom. 

The dataset comprises 7024 observations and 17 variables, encompassing continuous numerical, binary, and categorical types. No cells were empty; instead, NA values were encoded as 9. Our team decided to remove all the rows that contain 9 (i.e., NA) since imputing the NAs would result in significant change in the result of our statistical analysis. This reduced our dataset size to approximately 4500 observations. 

### <span style="font-size: 30px; font-weight: bold;">Data Dictionary</span>

```{r, echo=FALSE}
data_dictionary <- read_xlsx(data.dictionary_filePath)
datatable(data_dictionary, options = list(pageLength = 20))
```

<!-- ## Column 2 {data-with=500} -->

### <span style="font-size: 30px; font-weight: bold;">Data Sample</span>

```{r, echo=FALSE}
dataset2[1:5,] %>%
  DT::datatable()
```

Multiple Regression 
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">Multiple Regression</span>

by Mehdi Hasanov

In this section, we will develop a multiple linear regression (MLR) model with the intent to find a model suitable for predicting the price. Choosing `PRICE` is natural as we intuitively know that features of a house affect it's pricing. Also, we can imagine that this can be useful information for real world applications. However, the real question would be how much of the variance in the `PRICE` can be explained by the other variables. 


To start, let's visualize the scatter matrix of our data set to investigate further on the variables we have. For simplicity, we will only work with continuous and binary variables to build this model. However, we can possibly create dummy variables to include categorical variables if we want to.

####

```{r}
ggpairs(dataset, columns = c("PRICE", "SQFT", "WEIGHT", "WGTADJ", "LEASE", "BEDROOMS"),
upper = list(continuous = "smooth"), lower = list(continuous = "cor") )
options(show.signif.stars = F)
```

### <span style="font-size: 20px;">Initial Model</span>

You can see that `PRICE` and `SQFT` have the highest correlation, which is not surprising. Such relationships are intuitive. Though it was a slight concern that `PRICE` is not normally distributed. 

Now, let's build our full model. 

```{r}
modfit <- lm(PRICE ~ SQFT + WGTADJ + WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)
```

Next, we need to check the condition number of our model matrix to see if the model matrix has an issue of multicollinearity: 

```{r}
kappa( t(model.matrix(modfit)) %*% model.matrix(modfit) )
```

The condition number is too big, which indicates that the estimator is having numerical instability. In other words, the model matrix is close to be singular, and therefore, there is a high chance of multicollinearity among the predictor variables. 

To check further on the possibility of multicollinearity among the predictor variables, we can check their variance inflation factor (VIF): 

```{r}
VIF_values <- VIF(modfit)
print(VIF_values)
```

We can see that the VIF are all of an acceptable magnitude because they are all less than 5. Therefore, there is no issue of multicollinearity among the predictor variables. Otherwise the feature with the highest VIF would have been removed and VIF recalculated.

Let's check the fitted model. 

```{r}
summary(modfit)
```

0.6497 is the R-squared value, the proportion of the variation explained by the model.

We can see that `WGTADJ` failed the test and will now be eliminated from the model and the model refited.

```{r}
modfit <- lm(PRICE ~ SQFT + WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)
```

Let's check the Residuals versus Fitted graph for any patterns.

####

```{r}
plot(rstudent(modfit) ~ fitted(modfit), pch=19, las=1, xlab = "Fitted Values", ylab="Standardized Residuals")
abline(h=0)

```

It is hard to tell if there is curvature, so we will check if the residuals are normally distributed. 

```{r}
shapiro.test(modfit$residuals)
```

We failed the Shapiro-Wilk normality test. Therefore, a log transformation will be applied.

Log transformation is needed due the issue of heteroscedasticity and the existence of pattern in errors around the line of fit. This is also necessary due to `PRICE` not being normally distributed.

```{r}
dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_WEIGHT <- log(dataset$WEIGHT)
dataset$log_PRICE <- log(dataset$PRICE)
dataset$log_WGTADJ <- log(dataset$WGTADJ)

modfit <- lm(log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + LEASE + BEDROOMS + FINALDEST, data = dataset)
summary(modfit)
```

Due to the t-test we will remove `FINALDEST`.

```{r}
modfit <- lm(log_PRICE ~ log_SQFT + log_WGTADJ + log_WEIGHT + LEASE + BEDROOMS, data = dataset)
summary(modfit)
```

The model has high R-sqaured and Adjusted R-squared values.

Our data looks significant.

```{r}
reduced_modfit <- lm(log_PRICE ~ 1, data = dataset)
anova(reduced_modfit, modfit)
```

Though it looks like taking into account categorical variables like `SECTIONS` could be relevant. Quite unusually the adjusted R-squared value kept growing as models with more features were being evaluated, without eventually dropping back down.

```{r}
best_subsets_reg <- regsubsets(log_PRICE ~ .-PRICE, data = dataset)
best_subsets_results <- summary(best_subsets_reg)
data.frame(best_subsets_results$outmat,
"adjR2" = best_subsets_results$adjr2,
"Cp" = best_subsets_results$cp,
"BIC" = best_subsets_results$bic )
```

To conclude I would say that the model is effective at finding a relationship between the features and the PRICE.

kNN Regression
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">k-Nearest Neighbors Regression</span>

by Mohammad Ali Beheshti

<span style="font-size: 20px; font-weight: bold;">Correlation Analysis of Continuous Numerical Variables Using Scatterplot Matrix</span>

In this part, we create a scatter plot matrix to investigate on any evidence of correlation between any of the four continuous numerical variables of `PRICE`, `SQFT`, `WEIGHT`, and `WGTADJ`.

####

```{r}
# Create a partial scatterplot matrix for the dataset2
ggpairs(dataset2,
        columns = c("PRICE", "SQFT", "WEIGHT", "WGTADJ"),
        upper = list(continuous = "smooth"),
        lower = list(continuous = "cor") )
```

As you can see, among all the variables, `PRICE` and `SQFT` has the highest correlation (approximately +0.70).

<span style="font-size: 20px; font-weight: bold;">The KNN Regression of Price vs. Square Footage of Homes</span>

Now, let's take a look at the scatter lot of `PRICE` vs. `SQFT`:

####

```{r, echo=FALSE, fig.weight = 5, fig.height = 5}
# Plot the scatter plot of PRICE vs. SQFT using ggplot
graph <- ggplot(data = dataset2, aes(x = SQFT, y = PRICE)) +
  geom_point() +  # Add points for scatterplot
  labs(title = "Price vs. Square Footage of Homes",
       x = "Square Footage (Square Feet)",
       y = "Price (Dollars)") +
  scale_y_continuous(labels = comma) + # Format y-axis labels with commas
  theme_minimal() +
  theme(
    plot.title = element_text(size = 16, face = "bold", hjust = 0.5),
    # Adjust title text size, bold, and center-aligned
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12),
    axis.text = element_text(size = 12),
    panel.border = element_rect(
      color = "black",
      size = 1,
      fill = NA
    ),  # Add rectangular panel border
    axis.ticks = element_line(
      color = "black",
      size = 0.5
    ),  # Add tick marks to x and y axes
    panel.grid.major = element_blank(),  # Remove major gridlines
    panel.grid.minor = element_blank()   # Remove minor gridlines
  )

# Display the graph
graph

```

This scatter plot evidently shows a high positive correlation between the two variables.

Now, our research question would be: Given the `SQFT`, can we predict the `PRICE` using the kNN regression. If so, what would be an optical k for the regression.

First, let's use kNN regression with k = 50 as the number of neighbors. The following is the R code chuck to conduct a kNN regression with `PRICE` variable (our response) being regressed on the `SQFT` variable (our explanatory variable) with k = 50:

```{r, echo=TRUE}
# Set the seed for reproducibility
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7))

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

# Perform kNN regression using the 'knn.reg' function with 'SQFT'
# as predictor and 'PRICE' as the response variable, using a k-value of 50
y_pred_knn_reg <-
  knn.reg(
    train = training_df["SQFT"],
    test = training_df["SQFT"],
    y = training_df["PRICE"],
    k = 50
  )

# Create a data frame 'df_knn_reg_w_pred' containing 'SQFT' and predicted
# values 'yhat'
df_knn_reg_w_pred <-
  data.frame(x = training_df["SQFT"], yhat = y_pred_knn_reg$pred)
```

####

```{r, echo=FALSE, fig.weight = 5, fig.height = 5}
# Create a ggplot2 scatter plot with regression line
# The red points and lines are for predicted values
graph <- ggplot(training_df, aes(x = SQFT, y = PRICE)) +
  geom_point() +
  geom_point(data = df_knn_reg_w_pred,
             aes(x = SQFT, y = yhat),
             color = "red") +
  geom_line(data = df_knn_reg_w_pred,
            aes(x = SQFT, y = yhat),
            color = "red") +
  labs(
    title = str_wrap("Price vs. Square Footage of Homes
                     with the kNN Regression Line (K=50)", width = 40),
    # Set plot title with word wrap
    x = "Square Footage",  # Set x-axis label
    y = "Price",   # Set y-axis label
  ) +
  theme_minimal() +  # Apply minimal theme
  scale_y_continuous(labels = comma) + # Format y-axis labels with commas
  theme(
    plot.title = element_text(size = 16, face = "bold", hjust = 0.5),
    # Adjust title text size, bold, and center-aligned
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12),
    axis.text = element_text(size = 12),
    panel.border = element_rect(
      color = "black",
      size = 1,
      fill = NA
    ),  # Add rectangular panel border
    axis.ticks = element_line(
      color = "black",
      size = 0.5
    ),  # Add tick marks to x and y axes
    panel.grid.major = element_blank(),  # Remove major gridlines
    panel.grid.minor = element_blank()   # Remove minor gridlines
  )

# Display the graph
graph

```

Our kNN regression worked not bad with k=50. However, it looks like it is over fitting some noises and the regression line is not smooth. To fix this issue, we should find the optimal k and avoid the over-fitting of the data. Now, to find the optimal value for k, let's examine the bias-variance trade-off for the out-of-sample RMSE (root-mean-square error):

```{r, results='asis', fig.width= 5, fig.height= 5}
##--------------------------------------------------------------
## Examining Bias Variance Trade-Off for the Out-of-Sample RMSE
##--------------------------------------------------------------
# Set the seed for reproducibility
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7))

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

testing_PRICE <- testing_df %>% select(PRICE)
testing_SQFT <- testing_df %>% select(SQFT)

kset <- c(seq(2, nrow(testing_df), by = 10))

RMSE_OOS <- rep(NA, length(kset))

for (i in 1:length(kset)) {

  # Fit the model using the training set and make predictions for
  # y = PRICE using the testing x = SQFT
  homes_k_gen <- kknn(PRICE ~ SQFT,
                      train = training_df,
                      test = testing_SQFT,
                      k = kset[i],
                      kernel = "rectangular")

  RMSE_OOS[i] <- sqrt(sum((homes_k_gen$fitted.values
                           - testing_PRICE$PRICE)^2)
                      /nrow(testing_PRICE))

}
```

####

```{r, echo=FALSE, fig.width= 5, fig.height= 5}
# Plot the results
homes_knn_out_of_sample <- data.frame(k = kset, RMSE_OOS = RMSE_OOS)
homes_knn_out_of_sample <- homes_knn_out_of_sample %>%
  mutate( complexity = log(1/k) )
plot <- ggplot(homes_knn_out_of_sample, aes(x = complexity, y = RMSE_OOS)) +
  geom_point() +
  geom_line() +
  geom_point(data = homes_knn_out_of_sample[homes_knn_out_of_sample$k
                                            %in% c(142), ],
             aes(x = complexity, y = RMSE_OOS),
             color = "red"
             ) +
  annotate("text", x = -4.7, y = 35000,
           label = "k = 142",
           color = "red",
           size = 5) +
  labs(
  title = str_wrap("RMSE Out-of-Sample Predictions", width = 50),
  # Set plot title with word wrap
  x = "Complexity(log(1/k))",  # Set x-axis label
  y = "Out-of-Sample RMSE",   # Set y-axis label
  ) +
  theme_minimal() +  # Apply minimal theme
  scale_y_continuous(labels = comma) + # Format y-axis labels with commas
  theme(
    plot.title = element_text(size = 14, hjust = 0.5),
    # Customize title font size, family, and alignment
    axis.title.x = element_text(size = 12),
    # Customize x-axis label font size and family
    axis.title.y = element_text(size = 12),
    # Customize y-axis label font size and family
    axis.text = element_text(size = 12),
    # Customize axis text font size and family
    panel.border = element_rect(color = "black",
                                linewidth = 1,
                                linetype = "solid",
                                fill = NA),  # Customize panel border
    panel.grid.minor.x = element_blank(),  # Remove minor gridlines on x-axis
    axis.ticks = element_line(color = "gray", linewidth = 0.5),
    # Customize tick marks
  )

plot

```

After running the bias-variance trade-off analysis on several testing data, we realized that our bias-variance trade-off for the out-of-sample RMSE shows the most optimal number of neighbors for this model is 142. However, you may not see k=142 as the most optimal k (i.e., number of neighbors) in every single bias-variance analysis, including the one shown above. On the contrary some of the bias-variance analysis suggested lower k value, which were not resolving the issue overfitting in the initial model with obtained.

Now, let's plot the kNN regression with k=142:

####

```{r, echo=FALSE, fig.width= 5, fig.height= 5}
# Perform kNN regression using the 'knn.reg' function with 'SQFT'
# as predictor and 'PRICE' as the response variable, using a k-value of 142
y_pred_knn_reg <-
  knn.reg(
    train = training_df["SQFT"],
    test = training_df["SQFT"],
    y = training_df["PRICE"],
    k = 142
  )

# Create a data frame 'df_knn_reg_w_pred' containing 'SQFT' and predicted
# values 'yhat'
df_knn_reg_w_pred <-
  data.frame(x = training_df["SQFT"], yhat = y_pred_knn_reg$pred)

# Create a ggplot2 scatter plot with regression line
# The red points and lines are for predicted values
graph <- ggplot(training_df, aes(x = SQFT, y = PRICE)) +
  geom_point() +
  geom_point(data = df_knn_reg_w_pred,
             aes(x = SQFT, y = yhat),
             color = "red") +
  geom_line(data = df_knn_reg_w_pred,
            aes(x = SQFT, y = yhat),
            color = "red") +
  labs(
    title = str_wrap("Price vs. Square Footage of Homes
                     with the kNN Regression Line (K=142)", width = 40),
    # Set plot title with word wrap
    x = "Square Footage",  # Set x-axis label
    y = "Price",   # Set y-axis label
  ) +
  theme_minimal() +  # Apply minimal theme
  scale_y_continuous(labels = comma) + # Format y-axis labels with commas
  theme(
    plot.title = element_text(size = 16, face = "bold", hjust = 0.5),
    # Adjust title text size, bold, and center-aligned
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12),
    axis.text = element_text(size = 12),
    panel.border = element_rect(
      color = "black",
      size = 1,
      fill = NA
    ),  # Add rectangular panel border
    axis.ticks = element_line(
      color = "black",
      size = 0.5
    ),  # Add tick marks to x and y axes
    panel.grid.major = element_blank(),  # Remove major gridlines
    panel.grid.minor = element_blank()   # Remove minor gridlines
  )

# Display the graph
ggplotly(graph)

```

As you can see in the new kNN regression fit with `k=142`, the overfitting issue is fixed, specially at the left bottom corner of the scatter plot, where the data points are bunched and very close to each other.

In conclusion, we were able to predict the `PRICE` with the `SQFT` using the kNN regression algorithm. The out-of-sample RMSE predictions shows that the optimal number of nearest neighbor (k) for this regression is 142.

&nbsp;

&nbsp;

&nbsp;

Natural Cubic Spline
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">Natural Cubic Spline</span>

By Mehdi Hasanov

Can we predict `PRICE` with `SQFT` (i.e., square footage)?
In this section, we are trying to find the answer to this question through the model. This model will fit `SQFT` to `PRICE`. As the data seems to fan out it is typically recommended to do a Log transformation of these continuous variables. After applying this transformation the data set was broken up into training and testing data sets (70% and 30%).

####

```{r}
dataset <- dataset[dataset$SQFT != 9, ]
dataset <- dataset[dataset$PRICE != 9, ]
#Price vs SQFT
plot(dataset$SQFT, dataset$PRICE, 
     xlab = "SQFT", 
     ylab = "PRICE",
     main = "Scatter Plot of SQFT vs PRICE")
```
```{r}
#Log vs Log transformation
dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_PRICE <- log(dataset$PRICE)
#Breakup 70 vs 30
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]
```

<span style="font-size: 20px; font-weight: bold;">Train Data</span>

We can fit our model using a range of df to pick the best one (low SSE). We can also visualize this information to make the choice. From this visualization we picked the value 16 for df. While values greater than 16 have a lower SSE the change is mall and we don't want to over fit.

####

```{r}
calc_sse <- function(d_freedom) {
  model_bs <- lm(formula = log_PRICE ~ bs(log_SQFT, df = d_freedom, intercept = TRUE), data = train_data)
  residuals <- model_bs$residuals
  sse <- sum(residuals^2)
  return(sse)
}

results_dataset <- data.frame(d_freedom = 4:19, SSE = 0)

for (d_freedom in 4:19) {
  sse <- calc_sse(d_freedom)
  results_dataset[d_freedom - 3, "SSE"] <- sse
}

```

```{r, echo = FALSE}
graph <- ggplot(results_dataset, aes(x = d_freedom, y = SSE)) +
  geom_line(color = "blue") +
  geom_point(color = "blue") +
  labs(title = "SSE vs. df", x = "d_freedom", y = "SSE")

ggplotly(graph)

best_model <- lm(log_PRICE ~ bs(log_SQFT, df = 16, intercept = TRUE), data = train_data)
```

```{r, echo = FALSE}
plot(train_data$log_SQFT, train_data$log_PRICE, main = "Best Fit (df 16)", xlab = "SQFT", ylab = "PRICE")
lines(sort(train_data$log_SQFT), predict(best_model, newdata = data.frame(log_SQFT = sort(train_data$log_SQFT)), type = "response"), col = "blue")
abline(v = attr(bs(train_data$log_SQFT, df = 16), "knots"), col = "green")
```

<span style="font-size: 20px; font-weight: bold;">Test Data</span>

We can repeat our approach to find a df. From this visualization we picked the value 11 for df. I would say that the approach was definitely somewhat successful, especially since we minimized SSE and looks good on the test set. A;though the shape of the data might not be ideal for this. 

####

```{r, fig.width= 8, fig.height= 8}
results_dataset <- data.frame(d_freedom = 4:19, SSE = 0)

for (d_freedom in 4:19) {
  best_model <- lm(log_PRICE ~ bs(log_SQFT, df = d_freedom, intercept = TRUE), data = test_data)
  predicted_values <- predict(best_model, newdata = test_data, type = "response")
  residuals_dataset <- test_data$log_PRICE - predicted_values
  sse_dataset <- sum(residuals_dataset^2)
  results_dataset[d_freedom - 3, "SSE"] <- sse_dataset
}

```

```{r, echo = FALSE}
graph <- ggplot(results_dataset, aes(x = d_freedom, y = SSE)) +
  geom_line(color = "blue") +
  geom_point(color = "blue") +
  labs(title = "SSE vs. df", x = "d_freedom", y = "SSE")

ggplotly(graph)
```

```{r}
best_model <- lm(log_PRICE ~ bs(log_SQFT, df = 16, intercept = TRUE), data = train_data)
```

```{r, echo = FALSE}
plot(test_data$log_SQFT, test_data$log_PRICE, main = "Best Fit for Test (df 16)", xlab = "SQFT", ylab = "PRICE")
lines(sort(test_data$log_SQFT), predict(best_model, newdata = data.frame(log_SQFT = sort(test_data$log_SQFT)), type = "response"), col = "blue")
abline(v = attr(bs(test_data$log_SQFT, df = 16), "knots"), col = "green")
```
It is hard to comment here. We can visually see the line and where the mean given a QSFT value should be. It seems to be a good estimator, but our data shape makes the SSE feel abnormally big, yet this is still somewhat useful.

Ridge Regression Fit
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">Ridge Regression Fit</span>

by Mohammad Ali Beheshti

In this section, we would like to predict the `PRICE` of a house using all available numerical variables, which are `SQFT` (i.e., square footage), `WEIGHT` (i.e., sample weight), and `WGTADJ` (i.e., weight adjustment), from the data set. We perform the regression on only the observations which have no NA values.

Before we choose any regression model to predict `PRICE`, first, let's run a multiple linear regression (MLR) and check its condition number to see how numerically unstable our estimator is. If the condition number is very high, this indicates that our model matrix is close to be singular, and, therefore, our estimator is numerically unstable. In this situation, we can use a regression method, such as Ridge regression, that uses regularization to make our model matrix full-rank (i.e., non-singular), and, as a result, fix the issue of numerical instability in the estimator. 

So, let's check the condition number of the model matrix for the MLR model. 

```{r}
# Define the model matrix 
newlm <- lm(PRICE ~ SQFT + WEIGHT + WGTADJ, data=dataset2)

# Compute the condition number of the model matrix
kappa( t(model.matrix(newlm)) %*% model.matrix(newlm) )

```

As you can see, the condition number is very high. This indicates that our model matrix is close to be singular and the estimator has the issue of numerical instability. 

To fix this issue, we will use the Ridge regression, which uses Tikhonov regularization. We use R `glmnet` library for the Ridge regression. 

```{r}

# Define response variable
y <- dataset2$PRICE

# Define matrix of predictor variables
x <- data.matrix(dataset2[, c('SQFT', 'WEIGHT', 'WGTADJ')])

# Fit the Ridge regression model
# We choose `alpha = 0` for the Ridge regression. `alpha = 1` will perform a 
# LASSO regression. 
modfit_ridge <- glmnet(x, y, alpha = 0)

summary(modfit_ridge)
``` 

Now, let's perform a k-fold cross validation to find the optimal lambda value for the penalty function of the Ridge regression. 

####

```{r}

# Perform k-fold cross-validation to find optimal lambda value
cv_model <- cv.glmnet(x, y, alpha = 0)

```

```{r, echo = FALSE}
# Produce plot of test MSE by lambda value
plot(cv_model, main = "Mean-Squared Error vs. Log(lambda)") 

```

As you can see in the plot of MSE vs. $log(\lambda)$, the best lambda value (\lambda) is approximately equal to $e^{8.13} \approx 3390.41$: 

```{r}
# Find the optimal lambda value that minimizes test MSE
best_lambda <- cv_model$lambda.min
best_lambda
```

Now, let's compute our Ridge regression model using $\lambda = 3390.41$ and find its regression coefficients.  

```{r}
# Find coefficients of best model
best_modfit_ridge <- glmnet(x, y, alpha = 0, lambda = best_lambda)

# Print the coefficients of the best model 
coef(best_modfit_ridge)
```

In conclustion, due to numerical instability of our estimator in the multiple linear regression model, we decided to use the Ridge regression with $\lambda = 3390.41$ to predict the `PRICE` given `SQFT`, `WEIGHT`, and `WGTADJ` as our predictor variables. The obtained regression equation is: 

$$
\widehat{PRICE} = 15337.99203 + 69.84305 \ SQFT - 497.92052 \ WEIGHT + 28260.08509 \ WGTADJ
$$
&nbsp;

&nbsp;

&nbsp;


Naive Bayes Classification
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">Naive Bayes Classification</span>

by Mehdi Hasanov

Here we will try and answer the following question: Can we predict whether a house is being leased using Naive Bayes Classification?

Once again we start by splitting the data into training and testing data sets. Then we fit the model using all features and examine the coefficient. We found something very interesting when examining the coefficients of the full model. Although by accident. The value 9 represents NA in this data set. Rows with 9 values were originally cleaned out, but those with 9 in the PRICE column were reintroduced here to catch something special. But first note how the model is doing well in some part, but has a huge problem miss classifying when the true value is 2.

```{r, echo=FALSE}
#The data had to be reintroduced intentionally to undo cleaning and transormations
# Load the dataset 
dataset <- read.csv(data_filePath, header = TRUE, check.names = FALSE)

##--------------------
## Cleaning "dataset"
##--------------------

## "SHIPMONTH" Conversion 

# Extract and keep only the month part
dataset$SHIPMONTH <- substr(dataset$SHIPMONTH, 5, 6)

# # Convert the month part to an actual month name (optional)
# dataset$SHIPMONTH <- format(as.Date(paste(df$column_variable, "01", sep = "-"), format = "%Y-%m-%d"), "%B")

# Define a vector of month names
month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Use the month names vector to replace the month numbers
dataset$SHIPMONTH <- month_names[as.integer(dataset$SHIPMONTH)]

#Remove columns
dataset$jbedroom <- NULL
dataset$jfinaldest <- NULL
dataset$jfootings <- NULL
dataset$jlease <- NULL
dataset$jlocation <- NULL
dataset$jpiers <- NULL
dataset$jprice <- NULL
dataset$jsecured <- NULL
dataset$jsqft <- NULL
dataset$jstatus <- NULL
dataset$jtitle <- NULL

#Remove CONTROL
dataset$CONTROL <- NULL

#Remove rows with value 9
dataset <- dataset[dataset$LEASE != 9, ]

#Encode categorical variables as factors
dataset$REGION <- factor(dataset$REGION)
dataset$SHIPMONTH <- factor(dataset$SHIPMONTH)
dataset$SECTIONS <- factor(dataset$SECTIONS)
dataset$STATUS <- factor(dataset$STATUS)
dataset$LEASE <- factor(dataset$LEASE)
dataset$FINALDEST <- factor(dataset$FINALDEST)
dataset$BEDROOMS <- factor(dataset$BEDROOMS)
dataset$TITLED <- factor(dataset$TITLED)
dataset$LOCATION <- factor(dataset$LOCATION)
dataset$FOOTINGS <- factor(dataset$FOOTINGS)
dataset$PIERS <- factor(dataset$PIERS)
dataset$SECURED <- factor(dataset$SECURED)

```

```{r}
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]

nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))
```

<span style="font-size: 20px; font-weight: bold;">PRICENOT9</span>

A natural follow up was to investigate the coefficients. The bellow model table caught my attention. At the time we replaced 9 with median values. We changed our approach and just removed those rows, but in the process something got uncovered. All values where Y is 1 have 9 (NA) for their price. This was obvious due to the variance being zero. Naturally this can be used to easily be used to eliminate some of these classifications. I did have some concern about this approach, since it feels weird to use and NA value in this way, after all this could be over fitting. But from a industry or business analysis stand of point one can argue that such and approach could be useful. It all depends on the application. 
```{r}
nb_model$tables[[11]]
```
So we added a feature that captures this behavior. I called it PRICENOT9. As you can see this greatly improved the accuracy.
```{r}
dataset$PRICENOT9 <- ifelse(dataset$PRICE != 9, 1, 0)
dataset$PRICENOT9 <- factor(dataset$PRICENOT9)
```

```{r}
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]
nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))
```

<span style="font-size: 20px; font-weight: bold;">Less is more</span>

In the end the continuous variables were removed from the model, since after testing several features we saw they didn't contribute much and we didn't want to over fit. The results were amazing, over 90% accuracy at the time when using our initial data cleaning approaches. So I would say the answer to our original question was yes. We can predict whether a house is being leased using Naive Bayes Classification, with extreme accuracy.

Footnote: Originally our data cleaning approach was different, we used medians to replace the 9/NA values and even then the new PRICENOT9 feature won't a perfect collator to LEASE. But as we fixed our cleaning methodology at the very end these new relationships were uncovered. So the initial approach to this model was kept, but updated to give more honesty and transparency. Overall a great learning experience. This approach made a lot more sense before some of the discoveries discussed. As I believed that the PRICE having a certain value was indicative of a certain company and model that was the primary lease provider. Though such a possibility might still exist.

```{r}
nb_model <- naiveBayes(LEASE ~ PRICENOT9, data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))
```

<span style="font-size: 20px; font-weight: bold;">What we should have done</span>

To avoid criticism and demonstrate proper methodology bellow is a proper approach to the problem. Log transformations! Added bellow were the log transformations of some of the continuous features to the data set. Only 98 classifications out of 1252. Great results. Though it is concerning the more than half of the time the model is wrong when prediction a value of 1. Though this is still really good.

```{r, echo=FALSE}
#The data had to be reintroduced intentionally to undo cleaning and transormations
# Load the dataset 
dataset <- read.csv(data_filePath, header = TRUE, check.names = FALSE)

##--------------------
## Cleaning "dataset"
##--------------------

## "SHIPMONTH" Conversion 

# Extract and keep only the month part
dataset$SHIPMONTH <- substr(dataset$SHIPMONTH, 5, 6)

# # Convert the month part to an actual month name (optional)
# dataset$SHIPMONTH <- format(as.Date(paste(df$column_variable, "01", sep = "-"), format = "%Y-%m-%d"), "%B")

# Define a vector of month names
month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Use the month names vector to replace the month numbers
dataset$SHIPMONTH <- month_names[as.integer(dataset$SHIPMONTH)]

#Remove columns
dataset$jbedroom <- NULL
dataset$jfinaldest <- NULL
dataset$jfootings <- NULL
dataset$jlease <- NULL
dataset$jlocation <- NULL
dataset$jpiers <- NULL
dataset$jprice <- NULL
dataset$jsecured <- NULL
dataset$jsqft <- NULL
dataset$jstatus <- NULL
dataset$jtitle <- NULL

#Remove CONTROL
dataset$CONTROL <- NULL

#Remove rows with value 9
dataset <- dataset[dataset$LEASE != 9, ]

#Encode categorical variables as factors
dataset$REGION <- factor(dataset$REGION)
dataset$SHIPMONTH <- factor(dataset$SHIPMONTH)
dataset$SECTIONS <- factor(dataset$SECTIONS)
dataset$STATUS <- factor(dataset$STATUS)
dataset$LEASE <- factor(dataset$LEASE)
dataset$FINALDEST <- factor(dataset$FINALDEST)
dataset$BEDROOMS <- factor(dataset$BEDROOMS)
dataset$TITLED <- factor(dataset$TITLED)
dataset$LOCATION <- factor(dataset$LOCATION)
dataset$FOOTINGS <- factor(dataset$FOOTINGS)
dataset$PIERS <- factor(dataset$PIERS)
dataset$SECURED <- factor(dataset$SECURED)

```

```{r}
dataset$log_WEIGHT <- log(dataset$WEIGHT)
dataset$log_SQFT <- log(dataset$SQFT)
dataset$log_PRICE <- log(dataset$PRICE)
```

```{r}
set.seed(123)
sample_size <- floor(0.7 * nrow(dataset))
train_indices <- sample(1:nrow(dataset), size = sample_size)
train_data <- dataset[train_indices, ]
test_data <- dataset[-train_indices, ]
nb_model <- naiveBayes(LEASE ~ ., data=train_data)
predictions <- predict(nb_model, test_data)
CrossTable(predictions, test_data$LEASE,
prop.chisq = FALSE, prop.t = FALSE, prop.r = FALSE,
dnn = c("predicted", "actual"))
```

Classification using Logistic Reg. 
=======================================================================

### <span style="font-size: 30px; font-weight: bold;">Classification using Logistic Regression</span>

by Mohammad Ali Beheshti

In our dataset, `FINALDEST` is a binary variable that indicates whether a manufactured home is placed at its final destination or not. We would like classify a manufactured home on whether or not it was placed at its final destination using all available numerical variables in the dataset, which are `PRICE`, `SQFT` (i.e., square footage), `WEIGHT` (i.e., sample weight), and `WGTADJ` (i.e., weight adjustment). We use logistic regression to do this classification. For this model, we remove all the observations in our dataset that contain NA values. 

First, let's investigate on the `FINALDEST` variable by taking a look the frequency of its values (levels). A value of `1` means the home was placed at its final destination and a value of `2` means otherwise. 

```{r}
# Create a frequency table
freq_table <- table(dataset2$FINALDEST)

# Display the frequency table
print(freq_table)
```

As you can see, there is no huge difference between the proportion of the two levels. Also, most of the homes were placed at their final destination.   

Now, lets use the stepwise search as the selection method along with the BIC (Bayes information criterion) as the selection criterion to select the best model for our logistic regression. 

```{r, echo=FALSE}
# Convert all 2's (failure value) to 0's. 
dataset2$FINALDEST <- ifelse(dataset2$FINALDEST == 2, 0, dataset2$FINALDEST)
```

```{r}
# Set the seed for reproducibility 
set.seed(123)

# Subset the data into an approximately 70%/30% training/testing split
# Randomly select row indices for the training set (70% of the data)
index <- sample(1:nrow(dataset2), round(nrow(dataset2) * 0.7)) 

# Create the training dataset2 using the selected indices
training_df <- dataset2[index, ]

# Create the testing dataset2 using the remaining indices
testing_df <- dataset2[-index, ]

# Define the null model for the logistic regression 
null <- glm(data = training_df, FINALDEST ~ 1, family = binomial)

# Define the full model for the logistic regression 
full <- glm(data = training_df, FINALDEST ~ PRICE + SQFT + WEIGHT + WGTADJ, family = binomial)

# Use stepwise search to select the best model 
step(null, 
     scope = list(lower = null, upper = full), 
     direction = "both", 
     k = log(nrow(training_df)), trace = 0)
```

As you can see, the best selected model using BIC as the selection criterion happens to only include `WEIGHT`.  

Based on the result we obtained, the following is the logistic regression equation for the selected model: 

$$
\widehat{\eta} = 0.86747 - 0.01849 \ * WEIGHT
$$
Now, let's plot `FINALDEST` vs. `WEIGHT` along with the logistic curve that is obtained from the logistic regression model. 

####

```{r, echo = FALSE}
graph <- ggplot(training_df, aes(x = WEIGHT, y = as.numeric(training_df$FINALDEST))) +
  geom_point(position = position_jitter(height = 0.03, width = 0), size = 0.1) +
  geom_smooth(method = "glm", method.args = list(family = "binomial"), se = F, size = 1.5) +
  geom_hline(yintercept = 0.5) + 
  # geom_vline( xintercept = c(0.86747/0.01849), color = c("blue") ) +
  labs(y = str_wrap("Probability of Manufactured Home Reached Final Dest.", width=30)) + 
  theme_bw()

graph
```

We want to use the logistic regression model we obtained to classify `FINALDEST` (i.e., if a produced house reached its final destination) as "Yes" (1) or "No" (0). 

Now, the question is what would be the value of the decision boundary for `WEIGHT`. The decision boundary is a `WEIGHT` value that. If a produced house has a weight less than the decision boundary, it would be classified as 1 (i.e., reached its final destination) or 0 otherwise. The following is the condition statement for the classification decision-making process: 

$$
\begin{cases}
  \text{0 (did not reach its final destination)} & \text{if } \text{`WEIGHT`} \geq \text{Decision Boundary}, \\
  \text{1 (reached its final destination)} & \text{if } \text{`WEIGHT`} < \text{Decision Boundary}.
\end{cases}
$$
Since we obtained a simple logistic regression model (i.e., a regression model with a single predictor), the decision boundary should be $\geq -\frac{\beta_0}{\beta1}$. Therefore, for this model, the decision boundary should be the weight of $\geq 46.916$. So, let's visualize the decision boudary and a look at the plot of `FINALDEST` vs. `WEIGHT`  with the logistic curve. 

####

```{r, echo = FALSE}
graph <- ggplot(training_df, aes(x = WEIGHT, y = as.numeric(training_df$FINALDEST))) +
  geom_point(position = position_jitter(height = 0.03, width = 0), size = 0.1) +
  geom_smooth(method = "glm", method.args = list(family = "binomial"), se = F, size = 1.5) +
  geom_hline(yintercept = 0.5) + 
  geom_vline( xintercept = c(0.86747/0.01849), color = c("blue") ) +
  labs(y = str_wrap("Probability of Manufactured Home Reached Final Dest.", width=30)) + 
  theme_bw()

ggplotly(graph)
```

As you can see in the plot, the decision boundary happened to approximately intersect with the threshold of 0.5 or 50 percent in the probability of `FINALDEST` on the y-axis. So, we will use the threshold of 0.5 to classify our data points. Any data point with the probability of 0.5 or greater will be classified as "true" for the `FINALDEST`. 

Now, let's define the best model using logistic regression, and compute the predicted probabilities for the `FINALDEST` using the best model we obtained from the logistic regression. 

```{r}
# Define the best fitted model we obtained 
modfit_best <- glm(data = training_df, FINALDEST ~ WEIGHT, family = binomial)

# Compute the predicted values for the training dataset using the best fitted model 
pihat_train <- predict(modfit_best, 
                       newdata = training_df,
                       type = "response")

```

Next, we classify all the predicted values for the `FINALDEST` using a threshold of 70 percent. That being said, any `FINALDEST` that has a probability of more than 70 percent, will be classified as "Yes" or "reached the final destination", and any  `FINALDEST` that has a probability of 70 percent or less, will be classified as "No" or "did not reached the final destination."

```{r}
# Define the threshold
threshold <- 0.50

# Categorize all the predicted values for the training dataset to the binary values of yes and no 
training_predicted_category <- factor( ifelse(pihat_train > threshold, "Yes", "No") )

# Convert all the `FINALDEST` binary values to `Yes` and `No` instead of 1 and 0
reference_training <- factor( ifelse(training_df$FINALDEST == 1, "Yes", "No") )

```

Now, let's look at the in-sample misclassification rate and see how well our best model from the logistic regression classified the data: 

```{r}
# Average Misclassification Rate
mean((as.numeric(training_df$FINALDEST)-1) != (pihat_train > 0.70))

```

With a threshold of 70 percent, we have a misclassification rate of about 43%, which is high and not good. 70 percent is the best threshold value we can choose. This high misclassification rate makes sense since if you look at the last plot; the majority of the manufactured homes reached their destination no matter how heavy their weight. 

Now, let's look at the confusion matrix for the in-sample classification:  

```{r}
# Construct the confusion matrix for the in-sample classification
confusionMatrix(data = training_predicted_category,
                reference = (reference_training))
```

As the confusion matrix for the training data shows, the in-sampele accuracy rate is about 40 percent, which is very low. A high number of houses were falsely predicted that they did reached their destination, but they did.

Finally, let's look at the out-of-sample misclassification rate: 

```{r}
# Compute the predicted values for the testing dataset using the best fitted model 
pihat_test <- predict(modfit_best, 
                       newdata = testing_df,
                       type = "response")

# Categorize all the predicted values for the testing dataset to the binary values of yes and no 
testing_predicted_category <- factor( ifelse(pihat_test > threshold, "Yes", "No") )

# Average Misclassification Rate
mean((as.numeric(testing_df$FINALDEST)-1) != (pihat_test > 0.70))
```

If we set the threshold to 70 percent, we have a misclassification rate of about 43%, which is close to what we get for the training dataset. This indicates that our model at least did a good job for out-of-sample classification. 

Now, let's look at the confusion matrix for the out-of-sample classification:   

```{r}
# Convert all the `FINALDEST` binary values to `Yes` and `No` instead of 1 and 0
reference_testing <- factor( ifelse(testing_df$FINALDEST == 1, "Yes", "No") )

# Construct the confusion matrix for the out-of-sample classification
confusionMatrix(data = testing_predicted_category,
                reference = (reference_testing))
```

As the confusion matrix for the testing data shows, the out-of-sample accuracy rate is about 37 percent, which is, again, very low. A high number of houses were falsely predicted that they did reached their destination, but they did.

In conclusion, were  able to classify the `FINALDEST` of an observation using `SQFT` and `WEIGHT` with a very low in-sample and out-of-sample accuracy rate of about 40 percent using the logistic regression approach. 

&nbsp;

&nbsp;

&nbsp;

About Our Team
=======================================================================
## Column 1 {data-width==500}

### <span style="font-size: 30px; font-weight: bold;">About Our Team</span>

This is Mohammad-Ali and Mehdi from Virginia Tech. We are senior undergraduate students, majoring in Computational Modeling and Data Analytics (CMDA). We are both taking the "Intermediate Data Analysis and Machine Learning" (CMDA 4654) course with Dr. Christian Lucero this semester, and we decided to work on this data science project together. 

Here is more about each of us: 

## Column 2 {data-width==500}

### <span style="font-size: 30px; font-weight: bold;">Mohammad-Ali Beheshti</span>

I am is originally from Tehran, Iran. I am perusing my bachelors in Computational Modeling and Data Analytics (CMDA) with a minor in Computer Science and a minor in Environmental Horticulture. My favorite pastime is group workout.

Email: mohab14@vt.edu

### <span style="font-size: 30px; font-weight: bold;">Mehdi Hasanov</span>
I am originally from Baku, Azerbaijan. I am perusing my bachelors in Computational Modeling and Data Analytics (CMDA). My favorite pastime is hiking.

Email: mhasanov@vt.edu