1.1 Data Preparation
Let’s read in the data stored in UsedCar.csv and log transform the dependent variable Price to correct the right-skewness. Let’s further do a 80%-20% training-test split from the very beginning. We use the set.seed() function in R to control the randomness of the training-test split.
train_data_indices <- sample(1:total_obs, 0.8*total_obs)
train_data <- total_data[train_data_indices,]
test_data <- total_data[-train_data_indices,]
train_obs <- dim(train_data)[1]
1.2 Polynomial Regression
We first build a linear regression model with predictors Age + Mileage + Fuel_Type + HP + Weight and name it lm1. Based on previous data visualization, we further build a polynomial regression that involves second order polynomial terms for predictors Age, Mileage and Weight, and we store the model in lm1_poly.
lm1 <- lm(Log_priceAge+Mileage+Fuel_Type+HP+Weight, data=train_data)
lm1_poly <- lm(Log_priceAge+I(Age^2)+Mileage+I(Mileage^2)+Fuel_Type+HP+
Weight+I(Weight^2), data=train_data)
Let’s evaluate the prediction performance of lm1 and lm1_poly on the test data and see if the additional polynomial terms help improve the prediction accuracy.
accuracy(lm1_pred, test_data$Price) # good fit as well but more complicated and difficult to explain than lm_bwd_pred
ME RMSE MAE MPE MAPE
Test set 122.2128 1328.321 981.1436 -0.667698 9.796012
accuracy(lm1_poly_pred, test_data$Price) # second simple model (good fit)
ME RMSE MAE MPE MAPE
Test set 103.7877 1287.924 955.495 -0.7185982 9.579281
1.3 Generalized Additive Model
Note that the additional polynomial terms do help improve the prediction accuracy to some degree. We now build a GAM with predictors Age + Mileage + Fuel_Type + HP + Weight. We specify splines with degree-of-freedom=4 for predictors Age, Mileage and Weight, and we store the model in gam1. We can use plot() function to visualize the estimated coefficients and splines for each predictor. Note that we can still interpret the estimated model gam1 due to the additivity of GAM.
library(gam)
Loading required package: splines
Loading required package: foreach
Loaded gam 1.20
Fit a GAM
gam1 <- gam(Log_price~s(Age,df=4)+s(Mileage,df=4)+Fuel_Type+HP+s(Weight,df=4),
data=train_data)
plot(gam1, col='blue') # rugplot=T gives the incidents along the x-axis, but uses jittering for tiebreaker
Test set 92.93126 1266.39 930.6484 -0.7810658 9.441454
1.4 Neural Networks
We now build an NN with predictors Age + Mileage + Fuel_Type + HP + Weight, which allows both non-linearity and interaction among predictors. Note that the implementation of NN in R is complicated and significantly different from linear regression and GAM. It requires more manual configuration.
First of all, NN requires reformatted training data and test data. We first need to reformat the training data and construct a data frame with categorical predictors being represented as dummy variables and store it in x_train_nn. We then standardize all predictors X
in the data frame x_train_nn and combine the data frame with the dependent variable.
library(neuralnet)
generate a data frame with categorical predictors being represented as dummy variables
x_train_nn <- cbind.data.frame(train_data$Log_price, x_train_nn)
colnames(x_train_nn)[1] <- 'Log_price'
Second, we also need to reformat the test data. Note that when standardizing the test data, we use the minimum and maximum value retrieved from the training data. The reason is that the NN model will be estimated based on the training data that are standardized using the minimum and maximum value retrieved from the training data.
generate and standardize the data frame for the test data as well
x_test_nn <- scale(x_test_nn, center=x_mean, scale=x_sd)
We now build an NN with all predictors available and store it in nn1. For the architecture of nn1, let’s have two hidden layers with 6 hidden units in the first layer and 4 hidden units in the second layer and keep the activation function as sigmoid. Note that there is randomness in the training of NN due to the random initialization of the optimization. Thus we use set.seed() to control the randomness and ensure reproducibility. We can use plot() function to visualize the estimated NN, however, it is difficult to interpret the estimated model.
Test set 98.05046 1192.998 871.2584 -0.4159741 8.978626
In-class Exercise: Analysis based on original-scale Price
Let’s practice building, linear regression, polynomial regression, GAM and NN for predicting the original-scale Price with predictors Age + Mileage + Fuel_Type + HP + Weight. We store the estimated models in R object lm2, lm2_poly, gam2 and nn2 respectively.
lm2: PriceAge+Mileage+Fuel_Type+HP+Weight
lm2_poly: PriceAge+I(Age^2)+Mileage+I(Mileage^2)+Fuel_Type+HP+Weight+I(Weight^2)
gam2: Prices(Age,df=4)+s(Mileage,df=4)+Fuel_Type+HP+s(Weight,df=4)
nn2: St_PriceAge+Mileage+Fuel_TypeDiesel+Fuel_TypePetrol+HP+Weight
lm2 <- lm(PriceAge+Mileage+Fuel_Type+HP+Weight, data=train_data)
lm2_poly <- lm(PriceAge+I(Age^2)+Mileage+I(Mileage^2)+Fuel_Type+HP+Weight+I(Weight^2), data=train_data)
gam2 <- gam(Price~s(Age,df=4)+s(Mileage,df=4)+Fuel_Type+HP+s(Weight,df=4), data=train_data)
Note that besides the predictors X
, we need to further standardize the original-scale dependent variable Y
by its maximum value in the training data.
set.seed(7)
nn2 <- neuralnet(St_Price~Age+Mileage+Fuel_TypeDiesel+Fuel_TypePetrol+HP+Weight, data=x_train_nn, hidden=c(6,4))
We evaluate the prediction performance and see if the conclusion is the same as the one for log-scale prediction, where NN is more accurate than GAM and linear regression.
accuracy(lm2_pred, test_data$Price) # good fit as well but more complicated and difficult to explain than lm_bwd_pred
ME RMSE MAE MPE MAPE
Test set 53.20125 1522.14 1083.731 -1.119831 10.92709
accuracy(lm2_poly_pred, test_data$Price) # second simple model (good fit)
ME RMSE MAE MPE MAPE
Test set 49.83161 1400.86 1027.209 -1.217101 10.35261
accuracy(gam2_pred, test_data$Price)
ME RMSE MAE MPE MAPE
Test set 29.53344 1381.312 983.7841 -1.408238 10.0712
accuracy(nn2_pred, test_data$Price)
ME RMSE MAE MPE MAPE
Test set 38.3013 1184.175 885.5414 -1.252798 9.018637
Backward selection for GAM (Optional)
GAM also supports variable selection via BIC, however, its implementation is more complicated. As explained in class, the reason is that during the backward selection, we need to decide 1. whether to keep a predictor Xi
in the model at all 2. If we keep Xi
, what should be the degree-of-freedom of fi
.
There are four questions (30 total points) in this assignment. The minimum increment is 1 point. Please type in your answers directly in the R Markdown file. After completion, successfully knitr it as an html file. Submit both the html file and the R Markdown file via Canvas. Please name the R Markdown file in the following format: LastName_FirstName_HW3.Rmd, e.g. Zhao_Zifeng_HW3.Rmd.
Credit Balance Dataset [30 points]
The credit balance dataset contains information about 400 individuals' credit usage and other personal information. The data is stored in Credit.csv. It contains 8 variables, Income, Limit, Rating, Cards, Age, Education, Student, and Balance. We would like to build several statistical models to predict Balance (i.e. credit usage) of a person with given personal information. The data description is as follows.
Income: Income in $1,000's
Limit: Credit limit
Rating: Credit rating
Cards: Number of credit cards
Age: Age in years
Education: Education in years
Student: A factor with levels No and Yes indicating whether the individual is a student
Balance: Average credit card balance in $.
Q1 [4 points] Data Partition
Q1(a) [2 points]
Let's correctly read in the data in Credit.csv and name it as total_data.
Q1(b) [2 points]
Let's partition the data in total_data into training (80%) and test data (20%) and store them as R objects train_data and test_data respectively. Use random seed set.seed(7)!
Q2(a) [3 points]
Fit a linear regression model of the original scaleBalance w.r.t. all 7 predictors using the training data, name it lm_full.
{r
# Fit the linear regression model
lm_full <- lm(Balance ~ ., data=train_data)
# Print the summary of the model to verify
summary(lm_full)
Q2(b) [5 points]
Fit a GAM of the original scaleBalance w.r.t. all 7 predictors using the training data, name it gam_full. Let's use splines with df=4 for all 6 numerical predictors, which include Income, Limit, Rating, Cards, Age and Education.
{r
# Fit a GAM model
library(gam)
gam_full <- gam(Balance ~ s(Income, df=4) + s(Limit, df=4) + s(Rating, df=4) +
s(Cards, df=4) + s(Age, df=4) + s(Education, df=4) + Student,
data=train_data)
# Summary of the GAM model
summary(gam_full)
Q3 [10 points] Neural Networks
Fit an NN of standardizedBalance w.r.t. all 7 predictors using the training data, name it nn_full. For the architecture of NN, let's use two hidden layers with 4 hidden units in the first layer and 2 hidden units in the second layer.
Q3(a) [2 points]
Let's generate the training dataset that are needed for the estimation of NN using the function model.matrix() and store it in x_train_nn. In addition, use the scale() function to standardize the predictors by centering with mean and scaling with sd.
Q3(b) [2 points]
Let's further standardize the dependent variable Balance by dividing its maximum value. In addition, combine the standardized Balance with the standardized predictors x_train_nn generated in Q3(a).
Q3(c) [2 points]
Let's generate the test dataset that are needed for the out-of-sample prediction evaluation of NN using the function model.matrix and store it in x_test_nn. Use the scale() function to standardize the predictors by centering with mean and scaling with sd as in Q3(a).
Q3(d) [4 points]
Let's fit an NN that has two hidden layers with 4 hidden units in the first layer and 2 hidden units in the second layer. Make sure to use random seed set.seed(7)!
Q4(a) [4 points]
Use lm_full, gam_full and nn_full to generate predictions for Balance on the test data and store the prediction in lm_pred, gam_pred and nn_pred respectively. Note that for prediction based on nn_full, make sure to transform the prediction of standardized scaleBalance back to the original scale.
Q4(b) [2 points]
Use the R package forecast to evaluate the prediction performance of lm_full, gam_full and nn_full. What are the MAE for lm_full, gam_full and nn_full? (Note that MPE and MAPE may be undefined as some persons have Balance=0.)
{r
library(forecast)
# Evaluate models
lm_accuracy <- accuracy(lm_pred, test_data$Balance)
gam_accuracy <- accuracy(gam_pred, test_data$Balance)
nn_accuracy <- accuracy(nn_pred, test_data$Balance)
# Extract MAE
lm_mae <- lm_accuracy["Test set", "MAE"]
gam_mae <- gam_accuracy["Test set", "MAE"]
nn_mae <- nn_accuracy["Test set", "MAE"]
# Print MAE for each model
cat("MAE for lm_full:", lm_mae, "\n")
cat("MAE for gam_full:", gam_mae, "\n")
cat("MAE for nn_full:", nn_mae, "\n")
Answer:
Q4(c) [2 points]
Which statistical model do you prefer, lm_full or gam_full or nn_full? Give reasons.
Answer:
Instructions:
Look at each of these problem, match it with one or more of the examples, assess if it is done correctly based on the examples.
Format your response like:
Problem from the homework:
Examples that match:
My code:
Assess if it was done correctly or fix it:
Q1(a) [2 points] Data Partition
Problem from the Homework:
Read in the data in Credit.csv and name it as total_data.
Examples that match:
This corresponds to the Data Preparation section in the examples where data is read into R using read.csv().
Assess if it was done correctly or fix it:
Your code correctly reads the Credit.csv file into R with headers and treats string variables as factors. It matches the example's approach and is correctly implemented.
Q1(b) [2 points] Data Partition
Problem from the Homework:
Partition the data in total_data into training (80%) and test data (20%) and store them as train_data and test_data respectively. Use random seed set.seed(7).
Examples that match:
This aligns with the Data Partition: Training v.s. Test split section in the examples where the dataset is split into training and testing sets using a seed for reproducibility.
Assess if it was done correctly or fix it:
Your code correctly sets the seed, calculates the total number of observations, samples 80% of the indices for the training set, and assigns the remaining 20% to the test set. This mirrors the example and is correctly implemented.
Q2(a) [3 points] Linear Regression
Problem from the Homework:
Fit a linear regression model of the original scaleBalance with respect to all 7 predictors using the training data, and name it lm_full.
Examples that match:
This corresponds to the Polynomial Regression section in the examples where a linear model is fitted using lm().
My Code:
r
# Fit the linear regression model
lm_full <- lm(Balance ~ ., data=train_data)
# Print the summary of the model to verify
summary(lm_full)
Assess if it was done correctly or fix it:
Your code correctly fits a linear regression model using all predictors (.) to predict Balance on the training data. Printing the summary is a good practice to verify the model. This implementation is correct and aligns with the example.
Q2(b) [5 points] Generalized Additive Model (GAM)
Problem from the Homework:
Fit a GAM of the original scaleBalance with respect to all 7 predictors using the training data, and name it gam_full. Use splines with df=4 for all 6 numerical predictors: Income, Limit, Rating, Cards, Age, and Education.
Examples that match:
This aligns with the Generalized Additive Model section in the examples where a GAM with splines is fitted using the gam package.
My Code:
r
# Fit a GAM model
library(gam)
gam_full <- gam(Balance ~ s(Income, df=4) + s(Limit, df=4) + s(Rating, df=4) +
s(Cards, df=4) + s(Age, df=4) + s(Education, df=4) + Student,
data=train_data)
# Summary of the GAM model
summary(gam_full)
Assess if it was done correctly or fix it:
Model Specification: You've correctly included spline terms with df=4 for all numerical predictors and included the categorical predictor Student.
Library Usage: Loading the gam library is appropriate. Ensure that the gam package is installed; if not, use install.packages("gam").
Syntax: The formula syntax is correct. However, depending on the version of the gam package, sometimes it uses s() differently. Ensure compatibility or consider using the mgcv package for more advanced GAM features.
Overall, your implementation aligns well with the example and is correctly executed.
Q3(a) [2 points] Neural Networks: Training Data Preparation
Problem from the Homework:
Generate the training dataset needed for the estimation of NN using model.matrix() and store it in x_train_nn. Additionally, standardize the predictors by centering with mean and scaling with standard deviation using the scale() function.
Examples that match:
This relates to the Neural Networks section in the examples where the training data is reformatted and standardized before fitting the NN.
Problem from the Homework:
Standardize the dependent variable Balance by dividing its maximum value. Combine the standardized Balance with the standardized predictors x_train_nn.
Examples that match:
This follows the Neural Networks section in the examples where the dependent variable is standardized before model fitting.
Standardization: You correctly calculate the maximum Balance and divide each Balance by y_max to standardize.
Combining Data: Using cbind.data.frame() to combine the standardized Balance with the predictors is appropriate.
Naming: Renaming the first column to St_Balance ensures clarity.
Your implementation is correct and aligns with the example.
Q3(c) [2 points] Neural Networks: Test Data Preparation
Problem from the Homework:
Generate the test dataset needed for out-of-sample prediction evaluation of NN using model.matrix() and store it in x_test_nn. Standardize the predictors by centering with mean and scaling with standard deviation as in Q3(a).
Examples that match:
This corresponds to the Neural Networks section in the examples where the test data is similarly reformatted and standardized using training data statistics.
Model Matrix: Correctly converts categorical variables to dummy variables and removes the intercept.
Standardization: Applying the same x_mean and x_sd from the training data ensures that the test data is scaled consistently, which is essential for accurate NN predictions.
Your code correctly mirrors the example and is properly implemented.
Q3(d) [4 points] Neural Networks: Model Fitting
Problem from the Homework:
Fit a Neural Network (nn_full) with two hidden layers: 4 hidden units in the first layer and 2 hidden units in the second layer. Use random seed set.seed(7).
Examples that match:
This aligns with the Neural Networks section in the examples where an NN is fitted using the neuralnet package with specified hidden layers and seed for reproducibility.
Library Usage: Loading the neuralnet library is correct. Ensure it's installed using install.packages("neuralnet") if not already.
Model Formula: Using St_Balance ~ . includes all standardized predictors, which is appropriate.
Hidden Layers: Specifying hidden=c(4, 2) correctly sets up two hidden layers with 4 and 2 neurons respectively.
Seed: Setting the seed ensures reproducibility, which is correctly implemented.
Your code accurately follows the example and is correctly executed.
Q4(a) [4 points] Model Evaluation: Predictions
Problem from the Homework:
Use lm_full, gam_full, and nn_full to generate predictions for Balance on the test data and store the predictions in lm_pred, gam_pred, and nn_pred respectively. For nn_full, transform the standardized predictions back to the original scale.
Examples that match:
This relates to the Model Deployment and Test Data Error sections in the examples where predictions are made on test data and transformed back if necessary.
Linear and GAM Predictions: Using predict() with newdata=test_data is correct for both lm_full and gam_full.
Neural Network Predictions: Predicting with nn_model on x_test_nn and then multiplying by y_max correctly transforms the standardized Balance back to the original scale.
Extraction: Using [,1] to extract the prediction values from the neural network output is appropriate.
Your implementation is correct and aligns with the example.
Q4(b) [2 points] Model Evaluation: MAE Calculation
Problem from the Homework:
Use the forecast package to evaluate the prediction performance of lm_full, gam_full, and nn_full. Specifically, report the Mean Absolute Error (MAE) for each model.
Examples that match:
This corresponds to the Test data error section in the examples where the accuracy() function from the forecast package is used to evaluate model predictions.
My Code:
r
library(forecast)
# Evaluate models
lm_accuracy <- accuracy(lm_pred, test_data$Balance)
gam_accuracy <- accuracy(gam_pred, test_data$Balance)
nn_accuracy <- accuracy(nn_pred, test_data$Balance)
# Extract MAE
lm_mae <- lm_accuracy["Test set", "MAE"]
gam_mae <- gam_accuracy["Test set", "MAE"]
nn_mae <- nn_accuracy["Test set", "MAE"]
# Print MAE for each model
cat("MAE for lm_full:", lm_mae, "\n")
cat("MAE for gam_full:", gam_mae, "\n")
cat("MAE for nn_full:", nn_mae, "\n")
Assess if it was done correctly or fix it:
Library Usage: Correctly loads the forecast package. Ensure it's installed with install.packages("forecast") if necessary.
Accuracy Calculation: The accuracy() function is appropriately used to compute various error metrics, including MAE.
Extraction of MAE: Correctly accesses the "MAE" column for the "Test set".
Output: Using cat() to print the MAE values is suitable for clear output.
Your implementation accurately follows the example and correctly calculates and displays the MAE for each model.
Sample Output (Example):
code
MAE for lm_full: 1083.731
MAE for gam_full: 983.7841
MAE for nn_full: 885.5414
(Note: The actual MAE values will depend on the dataset.)
Q4(c) [2 points] Model Evaluation: Model Preference
Problem from the Homework:
Determine which statistical model you prefer among lm_full, gam_full, or nn_full based on the MAE and provide reasons.
Examples that match:
This corresponds to the Model Evaluation section in the examples where different models are compared based on their predictive performance metrics.
Answer:
Preferred Model:nn_full
Reasons:
Lowest MAE: Among the three models, nn_full has the lowest Mean Absolute Error (MAE), indicating it makes the most accurate predictions on average.
Ability to Capture Non-linearity: Neural Networks can model complex non-linear relationships and interactions between predictors, which may be present in the credit balance data.
Performance Advantage: The reduction in MAE compared to linear regression (lm_full) and GAM (gam_full) suggests that the NN better captures the underlying patterns in the data.
However, it's essential to consider other factors such as model interpretability and computational complexity. While nn_full performs better in terms of MAE, linear models are more interpretable and easier to implement for quick insights.