Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

AutoEncoders in Keras

A GRU autoencoder in Keras that compresses four hours of vessel track and decodes an eight-hour forecast, trained with probabilistic teacher forcing.

This tutorial builds a GRU autoencoder in Keras that reads four hours of a vessel's AIS track and forecasts the next eight hours of movement. Training uses probabilistic teacher forcing, feeding the decoder a mix of ground truth and its own predictions so convergence is faster and long-horizon forecasts stay stable. You walk away able to window raw AIS into supervised sequence pairs and train a sequence-to-sequence forecaster with a loss that thinks in meters.

What you will learn

  • Querying, segmenting, and interpolating a year of AIS tracks with AISdb

  • Windowing trajectories into fixed input and output sequences with delta features

  • Building a GRU encoder-decoder with a probabilistic teacher-forcing layer in Keras

  • Training with a haversine-based custom loss and standard Keras callbacks

  • Evaluating forecasts as physical distance errors on held-out vessels

Prerequisites

pip install aisdb tensorflow geopandas shapely plotly wandb scikit-learn tqdm

The run shown on this page queried a private regional AISdb database covering Atlantic Canada, ais-atlantic-canada.db, built from a full year of decoded AIS traffic (2021-01-01 through 2021-12-31), because forecasting eight hours from four needs enough long, clean voyages to fill the training buckets built below. If you do not have a private database, decode the open NOAA day file (AIS_2020_01_01.zip) into SQLite as shown in Using Your AIS Data, point get_tracks(dbname, "01012020", "02012020") at it, and add xmin=-98, xmax=-80, ymin=24, ymax=31 to the DBQuery call inside qry_database. One day of AIS exercises the full pipeline end to end but yields far fewer usable trajectories and a weaker fit than the full-year run shown here. You also need the Natural Earth 50m land shapefile (ne_50m_land.shp) under shapes/, a free Weights & Biases account for training logs, and a notebook environment, since the evaluation renders interactive Plotly figures.

Step 1. Set up imports and working folders

Everything downstream assumes these imports, a fixed random seed, and four working folders for the database, shapefiles, cached datasets, and model weights.

import os
import random
import pickle as pkl
import multiprocessing
from multiprocessing import Pool
from functools import partial
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta

import numpy as np
import geopandas as gpd
from shapely.geometry import Point
from tqdm import tqdm
from IPython.display import display
import plotly.graph_objects as go

import aisdb

import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer, Input, GRU, LSTM, RepeatVector, TimeDistributed, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import AdamW
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping

import wandb
from sklearn.metrics import (
    r2_score, mean_squared_error, mean_absolute_error,
    explained_variance_score, mean_absolute_percentage_error)

seed_value = 42
random.seed(seed_value)
np.random.seed(seed_value)
tf.random.set_seed(seed_value)

ROOT = os.getcwd()
PATH = "data"      # holds the SQLite database
SHAPES = "shapes"  # holds the Natural Earth land shapefile
ESRF = "cache"     # holds intermediate pickled datasets
MODELS = "models"  # holds trained weights and training histories
for folder in (PATH, SHAPES, ESRF, MODELS):
    os.makedirs(os.path.join(ROOT, folder), exist_ok=True)

Step 2. Query and segment a year of AIS

AISdb pulls the raw messages, splits tracks on 24-hour silences, drops speed and distance outliers, and interpolates every position to a fixed 5-minute cadence, which the windowing below depends on. A vessel can appear in several disjoint tracks after splitting, so voyages groups the segments by MMSI.

The dataset covers the Atlantic Canada receiver network, roughly a 100 km radius around each station.

100 km AIS receiver coverage over Atlantic Canada, from the private regional database used in this tutorial (full year 2021).

Step 3. Drop tracks that touch land

Interpolation and decoding glitches can place positions inland, and a forecaster trained on impossible tracks learns impossible motion. Any track with a single point on land is removed, in parallel across MMSIs, and the curated result is cached to disk so the filter runs once.

Step 4. Split voyages into train and test

