Getting ready

We will be using the MNIST dataset of handwritten digits in this example. It consists of 60,000 training and 10,000 test grayscale images that are 28x28 in size.

Let's start by loading the required libraries:

library(keras)
library(grid)
library(abind)

Now, let's load the data:

# Input image dimensions
img_rows <- 28
img_cols <- 28

# The data, shuffled and split between train and test sets
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y

Now, we can check the dimensions of the data:

dim(x_train)

In the following screenshot, you can see that there are 60,000 images in the training data, each of which are 28x28 in size:

Now that we've done this, we can redefine the dimensions of the training data from a matrix of 28x28 to a flattened 1D array that's 784 in length:

x_train <- array_reshape(x_train, c(nrow(x_train), 784))

Next, we normalize the training data and transform the values within the range of 0 and 1:

x_train <- x_train/255

Let's print one sample image data to see what it looks like:

x_train[1,]

Now that we are aware of the data, let's move on to the model building part.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset