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

Clustering with Scikit Learn

Find shipping lanes, anchorages, and vessel behavior groups in one day of NOAA AIS data by running DBSCAN and KMeans over AISdb tracks.

AIS gives you millions of position reports, but a raw stream of latitude and longitude says little on its own. In this tutorial you build two clustering pipelines on one open day of NOAA data over the Gulf of Mexico. DBSCAN pools every position to surface ports, anchorages, and fairways as dense hotspots, and KMeans groups whole tracks by movement features to separate vessels underway from vessels that barely move, the same machinery anomaly detection starts from.

What you will learn

  • Decode a NOAA day file into SQLite and pull vessel tracks with AISdb

  • Run DBSCAN with a haversine metric so eps means kilometers, not degrees

  • Reduce each track to a six-value movement feature vector with delta_knots

  • Choose the KMeans cluster count with a silhouette sweep and read the cluster profiles

Prerequisites

pip install aisdb scikit-learn matplotlib

One data file, the open NOAA day AIS_2020_01_01.zip, decoded via aisdb.decode_msgs in step 1. Every number and figure below is the output of running this page end to end on AISdb 1.8.0-alpha.

1. Decode the day file and generate tracks

decode_msgs accepts the compressed archive directly, so one call covers download to database, and the decode is a one-time cost (this run chewed through seven million messages on a heavily loaded shared server). The query window covers the Gulf of Mexico, a busy mix of port calls, offshore-supply runs, and through traffic, and TrackGen yields one dictionary per vessel with aligned lon, lat, time, and sog arrays, materialized with list(...) because both pipelines iterate the tracks twice.

load_tracks.py
import urllib.request
from datetime import datetime
from pathlib import Path

import numpy as np
import aisdb
from aisdb import SQLiteDBConn, DBQuery
from aisdb.database import sqlfcn_callbacks
from aisdb.gis import delta_knots

Path('./data').mkdir(exist_ok=True)
zip_path = Path('./data/AIS_2020_01_01.zip')
dbpath = './data/ais_2020_01_01.db'
url = 'https://coast.noaa.gov/htdata/CMSP/AISDataHandler/2020/AIS_2020_01_01.zip'
if not zip_path.exists():
    urllib.request.urlretrieve(url, zip_path)

if not Path(dbpath).exists():
    with SQLiteDBConn(dbpath=dbpath) as dbconn:
        aisdb.decode_msgs(filepaths=[str(zip_path)], dbconn=dbconn,
                          source='NOAA', verbose=True)

with SQLiteDBConn(dbpath=dbpath) as dbconn:
    qry = DBQuery(dbconn=dbconn,
                  start=datetime(2020, 1, 1), end=datetime(2020, 1, 2),
                  xmin=-98, xmax=-80, ymin=24, ymax=31,  # Gulf of Mexico
                  callback=sqlfcn_callbacks.in_bbox_time_validmmsi)
    tracks = list(aisdb.track_gen.TrackGen(qry.gen_qry(), decimate=False))

n_positions = sum(len(t['time']) for t in tracks)
print(f"loaded {len(tracks)} vessel tracks ({n_positions:,} positions)")

2. Find spatial hotspots with DBSCAN

DBSCAN needs no cluster count up front, finds arbitrarily shaped dense regions, and labels sparse points as noise instead of forcing them into a group. The detail that trips people up is the metric. haversine expects radians, so eps is also in radians, and a 1 km neighborhood becomes 1 / 6371 (Earth's mean radius in km). A seeded 200,000-point subsample keeps the ball-tree search fast and exactly reproducible.

Both parameters have physical meaning, kilometers and a point count, so you can reason about them instead of guessing. The noise points are mostly vessels in open transit whose positions never pile up densely enough to anchor a cluster.

3. Build per-track movement features

Hotspots tell you where things happen, not how vessels behave. For behavior, reduce each track to a small vector, speed statistics, bounding-box extent, duration, and message count. The 80-knot sanity filter drops tracks with GPS teleports, which would otherwise blow up the speed features.

4. Sweep k, fit KMeans, read the profiles

Standardize the columns first, KMeans measures Euclidean distance and the message count would otherwise dominate the knots. Then sweep k and keep the silhouette winner, which rewards clusters that are tight internally and well separated, and print each cluster's feature means to see what it represents.

The score peaks at k=2 and never recovers, so the dominant structure in a port-heavy day is binary. The profiles read it off directly, cluster 0 is 814 underway transits at about nine knots sweeping roughly a degree of latitude and longitude, cluster 1 is 5052 moored and anchored tracks averaging under a knot across a tenth of a degree.

Results

DBSCAN hotspots over the Gulf of Mexico, one NOAA day subsampled to 200,000 positions. The 26,630 noise points render in one color and trace the offshore fairways; the 555 dense clusters (eps 1 km, min_samples 25) pile up along the coast at ports, anchorages, and platforms.
KMeans behavior groups, same day and region. The silhouette sweep selects k=2, splitting 814 underway transits (blue) whose paths trace the lanes across the Gulf from 5052 near-stationary moored and anchored tracks (orange) hugging the ports and coast.

The two-cluster answer is real but coarse. One day of port-heavy AIS is overwhelmingly stationary vessels, so the strongest available signal is moving versus not moving; a longer window plus features like heading variance and turning rate is what separates transit types and fishing patterns. Run tracks through the denoising in Data Cleaning first when precision matters, and treat any unsupervised result as a hypothesis to validate against charts and domain knowledge.

Takeaway

  • DBSCAN with a haversine metric finds ports, anchorages, and fairways with parameters you can reason about in kilometers and point counts.

  • Six movement features per track plus standardization is enough for KMeans to separate underway traffic from moored vessels.

  • The silhouette sweep turns "how many clusters" from a guess into a defensible choice, but sanity-check that the winner is interpretable.

  • Subsample pooled positions with a seeded generator; haversine DBSCAN over millions of raw points is slow and memory hungry.

Next, Kalman Filters with FilterPy models how a single track evolves through time and smooths its noise away.

References

Last updated