Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

TensorFlow and Keras (Overview)

Keras is a high-level API for building and training neural networks with three lines: define a model, compile it with an optimizer, loss and metrics, and fit it. Keras 3 runs on JAX, TensorFlow or PyTorch backends; TensorFlow adds tf.data input pipelines, graph compilation with tf.function, the SavedModel format and a deployment ecosystem (TF Serving, TensorFlow Lite / LiteRT for phones and microcontrollers). This topic gives an overview of the Sequential, functional and subclassing APIs, compile/fit/evaluate/predict, callbacks, tf.data and deployment, and the semantics that surprise people. In the exercises you build a mini-Keras (Dense, Sequential, summary, compile, fit with validation_split and callbacks, History) in NumPy, then study how Keras's validation_split (the last fraction, unshuffled) misleads on sorted data yet is the honest choice for drifting time series.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Three lines to train a network

Keras was designed so that the common case is short: stack some layers, say how to measure mistakes and how to correct them, and press “fit”. It hides the training loop entirely, which is wonderful until you need to know exactly what it did, for example which part of your data it quietly kept aside to check itself.

What validation_split actually holds out
data order:
model.fit(x, y, epochs=50, batch_size=32, validation_split=0.20, shuffle=True)
row 0validation (20 rows)training (80 rows, shuffled every epoch)
training: 38% class 1
validation: 100% class 1
⚠️ misleading: validation is 100% class 1 while training is 38% class 1. Shuffle the arrays yourself (or pass validation_data) before calling fit.
Blue = class 0, orange = class 1. The split happens once, on the arrays as given, before the per-epoch shuffling of training batches. The same rule applies to the last batch of a tf.data pipeline: know what your validation set contains.
Why engineers care

TensorFlow’s deployment tools are a common route to running networks on embedded hardware: TensorFlow Lite Micro runs on microcontrollers with tens of kilobytes of memory, the kind of processor found in CubeSat payloads and small drones. Keras is often the fastest way to a working baseline before a custom pipeline.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Keras's fit method…
  2. 2. Why keep some data aside during training?
  3. 3. In the demo, with data sorted by label, the validation set…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The Keras workflow

import os
os.environ["KERAS_BACKEND"] = "jax"          # or "tensorflow", "torch" (Keras 3)
import keras

model = keras.Sequential([
    keras.Input(shape=(2,)),
    keras.layers.Dense(16, activation="relu"),
    keras.layers.Dense(8, activation="relu"),
    keras.layers.Dense(1, activation="sigmoid"),
])
model.summary()                               # Total params: 193
model.compile(optimizer=keras.optimizers.Adam(1e-2),
              loss="binary_crossentropy", metrics=["accuracy"])
history = model.fit(X, y, epochs=60, batch_size=32, validation_split=0.2,
                    callbacks=[keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True)])
model.evaluate(X_test, y_test); model.predict(X_new)
model.save("circles.keras")

Three ways to define a model: Sequential (a stack), the functional API (inputs = keras.Input(...); x = Dense(...)(inputs); model = keras.Model(inputs, outputs) for branches, multiple inputs and outputs, shared layers), and subclassing keras.Model with a call method for arbitrary Python logic.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Parameters of Dense(16) on a 2-feature input?
  2. 2. Which API handles a model with two inputs?
  3. 3. fit returns…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

Semantics worth knowing

  • validation_split takes the last fraction of x and y before shuffling; shuffle=True only reorders training batches each epoch. Sorted data gives a skewed validation set; shuffle it yourself or pass validation_data.
  • Callbacks: EarlyStopping(monitor, patience, restore_best_weights) (by default it does not restore the best weights), ReduceLROnPlateau(factor, patience), ModelCheckpoint, TensorBoard, CSVLogger, LearningRateScheduler.
  • Defaults: glorot_uniform initializers, Adam with epsilon=1e-7 (PyTorch uses 1e-8), loss reduction as a mean over the batch, metrics averaged over batches during the epoch.
  • train_step: override Model.train_step to customize what happens per batch while keeping fit’s machinery (callbacks, distribution, logging).

TensorFlow underneath

tf.data builds input pipelines: Dataset.from_tensor_slices(...).shuffle(buf).map(fn, num_parallel_calls=AUTOTUNE).batch(32).prefetch(AUTOTUNE) overlaps loading and training; cache() avoids recomputation. tf.function traces Python into a graph (AutoGraph converts Python control flow), much like jax.jit: retracing happens for new input signatures, and Python side effects run only at trace time. SavedModel stores the graph and weights for serving.

