Keras is a high-level API for building and training neural networks. It supplies layers, models, losses, optimizers, metrics, and a training loop, so you can start with a working model without writing its training logic from scratch. section 3.2 section 3.7
Classify handwritten digits
A small model can learn from MNIST images and then be tested on images it has not seen during training. library(keras3) .[.[train_images, train_labels], .[test_images, test_labels]] <- dataset_mnist() train_images <- array_reshape(train_images, c(60000, 28 * 28)) / 255 test_images <- array_reshape(test_images, c(10000, 28 * 28)) / 255 model <- keras_model_sequential() |> layer_dense(512, activation = "relu") |> layer_dense(10, activation = "softmax") model |> compile( optimizer = "adam", loss = "sparse_categorical_crossentropy", metrics = "accuracy" ) fit(model, train_images, train_labels, epochs = 5, batch_size = 128) evaluate(model, test_images, test_labels)$accuracy predict(model, test_images[1:10, ]) The illustrated run reaches 0.9784 test accuracy; a prediction for each image contains ten scores, one per digit class. section 2.1
The example follows a reusable sequence:
- Prepare inputs: reshape each 28 × 28 image into 784 values and divide pixel values by 255. section 2.1
- Assemble layers into a model. The final softmax layer produces scores for the ten classes. section 2.1
- Compile with an optimizer, loss, and metric; use fit() to train, evaluate() to test, and predict() for new inputs. section 2.1 section 3.7
Keras runs on a lower-level backend: TensorFlow, PyTorch, or JAX. TensorFlow is the default for a fresh R keras3 setup; use_backend("jax") is one way to choose another. The same high-level model code can move between backends, while backend-specific APIs remain available when you need finer control. NumPy can support prediction, but not training, because it lacks the required gradient API. section 3.2 section 3.6.1
Figure 3.4 Keras and its backends. A backend is a low-level tensor computing platform; Keras is a high-level deep learning API.
The diagram separates Keras's model-building API from the lower-level computing platforms that run it. section 3.6.1
Start with a Sequential model when layers form a simple chain. For other designs, use the Functional API or subclass Model. The default fit() loop provides callbacks and distributed-training support; overriding train_step() lets you change the learning step while keeping that loop. A fully custom loop remains an option. For distributed training with the JAX backend, Keras also provides DataParallel and ModelParallel configuration. section 7.4.4 section 7.5 section 18.2.2





