# Classify by nearest neighbours

Model / supervised

k-nearest neighbours

Page: <https://meridian.online/operations/classify-by-nearest-neighbours>

## Status

Runs as a SQL step.

arcform carries it as a `sql:` step today.

## The DuckDB step

classify by the three nearest labelled rows

```sql
CREATE TEMP TABLE result AS
WITH train(id, x1, x2, label) AS (VALUES (1, 0.1, 0.2, 'a'), (2, 0.3, 0.1, 'a'), (3, 0.2, 0.4, 'a'), (4, 4.0, 3.1, 'b'), (5, 4.2, 3.3, 'b'), (6, 3.9, 2.8, 'b')),
     new(nid, x1, x2) AS (VALUES (10, 0.2, 0.2), (11, 4.1, 3.0)),
     ranked AS (SELECT n.nid, t.label, row_number() OVER (PARTITION BY n.nid ORDER BY list_distance([n.x1, n.x2], [t.x1, t.x2])) AS rk FROM new n CROSS JOIN train t)
SELECT nid, mode(label) AS predicted FROM ranked WHERE rk <= 3 GROUP BY nid ORDER BY nid;
SELECT * FROM result;
SELECT CASE WHEN ((SELECT map_from_entries(list((nid, predicted) ORDER BY nid)) = MAP {10: 'a', 11: 'b'} FROM result)) THEN 'as expected' ELSE error('the two new points were not labelled a and b') END AS verdict;
```

The statement builds its own data.

It needs nothing installed beyond DuckDB itself.

## What other tools call it

Meridian's classification; an independent blind rating agreed on 86.2% of 312 rows (exact class, version 2).

- KNIME Analytics Platform: [`K Nearest Neighbor`](https://api.hub.knime.com/nodes/*XBb4xHehqT9wYCl4?details=full) (read 2026-09-27)
- RapidMiner Studio: [`k-NN`](https://docs.rapidminer.com/latest/studio/operators/modeling/predictive/lazy/k_nn.html) (read 2026-09-27)
