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.
model.fit(x, y, epochs=50, batch_size=32, validation_split=0.20, shuffle=True)
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.
- 1. Keras's fit method…
- 2. Why keep some data aside during training?
- 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.
- 1. Parameters of Dense(16) on a 2-feature input?
- 2. Which API handles a model with two inputs?
- 3. fit returns…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.Semantics worth knowing
- validation_split takes the last fraction of
xandybefore shuffling;shuffle=Trueonly reorders training batches each epoch. Sorted data gives a skewed validation set; shuffle it yourself or passvalidation_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_uniforminitializers, Adam withepsilon=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_stepto 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.
- 1. With validation_split=0.2 and shuffle=True, the validation rows are…
- 2. EarlyStopping's restore_best_weights defaults to…
- 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.TFLiteConverterwith 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.
- 1. For forecasting a drifting telemetry channel, the honest validation set is…
- 2. Full-integer TFLite quantization needs…
- 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).
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
- F. Chollet (2021). Deep Learning with Python, 2nd ed. Manning.
- M. Abadi et al. (2016). “TensorFlow: a system for large-scale machine learning.” OSDI.
- D. G. Murray et al. (2021). “tf.data: a machine learning data processing framework.” Proc. VLDB Endowment, 14(12).
- R. David et al. (2021). “TensorFlow Lite Micro: embedded machine learning for TinyML systems.” MLSys.
- Keras documentation (keras.io): Model training APIs (fit, validation_split), Callbacks API.