This “Hello, World!” shows the Keras Sequential API and fit().

TensorFlow 2 quickstart for beginners

This short introduction uses Keras to:

  1. Load a prebuilt dataset.
  2. Build a neural network machine learning model that classifies images.
  3. Train this neural network.
  4. Evaluate the accuracy of the model.

Set up TensorFlow

Import TensorFlow into your program to get started:


See the installation guide to learn how to correctly install TensorFlow for R.

Load a dataset

Load and prepare the MNIST dataset. Convert the sample data from integers to floating-point numbers:

c(c(x_train, y_train), c(x_test, y_test)) %<-% keras::dataset_mnist()
Loaded Tensorflow version 2.9.1
x_train <- x_train / 255
x_test <-  x_test / 255

Build a machine learning model

Build a sequential model by stacking layers.

model <- keras_model_sequential(input_shape = c(28, 28)) %>%
  layer_flatten() %>%
  layer_dense(128, activation = "relu") %>%
  layer_dropout(0.2) %>%

For each example, the model returns a vector of logits or log-odds scores, one for each class.

predictions <- predict(model, x_train[1:2, , ])
           [,1]       [,2]      [,3]         [,4]      [,5]       [,6]
[1,] -0.2865990 0.10246756 0.1823071  0.480318427 0.2972973 0.08421922
[2,]  0.2229058 0.07552445 0.3085604 -0.008882385 0.6066740 0.40753663
            [,7]      [,8]      [,9]     [,10]
[1,]  0.07219264 0.7367747 0.3742948 0.3403923
[2,] -0.26937979 1.0024217 0.4603127 0.7594261

The tf$nn$softmax function converts these logits to probabilities for each class:

[[0.05717045 0.08436087 0.09137238 0.12309477 0.10250724 0.08283539
  0.08184513 0.15908058 0.11071185 0.10702136]
 [0.08206316 0.07081762 0.08940207 0.06508545 0.12045273 0.09870346
  0.05015928 0.17893188 0.10405255 0.14033179]], shape=(2, 10), dtype=float64)

Note: It is possible to bake the tf$nn$softmax function into the activation function for the last layer of the network. While this can make the model output more directly interpretable, this approach is discouraged as it’s impossible to provide an exact and numerically stable loss calculation for all models when using a softmax output.

Define a loss function for training using loss_sparse_categorical_crossentropy(), which takes a vector of logits and an integer index of which are TRUE and returns a scalar loss for each example.

loss_fn <- loss_sparse_categorical_crossentropy(from_logits = TRUE)

This loss is equal to the negative log probability of the true class: The loss is zero if the model is sure of the correct class. This untrained model gives probabilities close to random (1/10 for each class), so the initial loss should be close to -log(1/10) ~= 2.3.

loss_fn(y_train[1:2], predictions)
tf.Tensor(2.4955830059234123, shape=(), dtype=float64)

Before you start training, configure and compile the model using Keras compile(). Set the optimizer class to "adam", set the loss to the loss_fn function you defined earlier, and specify a metric to be evaluated for the model by setting the metrics parameter to "accuracy".

model %>% compile(
  optimizer = "adam",
  loss = loss_fn,
  metrics = "accuracy"

Train and evaluate your model

Use the fit() method to adjust your model parameters and minimize the loss:

model %>% fit(x_train, y_train, epochs = 5)

The evaluate() method checks the models performance, usually on a Validation-set or Test-set.

model %>% evaluate(x_test,  y_test, verbose = 2)
      loss   accuracy 
0.07050181 0.97829998 

The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the TensorFlow tutorials.

If you want your model to return which class had the highest probability, you can reuse the trained model to define a new sequential model that also calls softmax and argmax:

probability_model <- keras_model_sequential() %>%
  model() %>%
  layer_activation_softmax() %>%
probability_model(x_test[1:5, , ])
tf.Tensor([3 2 1 1 4 4 3 0 2 4], shape=(10), dtype=int64)


Congratulations! You have trained a machine learning model using a prebuilt dataset using the Keras API.

For more examples of using Keras, check out the tutorials. To learn more about building models with Keras, read the guides. If you want learn more about loading and preparing data, see the tutorials on image data loading or CSV data loading.