Most MMSIs have between 1 and 49 segments while a few reach 176, so a naive split would let segment-rich vessels dominate. Categorizing voyages as long-term (30 or more segments) or short-term and splitting each bucket 80/20 keeps both behaviors represented in both sets.

Step 5. Window trajectories into samples

The model takes 4 hours of input (48 steps at the 5-minute cadence) and predicts 8 hours (96 steps), so every voyage shorter than 144 steps is dropped and the rest gain delta features that expose the rate of change. A window then slides one step at a time along each voyage, producing overlapping input/output pairs, and each input window gets a straightness score (straight-line over along-track haversine distance, inverted and scaled) so complex, twisty samples can be weighted more heavily during training.

Step 6. Normalize the samples

Three chained transforms bring every feature onto a comparable scale. Longitude, latitude, COG, and SOG first map to [0, 1] with domain bounds for Atlantic Canada, then standardization centers the data to fight vanishing gradients, and a final zero-one pass matches the range the activations expect. denormalize_x reverses the chain when plotting inputs later.

Step 7. Build the teacher-forcing GRU autoencoder

A GRU autoencoder compresses the input sequence into a single hidden state and decodes it into the forecast, and a GRU (Cho et al., 2014, arXiv:1406.1078) handles the temporal dependencies in each direction. The twist is the ProbabilisticTeacherForcing layer, which at every decoder step randomly feeds either the ground-truth previous position or the model's own previous output, governed by a mixing probability. Two graphs share the same trained layers, a training model that takes the ground-truth decoder input and a clean inference model that runs from the encoder alone.

Step 8. Compile with a haversine loss

Losses on normalized coordinates hide the physical size of an error, so the custom loss denormalizes both tensors back to degrees and works in meters through a TensorFlow haversine. It also computes step-to-step distance consistency and an input-to-output continuity penalty, available in the commented weighted combination, while the run shown trained on the RMSE term alone.

Model summary output (Training graph and Inference graph, full layer listing)

Step 9. Train with callbacks

Training pads the decoder's ground-truth input with a leading zero step, fixes the mixing probability at 0.5, and lets the callbacks manage the rest, with ReduceLROnPlateau lowering the learning rate when validation stalls, EarlyStopping restoring the best weights, ModelCheckpoint saving them, and WandbMetricsLogger streaming metrics to Weights & Biases (pass skip_wandb=True to drop it). The straightness weights from Step 5 plug in through the commented sample_weight argument, unused in the run shown.

Step 10. Evaluate in meters

The evaluation predicts the held-out set once, denormalizes everything back to real coordinates, plots sample forecasts against the ground truth, and reports distance errors through the haversine plus standard regression metrics. The slicing with [:, 1:] aligns the 96-step targets with the 95-step teacher-forced outputs.

Results

Each of the four plotted samples shows the green input track, the blue ground truth, and the red forecast, with per-trajectory min, max, mean, and median distance errors in the title. The console output then aggregates those distance errors across every test trajectory and adds R squared, MAE, MSE, RMSE, MAPE, and explained variance over all predicted coordinates. Absolute numbers depend on the database behind the run, the vessel mix, and the region, so compare the mean and median distance errors of your own runs before and after a change rather than chasing a universal benchmark, and expect visibly weaker forecasts from the one-day NOAA drop-in than from a full-year regional database.

Takeaway

  • Probabilistic teacher forcing trains the decoder on a mix of ground truth and its own predictions, speeding convergence while keeping the inference graph free of ground-truth inputs, and the two graphs share weights by sharing layers.

  • A loss that denormalizes to meters through the haversine judges forecasts in physical units, and extra terms for speed-consistency and continuity are wired in when plain RMSE is not enough.

  • Windowing with deltas, land filtering, and a length-balanced 80/20 split matter as much as the architecture, since a forecaster learns whatever the samples contain.

  • From here, tune the layer widths and the mixing probability with a search library such as HyperOpt, and probe the trained model with permutation feature importance or UMAP projections of its latent space.

Next, Embedding with traj2vec learns a fixed-length representation of an entire voyage instead of stepping through it one position at a time.

Last updated