Neural Networks with Keras
Introduction
Neural networks are a class of machine learning models inspired by the human brain, capable of capturing complex patterns in data. Keras is a high-level API for building and training deep learning models, providing a simple and user-friendly interface. In this lecture, we will learn how to build and train neural networks using the Keras package in R.
Key Concepts
1. What is Keras?
Keras is an open-source software library that provides a Python and R interface for artificial neural networks. Keras acts as an interface for the TensorFlow library. It is designed to enable fast experimentation with deep neural networks.
2. Neural Network Structure
A neural network consists of layers of interconnected nodes (neurons). The primary types of layers are:
- Input Layer: The layer that receives the input data.
- Hidden Layers: Intermediate layers that perform computations and extract features.
- Output Layer: The layer that produces the final prediction or classification.
Performing Neural Network Analysis in R with Keras
1. Installing Required Packages
We will use the keras
package for building neural networks.
# Installing the keras package
install.packages("keras")
library(keras)
# Installing TensorFlow backend
install_keras()
2. Preparing the Data
We will use the MNIST dataset, a popular dataset for image classification tasks.
# Loading the MNIST dataset
<- dataset_mnist()
mnist <- mnist$train$x
x_train <- mnist$train$y
y_train <- mnist$test$x
x_test <- mnist$test$y
y_test
# Reshaping and scaling the data
<- array_reshape(x_train, c(nrow(x_train), 784))
x_train <- array_reshape(x_test, c(nrow(x_test), 784))
x_test <- x_train / 255
x_train <- x_test / 255
x_test
# Converting labels to categorical
<- to_categorical(y_train, 10)
y_train <- to_categorical(y_test, 10) y_test
3. Building the Model
You can build a neural network model using the keras_model_sequential()
function.
# Building the neural network model
<- keras_model_sequential() %>%
model layer_dense(units = 256, activation = 'relu', input_shape = 784) %>%
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = 'relu') %>%
layer_dropout(rate = 0.3) %>%
layer_dense(units = 10, activation = 'softmax')
# Printing the model summary
summary(model)
4. Compiling the Model
Compile the model by specifying the loss function, optimizer, and metrics.
# Compiling the model
%>% compile(
model loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(),
metrics = c('accuracy')
)
5. Training the Model
Train the model using the fit()
function.
# Training the model
<- model %>% fit(
history
x_train, y_train,epochs = 30,
batch_size = 128,
validation_split = 0.2
)
6. Evaluating the Model
Evaluate the model’s performance on the test data.
# Evaluating the model
<- model %>% evaluate(x_test, y_test)
score print(score)
7. Making Predictions
Use the trained model to make predictions on new data.
# Making predictions
<- model %>% predict_classes(x_test)
predictions print(predictions)
Example: Comprehensive Neural Network Analysis
Here’s a comprehensive example of building, training, and evaluating a neural network using the Keras package in R.
# Loading the keras package
library(keras)
# Loading the MNIST dataset
<- dataset_mnist()
mnist <- mnist$train$x
x_train <- mnist$train$y
y_train <- mnist$test$x
x_test <- mnist$test$y
y_test
# Reshaping and scaling the data
<- array_reshape(x_train, c(nrow(x_train), 784))
x_train <- array_reshape(x_test, c(nrow(x_test), 784))
x_test <- x_train / 255
x_train <- x_test / 255
x_test
# Converting labels to categorical
<- to_categorical(y_train, 10)
y_train <- to_categorical(y_test, 10)
y_test
# Building the neural network model
<- keras_model_sequential() %>%
model layer_dense(units = 256, activation = 'relu', input_shape = 784) %>%
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = 'relu') %>%
layer_dropout(rate = 0.3) %>%
layer_dense(units = 10, activation = 'softmax')
# Printing the model summary
summary(model)
# Compiling the model
%>% compile(
model loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(),
metrics = c('accuracy')
)
# Training the model
<- model %>% fit(
history
x_train, y_train,epochs = 30,
batch_size = 128,
validation_split = 0.2
)
# Evaluating the model
<- model %>% evaluate(x_test, y_test)
score print(score)
# Making predictions
<- model %>% predict_classes(x_test)
predictions print(predictions)
Summary
In this lecture, we covered how to build and train neural networks using the Keras package in R, including data preparation, model building, training, evaluation, and prediction. Neural networks are powerful tools for capturing complex patterns in data, and Keras makes it easy to implement these models in R.
Further Reading
For more detailed information, consider exploring the following resources:
Call to Action
If you found this lecture helpful, make sure to check out the other lectures in the ML R series. Happy coding!