🐍 Exercise 1: a mini-Keras
Implement Dense layers (glorot_uniform, activations with derivatives), SGD and Adam (Keras epsilon), MSE and binary cross-entropy, accuracy and MAE, a Sequential model with build, summary (parameter counts), compile, predict, evaluate, get/set_weights and fit (batches, Keras-style validation_split, History, callbacks), plus EarlyStopping with restore_best_weights and ReduceLROnPlateau. Train on two noisy circles.
📝 Quick check (Level 2)
0/3 answered
  1. 1. With validation_split=0.2 and shuffle=True, the validation rows are…
  2. 2. EarlyStopping's restore_best_weights defaults to…
  3. 3. tf.function is most similar to…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Deployment

  • model.save("m.keras") for Keras; SavedModel (model.export(...)) for TF Serving.
  • TensorFlow Lite / LiteRT: tf.lite.TFLiteConverter with post-training quantization (dynamic-range, full-integer int8 with a representative dataset, float16) for phones and edge accelerators; TFLite Micro for microcontrollers (no OS, no dynamic memory).
  • TensorFlow.js for browsers; ONNX export (via tf2onnx) for other runtimes (C3.7).

Choosing a framework

Keras gives the shortest path to a standard model and a backend-independent codebase; PyTorch dominates research code; JAX suits custom transformations and accelerators. Interop is good (Keras 3 on JAX or PyTorch, ONNX for exchange), so pick by ecosystem: deployment target, existing code, and the libraries your field uses.

Validation done right

Random splits assume samples are exchangeable. That fails for time series (autocorrelation and drift leak the future), for grouped data (several samples per satellite, per patient, per flight: split by group), and for sorted data with Keras’s last-fraction rule. Validate the way the model will be used.

📝 Quick check (Level 3)
0/3 answered
  1. 1. For forecasting a drifting telemetry channel, the honest validation set is…
  2. 2. Full-integer TFLite quantization needs…
  3. 3. Several samples per spacecraft in a dataset: split by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Keras semantics, measured

Exercise 1. The 2-16-8-1 network has 193 parameters as summary() reports. On two noisy concentric circles, 60 epochs of Adam (lr 0.01, batch 32, validation_split 0.2) reach validation accuracy 1.000 and accuracy 0.993 on fresh test data. With 10 rows and validation_split 0.3, the validation rows are exactly rows 7, 8, 9. On a scripted validation curve 1.0, 0.8, 0.9, 0.95, …, EarlyStopping(patience 2) stops at epoch 3 and restores the epoch-1 weights, while ReduceLROnPlateau(factor 0.5, patience 1) halves the learning rate at epochs 2 and 3.

Exercise 2: what validation_split holds out.

Sorted labels. 1000 samples of two overlapping Gaussian classes, logistic regression, validation_split 0.2:

Data order validation class-1 share training class-1 share validation accuracy true test accuracy
shuffled 0.515 0.496 0.870 0.873
sorted by label 1.000 0.375 0.745 0.866

The sorted case reports a validation accuracy 12 points too low, measured on one class only.

Drifting series. y = a(t)·x + noise with the gain drifting from 1 to 2.5 over 1000 steps (5 seeds); a linear model:

Error estimate MSE
random 20% split 0.268
last 20% (Keras validation_split) 0.617
true error on the next 200 steps 0.894

The random split is 3.3× optimistic: interleaved validation points are surrounded by training points from the same period. The last-fraction split is much closer, because like deployment it asks the model about a period it hasn’t seen (it is still optimistic, since the drift continues beyond it).

🐍 Exercise 2 (research): what validation_split holds out
Implement Keras's validation_split rule and a random split. For classification data sorted by label, compare validation and true test accuracy and the class shares of each split; for a series with a drifting gain, compare random-split and last-fraction error estimates with the true error on the following period.

TensorFlow and Keras in AI, robotics and aerospace

  • On-board inference: TFLite Micro on microcontrollers for wake-word-style anomaly detection and simple vision; quantized models on edge TPUs and NPUs.
  • Earth observation: large Keras/TF pipelines for land-cover classification over satellite imagery with tf.data streaming tiles.
  • Ground segment: TF Serving behind telemetry dashboards for anomaly scores.
  • Teaching and baselines: Keras’s concise API is a common first model before custom JAX or PyTorch code.

References

  1. F. Chollet (2021). Deep Learning with Python, 2nd ed. Manning.
  2. M. Abadi et al. (2016). “TensorFlow: a system for large-scale machine learning.” OSDI.
  3. D. G. Murray et al. (2021). “tf.data: a machine learning data processing framework.” Proc. VLDB Endowment, 14(12).
  4. R. David et al. (2021). “TensorFlow Lite Micro: embedded machine learning for TinyML systems.” MLSys.
  5. Keras documentation (keras.io): Model training APIs (fit, validation_split), Callbacks API.