Neural networks are a type of machine learning algorithm that are designed to mimic the function of the human brain. They consist of interconnected nodes or “neurons” that process information and generate outputs based on the inputs they receive.
Uses
Neural networks are typically used for tasks such as image recognition, natural language processing, and prediction. They are capable of learning from data and improving their performance over time, which makes them well-suited for complex and dynamic problems.
Single Layer Neural Networks
A single layer neural networks can be formulated as linear function:
\[
f(X) = \beta_0 + \sum^K_{k=1}\beta_kh_k(X)
\]
Where \(X\) is a vector of inputs of length \(p\) and \(K\) is the number of activations, \(\beta_j\) are the regression coefficients and
Instead of minimizing \(F(\boldsymbol X)\) at each step, we minimize:
\[
F_\alpha(\boldsymbol X) = \sum_{i\in\alpha} f(y_i; \boldsymbol X)
\] where \(\alpha\) indicates the data points randomly sampled to be used to compute the gradient.
R6
Neural Networks
Stochastic Gradient Descent
R6
TensorFlow
Torch
R Code
Single Layer R Code
Multilayer R Code
Object-Oriented Programming
Loosely speaking Object-Oriented Programming involves developing R objects with specialized attributes.
# library(torch)library(luz) # high-level interface for torchlibrary(torchvision) # for datasets and image transformationlibrary(torchdatasets) # for datasets we are going to uselibrary(zeallot)torch_manual_seed(13)
Build a single-layer neural network that will predict body_mass_g with the remaining predictors except for year. The hidden layer will contain 50 nodes, and the activation functions will be ReLU.
Use the penguins data set to construct a 2-layer neural network to predict species with the other predictors, except for year. The 1st layer should have 10 nodes, the second layer should have 5 nodes, and use ReLU activations.
training <- penguins |>slice_sample(prop = .8)testing <- penguins |>anti_join(training)
Xtraining <- training |>model.matrix(species ~ . -1, data = _) |>scale()Xtesting <- testing |>model.matrix(species ~ . -1, data = _) |>scale()