There are several Artificial Neural Network (ANN) packages in R including nnet, neuralnet, and RSNNS.
# simulate data
set.seed(1)
x1=rnorm(1000)
x2=rnorm(1000)
x3=rnorm(1000)
y=10 + 2*x1 -5*x2 +4*x3 + 3*x1*x2 - 8*x1*x3 + 2*x2*x3 + 5*x1*x2*x3 + rnorm(1000)
df <- tibble(y,x1,x2,x3)# ANN single hidden layer, activation=identity
set.seed(12345)
nnet0 <- neuralnet(y ~ x1 + x2 + x3, data=df, act.fct = identity)
summary(nnet0)## Length Class Mode
## call 4 -none- call
## response 1000 -none- numeric
## covariate 3000 -none- numeric
## model.list 2 -none- list
## err.fct 1 -none- function
## act.fct 1 -none- function
## linear.output 1 -none- logical
## data 4 data.frame list
## exclude 0 -none- NULL
## net.result 1 -none- list
## weights 1 -none- list
## generalized.weights 1 -none- list
## startweights 1 -none- list
## result.matrix 9 -none- numeric
## [,1]
## error 5.813582e+04
## reached.threshold 9.925809e-03
## steps 7.300000e+01
## Intercept.to.1layhid1 -1.956515e+00
## x1.to.1layhid1 -7.007103e-01
## x2.to.1layhid1 1.372216e+00
## x3.to.1layhid1 -1.183926e+00
## Intercept.to.y 3.147931e+00
## 1layhid1.to.y -3.293998e+00
OLS estimation of linear regression produces:
##
## Call:
## lm(formula = y ~ x1 + x2 + x3, data = df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -82.817 -3.772 0.501 3.891 80.819
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 9.5927 0.3418 28.067 < 2e-16 ***
## x1 2.3081 0.3307 6.979 5.41e-12 ***
## x2 -4.5201 0.3288 -13.748 < 2e-16 ***
## x3 3.8998 0.3320 11.746 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 10.8 on 996 degrees of freedom
## Multiple R-squared: 0.274, Adjusted R-squared: 0.2718
## F-statistic: 125.3 on 3 and 996 DF, p-value: < 2.2e-16
Standardize variables into 0-1 interval:
# scale function
scale1 <- function(x){
(x - min(x)) / (max(x) - min(x))
}
#
dfs <- df |>
mutate_all(scale1)Train-test split:
# %75 train %25 test
set.seed(555)
train_id <- sample(1000, 750)
dfs_train <- dfs[train_id, ]
dfs_test <- dfs[-train_id, ]# single neuron, single layer, default act.fct = "logistic" (i.e., sigmoid)
nnet1 <- neuralnet(y ~ x1 + x2 + x3, data = dfs_train)
plot(nnet1, rep = "best")# single layer 2 neurons
nnet2 <- neuralnet(y ~ x1 + x2 + x3, data=dfs_train, hidden=2)
plot(nnet2, rep = "best")# 3 neurons
nnet3 <- neuralnet(y ~ x1 + x2 + x3, data=dfs_train, hidden=3)
plot(nnet3, rep = "best")# 2 hidden layers with 3 neurons each
# relu <- function(x) {max(0,x)}
nnet4 <- neuralnet(y ~ x1 + x2 + x3,
data = dfs_train,
hidden = c(3,3))
plot(nnet4, rep = "best")Test MSE from nnet4:
pred_nnet4 <- predict(nnet4, newdata = dfs_test)
mse_nnet4 <- mean((dfs_test$y - pred_nnet4)^2)
mse_nnet4## [1] 0.001518029
Test MSE from linear regression:
linreg <- lm(y ~ x1 + x2 + x3, data = dfs_train)
pred_linreg <- predict(linreg, newdata = dfs_test)
mse_linreg <- mean((dfs_test$y - pred_linreg)^2)
mse_linreg## [1] 0.006065131
Test MSE from the linear regression is larger than the test MSE from the ANN with two layers with 3 neurons (nnet4).
Let’s add interaction terms to the linear regression:
##
## Call:
## lm(formula = y ~ x1 * x2 * x3, data = dfs_train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.020642 -0.004792 -0.000036 0.004676 0.020356
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.97289 0.00915 -106.33 <2e-16 ***
## x1 3.50947 0.02059 170.41 <2e-16 ***
## x2 1.45794 0.01867 78.09 <2e-16 ***
## x3 2.97470 0.01641 181.30 <2e-16 ***
## x1:x2 -4.54202 0.04155 -109.31 <2e-16 ***
## x1:x3 -6.97838 0.03611 -193.27 <2e-16 ***
## x2:x3 -3.79397 0.03330 -113.93 <2e-16 ***
## x1:x2:x3 9.90535 0.07262 136.40 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.006887 on 742 degrees of freedom
## Multiple R-squared: 0.9927, Adjusted R-squared: 0.9926
## F-statistic: 1.434e+04 on 7 and 742 DF, p-value: < 2.2e-16
Compute test MSE from the linear regression with full interactions
options(scipen = 999) # turn off scientific display
pred_linreg2 <- predict(linreg2, newdata = dfs_test)
mse_linreg2 <- mean((dfs_test$y - pred_linreg2)^2)
mse_linreg2 ## [1] 0.00004746836
Clearly this has a better prediction accuracy than the neural net above. We note that, in this simulated example, we know the true model. But in reality when we typically have large number of features, it may not be easy to specify the true model.
Visualizing predictions:
data_pred <- tibble(pred_nnet4,
pred_linreg,
pred_linreg2,
truth = dfs_test$y)
#
p1 <- ggplot(data_pred, aes(truth, pred_nnet4)) +
geom_point() +
geom_smooth() +
ggtitle("NNET4")
p2 <- ggplot(data_pred, aes(truth, pred_linreg)) +
geom_point() +
geom_smooth() +
ggtitle("Linear regression")
p3 <- ggplot(data_pred, aes(truth, pred_linreg2)) +
geom_point() +
geom_smooth() +
ggtitle("Lin reg w/interactions")
# plot
library(patchwork)
p1 | p2 | p3# scale variables, except chas and medv
# boston <- as_tibble(Boston) %>%
# mutate(across(.cols=-c("chas","medv"), scale1))
boston <- as_tibble(Boston) |>
mutate(across(.cols=-c("chas"), scale1))
# scale1 was defined previously# train-test split
library(rsample)
set.seed(10) # for replication
boston_split <- initial_split(boston,
prop = 0.75,
strata = medv)# train-test data
boston_train <- boston_split |> training()
boston_test <- boston_split |> testing()# 2 hidden layers with 5 neurons each
set.seed(1010)
nn1 <- neuralnet(medv ~ crim + zn + indus + chas + nox + rm + age +
dis + rad + tax + ptratio + black + lstat,
data = boston_train,
hidden = c(5,5))# ANN(5,5) architecture
plot(nn1, col.hidden = 'darkgreen',
col.hidden.synapse = 'darkgreen',
show.weights = F,
information = F,
fill = 'lightblue',
rep = "best" # to render graph in html output
)# predictions
pred_nn1 <- predict(nn1, newdata = boston_test)
# convert scale1
pred_nn1_converted <- (max(pred_nn1)-min(pred_nn1))*pred_nn1 + min(pred_nn1)
test_medv <- (max(boston_test$medv)-min(boston_test$medv))*boston_test$medv + min(boston_test$medv)
# create a tibble
result_data <- tibble(test_medv, pred_nn1_converted)
head(result_data)## # A tibble: 6 × 2
## test_medv pred_nn1_converted[,1]
## <dbl> <dbl>
## 1 0.369 0.444
## 2 0.398 0.417
## 3 0.256 0.336
## 4 0.222 0.460
## 5 0.309 0.401
## 6 0.293 0.367
## [1] 0.01119983
Compare to linear regression:
# linear regression with full set of variables
reg1 <- lm(medv ~ crim + zn + indus + chas + nox + rm + age + dis + rad + tax +
ptratio + black + lstat, data = boston_train)
pred_reg1 <- predict(reg1, newdata = boston_test)
pred_reg1_converted <- (max(pred_reg1)-min(pred_reg1))*pred_reg1 + min(pred_reg1)
result_data$pred_reg1_converted <- pred_reg1_converted
head(result_data)## # A tibble: 6 × 3
## test_medv pred_nn1_converted[,1] pred_reg1_converted
## <dbl> <dbl> <dbl>
## 1 0.369 0.444 0.263
## 2 0.398 0.417 0.212
## 3 0.256 0.336 -0.0744
## 4 0.222 0.460 0.117
## 5 0.309 0.401 0.180
## 6 0.293 0.367 0.119
## [1] 0.04876404
# compare predictions
p1 <- ggplot(result_data, aes(test_medv, pred_nn1_converted)) +
geom_point() +
geom_smooth() +
ggtitle("ANN(5,5)")
p2 <- ggplot(result_data, aes(test_medv, pred_reg1_converted)) +
geom_point() +
geom_smooth() +
ggtitle("Linear Regression")
# plot
library(patchwork)
p1 | p2 This section will focus on time series forecasting using Recurrent Neural Networks (RNN).
For other applications, please refer to the resources section of the textbook website: https://www.statlearning.com/.
In particular, see the html output of Ch.10 lab in the text:
https://hastie.su.domains/ISLR2/Labs/Rmarkdown_Notebooks/Ch10-deeplearning-lab-torch.html
which uses R’s {torch} package (alternatively there is
also {keras} version which relies on Python).
We will replicate the example in Section 10.5.2 in the text. We refer to
https://hastie.su.domains/ISLR2/Labs/Rmarkdown_Notebooks/Ch10-deeplearning-lab-torch.html
for the original source of the replication using R
{torch} package.
library(glmnet)
library(torch)
library(luz) # high-level interface for torch
library(torchvision) # for datasets and image transformation
library(torchdatasets) # for datasets we are going to use
library(zeallot)
torch_manual_seed(13)library(ISLR2)
xdata <- data.matrix(
NYSE[, c("DJ_return", "log_volume","log_volatility")]
)
istrain <- NYSE[, "train"]
xdata <- scale(xdata)istrain = TRUE for each year in the
training set, and = FALSE for each year in the test
set.
We first write functions to create lagged versions of the three time
series. We start with a function that takes as input a data matrix and a
lag \(L\), and returns a lagged version
of the matrix. It simply inserts \(L\)
rows of NA at the top, and truncates the bottom.
lagm <- function(x, k = 1) {
n <- nrow(x)
pad <- matrix(NA, k, ncol(x))
rbind(pad, x[1:(n - k), ])
}We now use this function to create a data frame with all the required lags, as well as the response variable.
arframe <- data.frame(log_volume = xdata[, "log_volume"],
L1 = lagm(xdata, 1), L2 = lagm(xdata, 2),
L3 = lagm(xdata, 3), L4 = lagm(xdata, 4),
L5 = lagm(xdata, 5)
)If we look at the first five rows of this frame, we will see some
missing values in the lagged variables (due to the construction above).
We remove these rows, and adjust istrain accordingly.
We now fit the linear AR model to the training data using
lm(), and predict on the test data.
arfit <- lm(log_volume ~ ., data = arframe[istrain, ])
arpred <- predict(arfit, arframe[!istrain, ])
V0 <- var(arframe[!istrain, "log_volume"])
1 - mean((arpred - arframe[!istrain, "log_volume"])^2) / V0## [1] 0.413223
The last two lines compute the \(R^2\) on the test data, as defined in (3.17).
We refit this model, including the factor variable
day_of_week.
arframed <-
data.frame(day = NYSE[-(1:5), "day_of_week"], arframe)
arfitd <- lm(log_volume ~ ., data = arframed[istrain, ])
arpredd <- predict(arfitd, arframed[!istrain, ])
1 - mean((arpredd - arframe[!istrain, "log_volume"])^2) / V0## [1] 0.4598616
To fit the RNN, we need to reshape these data, since it expects a sequence of \(L=5\) feature vectors \(X=\{X_\ell\}_1^L\) for each observation, as in (10.20) on page 428. These are lagged versions of the time series going back \(L\) time points.
n <- nrow(arframe)
xrnn <- data.matrix(arframe[, -1])
xrnn <- array(xrnn, c(n, 3, 5))
xrnn <- xrnn[,, 5:1]
xrnn <- aperm(xrnn, c(1, 3, 2))
dim(xrnn)## [1] 6046 5 3
We have done this in four steps. The first simply extracts the \(n\times 15\) matrix of lagged versions of
the three predictor variables from arframe. The second
converts this matrix to a \(n\times 3\times
5\) array. We can do this by simply changing the dimension
attribute, since the new array is filled column wise. The third step
reverses the order of lagged variables, so that index \(1\) is furthest back in time, and index
\(5\) closest. The final step
rearranges the coordinates of the array (like a partial transpose) into
the format that the RNN module in torch expects.
Now we are ready to proceed with the RNN, which uses 12 hidden units.
model <- nn_module(
initialize = function() {
self$rnn <- nn_rnn(3, 12, batch_first = TRUE)
self$dense <- nn_linear(12, 1)
self$dropout <- nn_dropout(0.2)
},
forward = function(x) {
c(output, ...) %<-% (x %>%
self$rnn())
output[,-1,] %>%
self$dropout() %>%
self$dense() %>%
torch_flatten(start_dim = 1)
}
)
model <- model %>%
setup(
optimizer = optim_rmsprop,
loss = nn_mse_loss()
) %>%
set_opt_hparams(lr = 0.001)The output layer has a single unit for the response.
We fit the model in a similar fashion to previous networks. We supply
the fit function with test data as validation data, so that
when we monitor its progress and plot the history function we can see
the progress on the test data. Of course we should not use this as a
basis for early stopping, since then the test performance would be
biased.
fitted <- model %>% fit(
list(xrnn[istrain,, ], arframe[istrain, "log_volume"]),
epochs = 30, # = 200,
dataloader_options = list(batch_size = 64),
valid_data =
list(xrnn[!istrain,, ], arframe[!istrain, "log_volume"])
)
kpred <- as.numeric(predict(fitted, xrnn[!istrain,, ]))
1 - mean((kpred - arframe[!istrain, "log_volume"])^2) / V0## [1] 0.4052122
This model takes about one minute to train.
We could replace the nn_module() command above with the
following command:
model <- nn_module(
initialize = function() {
self$dense <- nn_linear(15, 1)
},
forward = function(x) {
x %>%
torch_flatten(start_dim = 2) %>%
self$dense()
}
)Here, torch_flatten() simply takes the input sequence
and turns it into a long vector of predictors. This results in a linear
AR model. To fit a nonlinear AR model, we could add in a hidden
layer.
However, since we already have the matrix of lagged variables from
the AR model that we fit earlier using the lm() command, we
can actually fit a nonlinear AR model without needing to perform
flattening. We extract the model matrix x from
arframed, which includes the day_of_week
variable.
## [1] "dayfri" "daymon" "daythur"
## [4] "daytues" "daywed" "L1.DJ_return"
## [7] "L1.log_volume" "L1.log_volatility" "L2.DJ_return"
## [10] "L2.log_volume" "L2.log_volatility" "L3.DJ_return"
## [13] "L3.log_volume" "L3.log_volatility" "L4.DJ_return"
## [16] "L4.log_volume" "L4.log_volatility" "L5.DJ_return"
## [19] "L5.log_volume" "L5.log_volatility"
The -1 in the formula avoids the creation of a column of
ones for the intercept. The variable day\_of\_week is a
five-level factor (there are five trading days), and the -1
results in five rather than four dummy variables.
The rest of the steps to fit a nonlinear AR model should by now be familiar.
arnnd <- nn_module(
initialize = function() {
self$dense <- nn_linear(20, 32)
self$dropout <- nn_dropout(0.5)
self$activation <- nn_relu()
self$output <- nn_linear(32, 1)
},
forward = function(x) {
x %>%
torch_flatten(start_dim = 2) %>%
self$dense() %>%
self$activation() %>%
self$dropout() %>%
self$output() %>%
torch_flatten(start_dim = 1)
}
)
arnnd <- arnnd %>%
setup(
optimizer = optim_rmsprop,
loss = nn_mse_loss()
) %>%
set_opt_hparams(lr = 0.001)
fitted <- arnnd %>% fit(
list(x[istrain,], arframe[istrain, "log_volume"]),
epochs = 30,
dataloader_options = list(batch_size = 64),
valid_data =
list(x[!istrain,], arframe[!istrain, "log_volume"])
)
plot(fitted)npred <- as.numeric(predict(fitted, x[!istrain, ]))
1 - mean((arframe[!istrain, "log_volume"] - npred)^2) / V0## [1] 0.4684338