# R Neural Network

**Data Science, Data Mining and Predictive Analytics**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In the previous four posts I have used multiple linear regression, decision trees, random forest, gradient boosting, and support vector machine to predict MPG for 2019 vehicles. It was determined that svm produced the best model. In this post I am going to use the neuralnet package to fit a neural network to the cars_19 dataset.

The raw data is located on the EPA government site.

Similar to the other models, the variables/features I am using are: Engine displacement (size), number of cylinders, transmission type, number of gears, air inspired method, regenerative braking type, battery capacity Ah, drivetrain, fuel type, cylinder deactivate, and variable valve. Unlike the other models, the neuralnet package does not handle factors so I will have to transform them into dummy variables. After creating the dummy variables, I will be using 27 input variables.

The data which is all 2019 vehicles which are non pure electric (1253 vehicles) are summarized in previous posts below.

str(cars_19)<br />'data.frame': 1253 obs. of 12 variables:<br /> $ fuel_economy_combined: int 21 28 21 26 28 11 15 18 17 15 ...<br /> $ eng_disp : num 3.5 1.8 4 2 2 8 6.2 6.2 6.2 6.2 ...<br /> $ num_cyl : int 6 4 8 4 4 16 8 8 8 8 ...<br /> $ transmission : Factor w/ 7 levels "A","AM","AMS",..: 3 2 6 3 6 3 6 6 6 5 ...<br /> $ num_gears : int 9 6 8 7 8 7 8 8 8 7 ...<br /> $ air_aspired_method : Factor w/ 5 levels "Naturally Aspirated",..: 4 4 4 4 4 4 3 1 3 3 ...<br /> $ regen_brake : Factor w/ 3 levels "","Electrical Regen Brake",..: 2 1 1 1 1 1 1 1 1 1 ...<br /> $ batt_capacity_ah : num 4.25 0 0 0 0 0 0 0 0 0 ...<br /> $ drive : Factor w/ 5 levels "2-Wheel Drive, Front",..: 4 2 2 4 2 4 2 2 2 2 ...<br /> $ fuel_type : Factor w/ 5 levels "Diesel, ultra low sulfur (15 ppm, maximum)",..: 4 3 3 5 3 4 4 4 4 4 ...<br /> $ cyl_deactivate : Factor w/ 2 levels "N","Y": 1 1 1 1 1 2 1 2 2 1 ...<br /> $ variable_valve : Factor w/ 2 levels "N","Y": 2 2 2 2 2 2 2 2 2 2 ...<br />

First I need to normalize all the non-factor data and will use the min max method:

maxs <- apply(cars_19[, c(1:3, 5, 8)], 2, max)<br />mins <- apply(cars_19[, c(1:3, 5, 8)], 2, min)<br /><br />scaled <- as.data.frame(scale(cars_19[, c(1:3, 5, 8)], center = mins, scale = maxs - mins))<br />tmp <- data.frame(scaled, cars_19[, c(4, 6, 7, 9:12)])<br />

Neuralnet will not accept a formula like

**fuel_economy_combined ~.**so I need to write out the full model.

n <- names(cars_19)<br />f <- as.formula(paste("fuel_economy_combined ~", paste(n[!n %in% "fuel_economy_combined"], collapse = " + ")))<br />

Next I need to transform all of the factor variables into binary dummy variables.

m <- model.matrix(f, data = tmp)<br />m <- as.matrix(data.frame(m, tmp[, 1]))<br />colnames(m)[28] <- "fuel_economy_combined")<br />

I am going to use the geometric pyramid rule to determine the amount of hidden layers and neurons for each layer. The general rule of thumb is if the data is linearly separable, use one hidden layer and if it is non-linear use two hidden layers. I am going to use two hidden layers as I already know the non-linear svm produced the best model.

r = (INP_num/OUT_num)^(1/3)<br />HID1_num = OUT_num*(r^2) #number of neurons in the first hidden layer <br />HID2_num = OUT_num*r #number of neurons in the second hidden layer<br />

This suggests I use two hidden layers with 9 neurons in the first layer and 3 neurons in the second layer. I originally fit the model with this combination but it turned out to overfit. As this is just a suggestion, I found that two hidden layers with 7 and 3 neurons respectively produced the best neural network that did not overfit.

Now I am going to fit a neural network:

set.seed(123)<br />indices <- sample(1:nrow(cars_19), size = 0.75 * nrow(cars_19))<br />train <- m[indices,]<br />test <- m[-indices,]<br /><br />n <- colnames(m)[2:28]<br />f <- as.formula(paste("fuel_economy_combined ~", paste(n[!n %in% "fuel_economy_combined"], collapse = " + ")))<br />m1_nn <- neuralnet(f,<br /> data = train,<br /> hidden = c(7,3),<br /> linear.output = TRUE)<br /><br />pred_nn <- predict(m1_nn, test)<br /><br />yhat <-pred_nn * (max(cars_19$fuel_economy_combined) - min(cars_19$fuel_economy_combined)) + min(cars_19$fuel_economy_combined)<br />y <- test[, 28] * (max(cars_19$fuel_economy_combined) - min(cars_19$fuel_economy_combined)) +min(cars_19$fuel_economy_combined)<br />

postResample(yhat, y)<br /> RMSE Rsquared MAE <br />2.0036294 0.8688363 1.4894264 <br /><br />

I am going to run a 20 fold cross validation to estimate error better as these results are dependent on sample and initialization of the neural network.

set.seed(123)<br />stats <- NULL<br /><br />for (i in 1:20) {<br /> indices <- sample(1:nrow(cars_19), size = 0.75 * nrow(cars_19))<br /> train_tmp <- m[indices, ]<br /> test_tmp <- m[-indices, ]<br /> <br /> nn_tmp <- neuralnet(f,<br /> data = train_tmp,<br /> hidden = c(7, 3),<br /> linear.output = TRUE)<br /> <br /> pred_nn_tmp <- predict(nn_tmp, test_tmp)<br /> <br /> yhat <- pred_nn_tmp * (max(cars_19$fuel_economy_combined) - min(cars_19$fuel_economy_combined)) + min(cars_19$fuel_economy_combined)<br /> y <- test_tmp[, 28] * (max(cars_19$fuel_economy_combined) - min(cars_19$fuel_economy_combined)) + min(cars_19$fuel_economy_combined)<br /> stats_tmp <- postResample(yhat, y)<br /> stats <- rbind(stats, stats_tmp)<br /> cat(i, "\n")<br />}<br />

mean(stats[, 1] ^ 2) #avg mse 4.261991<br />mean(stats[, 1] ^ 2) ^ .5 #avg rmse 2.064459<br /><br />colMeans(stats) #ignore rmse<br />#RMSE Rsquared MAE <br />#xxx 0.880502 1.466458 <br /><br />

The neural network produces a RMSE of 2.06.

Comparison of RMSE:<br /><br />svm = .93<br />gradient boosting = 1.8<br />random forest = 1.9<br />neural network = 2.06<br />decision tree = 2.49<br />mlr = 2.6<br />

**leave a comment**for the author, please follow the link and comment on their blog:

**Data Science, Data Mining and Predictive Analytics**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.