+1 (415) 366-1364

Anomaly Detection on TensorFlow: Autoencoders, Thresholds, and Alerts You Can Trust

Most real anomaly-detection problems share one awkward fact: you have plenty of normal data, almost no labelled failures, and the definition of "anomalous" keeps changing. A supervised classifier struggles here. An autoencoder trained only on normal data is a practical baseline: it learns to reconstruct what normal looks like, and inputs it reconstructs badly are suspects. This tutorial builds one in Keras 3 and, more importantly, covers the parts that usually go wrong: thresholds, evaluation and alert fatigue.

When an autoencoder is the right tool

Use it when normal behaviour is abundant and stable, anomalies are rare and varied, and a ranked list of suspects is useful. Skip it when you have many labelled examples of each failure type (use a classifier), or when a simple rule or a gradient-boosted model on engineered features would do. Always build the simple baseline first, such as per-feature z-scores or an isolation forest, so you know what the neural network must beat.

Prepare the data

Train only on data you believe is normal, and split by time rather than at random, so the validation set mimics the future.

import numpy as np, keras
from keras import layers

# X_train_normal, X_val_normal, X_test, y_test (1 = anomaly, may be tiny)
mean = X_train_normal.mean(0)
std = X_train_normal.std(0) + 1e-6
norm = lambda x: ((x - mean) / std).astype("float32")

Fit the scaling statistics on the training split only, and save them with the model. A mismatch between training and serving normalisation is the most common production bug we see.

Build the model

Keep the bottleneck narrow enough that the network cannot simply copy its input.

n = X_train_normal.shape[1]
inputs = keras.Input((n,))
x = layers.Dense(64, activation="relu")(inputs)
x = layers.Dense(16, activation="relu")(x)
z = layers.Dense(4, activation="relu", name="bottleneck")(x)
x = layers.Dense(16, activation="relu")(z)
x = layers.Dense(64, activation="relu")(x)
out = layers.Dense(n)(x)
ae = keras.Model(inputs, out)
ae.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mse")

ae.fit(norm(X_train_normal), norm(X_train_normal),
       validation_data=(norm(X_val_normal), norm(X_val_normal)),
       epochs=100, batch_size=256,
       callbacks=[keras.callbacks.EarlyStopping(patience=8, restore_best_weights=True)])

For sequences and sensor windows, swap the dense layers for Conv1D or LSTM layers; the scoring logic below stays the same.

Score and choose a threshold

The anomaly score is the per-sample reconstruction error.

def score(x):
    x = norm(x)
    return np.mean((x - ae.predict(x, verbose=0)) ** 2, axis=1)

val_scores = score(X_val_normal)
threshold = np.quantile(val_scores, 0.995)

A quantile of validation scores on normal data gives you an explicit, explainable false-positive budget: at 0.995, roughly 1 in 200 normal samples will alert. Pick the quantile from the business cost of a false alarm, not from a metric. If you have a handful of labelled anomalies, use them to sanity-check the choice, not to tune it aggressively, since a few examples make an unstable target.

Evaluate honestly

With few labels, report threshold-free ranking quality (average precision, or ROC-AUC if classes are not extremely skewed) and then precision and recall at the chosen threshold.

from sklearn.metrics import average_precision_score, precision_recall_fscore_support
s = score(X_test)
print("AP:", average_precision_score(y_test, s))
print(precision_recall_fscore_support(y_test, s > threshold, average="binary"))

Also review the top-scoring false positives by hand. They often reveal data-quality issues, such as stuck sensors or unit changes, that are worth alerting on anyway.

Explain the alerts

An alert that says only "score 0.83" gets ignored. Return the per-feature error alongside the score so an operator can see which signals drove it:

feature_err = (norm(x) - ae.predict(norm(x), verbose=0)) ** 2
top = np.argsort(-feature_err, axis=1)[:, :3]

Deploy and monitor

Export the model with ae.export("anomaly_savedmodel") for TensorFlow Serving, or convert it for edge devices as described in our LiteRT migration guide. Computing the score inside the serving graph, or in a thin wrapper versioned together with the scaling statistics and threshold, avoids drift between components.

Normal changes over time, so monitor the alert rate and the score distribution. A creeping alert rate usually means the world has moved rather than that failures have increased; see Catching Data Drift Early with TensorFlow Data Validation. Schedule periodic retraining on recent verified-normal data, and keep the threshold computation in the same pipeline so it is refreshed with the model.

Common pitfalls

  • Contaminated training data. Anomalies in the "normal" set teach the model to reconstruct them. Filter with a first-pass model and retrain.
  • Over-capacity. A wide bottleneck reconstructs everything, so nothing stands out.
  • Random splits on time series. Leakage makes validation errors look better than production will be.
  • One global threshold for heterogeneous assets. Calibrate per machine, segment or customer where behaviour differs.

Need help?

If you are scoping an anomaly-detection system and want an experienced second opinion on data, thresholds and deployment, get in touch and our TensorFlow consultants will respond with a practical plan.