A complete clustering experiment
Prepare protected partitions, compare declared seeds, inspect cluster occupancy and report held out scores with native e-means, o-means and p-means.
ImplementedAner 0.1.0 or newerMake each partition do one job
Define the experiment before fitting. Keep test observations reserved until the preprocessing, seeds and evaluation protocol are fixed.
- 01 · Prepare
Split, then standardize
Retain row IDs and feature meaning. Fit the standardizer on the training Dataset and reuse it for validation and test rows.
- 02 · Train
Compare declared seeds
At a fixed cluster count, retain the restart with the lowest training inertia. Record the seed, settings and cluster sizes.
- 03 · Validate
Inspect fit and meaning
Compare validation distortion and occupied clusters. More centers generally lower distortion; that alone does not choose a useful cluster count.
- 04 · Evaluate
Report reserved outcomes
Evaluate the test partition once per declared finalist. Retain squared distances, partition agreement and the complete experiment identity.
A large squared distance can help identify observations for review. Interpreting it requires the feature units, a suitable reference population and a declared threshold.
Use the native e-means, o-means and experimental p-means models to fit centers, compare repeated initializations, evaluate reserved observations and inspect the resulting groups. The diagnostic APIs and runnable CPU Iris workflow require Aner 0.0.10 or newer for the complete three method example. Metal requires a compatible Apple build and device; CUDA requires a separate CUDA enabled profile. The dev.6 M2/V100/L40 study measures these three recipes and separate strict Lloyd CPU supplements; the historical matched M2/V100 measurements retain their dev.4 runtime; the earlier M2 measurements retain their measured 0.0.10-dev.3 identity. Those measured binaries do not qualify a rebuilt stable package.
Prepare observations before fitting
Choose numerical features with meaningful squared Euclidean distance. Identify missing values, nonfinite values, identifiers and categorical columns before building the feature Tensor; fitting rejects nonfinite coordinates rather than silently imputing them. Keep the ordered feature names, units and original row IDs alongside the Tensor. Raw Tensor APIs do not retain Dataset role enforcement or a feature schema.
For a held out study, partition before fitting preprocessing. For related observations, retain grouping so one subject or source does not leak across roles. Fit the Dataset overload of the standardizer on the training view, then apply that same fitted transform to every partition:
import aner.dataset
let parts = dataset.iris().partition(validation: 0.2, test: 0.2, seed: 2026)
let training = parts.train()
let validation = parts.validation()
let scaler = dataset.fit_standardizer(training)
let x_train = dataset.transform(scaler, training.features())
let x_validation = dataset.transform(scaler, validation.features())
print(parts.audit())
print(training.provenance())The transform returns CPU Float64. For Metal, transform first, convert with astype("Float32"), then explicitly move each partition to "mps" with nn.to. Query dtype and device must match the fitted model. Scaling changes the clustering objective; it is a modeling choice, not a universal requirement.
Compare seeds and cluster counts
At a fixed k, fit several declared seeds and retain the run with the lowest training inertia. Record all runs, including unsuccessful or empty cluster outcomes. Sequential restarts can reuse one bounded local execution context; starting overlapping fits on the same exclusive executor is unsupported.
Inspect nearby cluster counts using validation distortion, occupied cluster counts, group interpretation and stability. Distortion generally falls as more centers are allowed, so selecting k solely by its minimum is not a complexity aware selection rule. The Iris example declares k=3 for its known three species benchmark and uses k=2,3,4 only as a validation curve.
import aner.ml
import aner.parallel
import aner.tensor
let x = [[0.0, 0.0], [0.0, 2.0], [10.0, 10.0], [10.0, 12.0]]
let execution = parallel.local(workers: 2)
var best = ml.fit_emeans(x, 2, 3.0, 42, execution: execution)
for restart in Range(2) {
let seed = 43 + restart
let candidate = ml.fit_emeans(x, 2, 3.0, seed, execution: execution)
if candidate.inertia() < best.inertia() { best = candidate }
}
print(best.seed())
let counts = best.cluster_sizes()
for cluster in Range(tensor.rows(counts)) { print(tensor.value(counts, cluster, 0)) }Use e-means as the exhaustive training assignment baseline. For o-means, compare the same input, seeds and epoch budget while recording the coarse cells and probes. More probes improve candidate coverage at additional cost; final evaluation is exhaustive for all three techniques. Equal epochs are not equal quality experiments.
Development 0.0.10-dev.6 adds experimental p-means, which returns the same diagnostic model. The current Iris example predeclares all three methods and uses the default p-means closing length of 0.5. Record its closing mode and length as well as the batch and probes. Choose any alternative controls on validation observations while preserving reserved test rows. A shorter closing length changes the final estimate; it is not evidence of better semantic groups. Historical measurements retain their original method scope and version.
Evaluate and interpret
score(input) is a nonnegative sum of squared nearest center distances, not a negated scoring convention. Divide by the query row count for MSE. squared_distances(input) returns one squared nearest center distance per row, without allocating all query by center distances. cluster_sizes() counts the final training labels, including zero for an unoccupied center.
import aner.ml
import aner.tensor
let model = ml.fit_emeans([[0.0], [2.0], [10.0], [12.0]], 2, 3.0, 42)
let query = [[1.0], [11.0], [20.0]]
print(model.score(query) / Float64(tensor.rows(query)))
let distance = model.squared_distances(query)
print(tensor.value(distance, 2, 0))
let counts = model.cluster_sizes()
for cluster in Range(tensor.rows(counts)) { print(tensor.value(counts, cluster, 0)) }A large distance is a screening signal, not an outlier probability. Calibrate any threshold on an appropriate reserved population, inspect units and distribution shifts, and report the chosen rule. Cluster IDs are arbitrary: use metrics.adjusted_rand_index to compare partitions on the same rows, not classification accuracy on center indices. Reference labels belong in evaluation, not automatically among fitting features. Repeated seeds need not produce independent solutions.
After choosing the protocol using training and validation, evaluate the final test partition once per declared finalist. The example reports all three predeclared algorithms; it does not select a winner by repeatedly examining test results.
Retain the experiment
Record the dataset citation, license and content hash; exact partition selection hashes and row order; ordered feature schema; fitted standardizer offsets and scales; algorithm, seed, recipe and resolved controls; dtype, device, worker count and workspace limit; runtime/source identity; centers, assignments, occupancy, scores and timing scope. Center rows are in transformed coordinates; invert the standardizer with its recorded scale and offset when interpreting original units.
The current CentroidModel is immutable in memory. It does not have a portable model checkpoint or an exact training resume format. Exported centers alone are insufficient to continue EMA training: continuation also needs moving masses, closing statistics, random streams, pass cursor and o-means index/revival state. Dense and contextual K-means checkpoint APIs do not serialize this model.
The native implementation currently supports dense, finite, unweighted Euclidean features. Spherical/cosine clustering, sample weights, automatic k, sampled silhouette, protected Frame adapters, distributed fitting and out of core partial fitting are separate extensions. Existing Dataset partitions, standardization and ARI compose with these models without implying those additional capabilities.
See the Machine learning module reference for the shared API.