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()
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.05071244 0.5779704 -0.7401736 -0.08471709 -0.02273238 -0.5441084
[2,] -0.22928327 0.1351517 -0.3160491 -0.24394375  0.03508042 -1.0097653
          [,7]      [,8]       [,9]      [,10]
[1,] -0.192526 0.2363778 -0.2609699 -0.6893842
[2,] -0.704735 0.4180042 -0.4001779 -0.9935134

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

[[0.10502907 0.19694412 0.05270846 0.10151763 0.10800929 0.06412544
  0.09114244 0.1399559  0.08511299 0.05545464]
 [0.10056938 0.14478977 0.09221124 0.09910574 0.13100186 0.04607939
  0.06251435 0.1921229  0.08477098 0.04683439]], 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.5219107458556875, 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.07764678 0.97750002 

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 0 4 2 4 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.