Browse documentation
aner.ml · Reference

Fitted K means and mini batch K means

Fit seeded clustering on protected training rows, preserve observation identity and inspect held out distances.

ImplementedAner 0.1.0 or newer

Aner 0.0.8 adds fitted K means for numerical observations in an AdaptiveFrame. Use a protected training view. Row IDs, group IDs, and any declared target stay outside the distance calculation. Assignments carry their original observation IDs and dimensionless cluster numbers from 0 through clusters - 1.

aner
let plan = ml.kmeans(clusters: 3, seed: 42)
let model = plan.fit(parts.train())
let assignments = model.predict(parts.test())
print(model.evaluate(parts.test()))

Run the survey clustering example from the source root with aner run examples/kmeans_surveys.aner.

OperationBehavior
ml.kmeans(clusters: 8, init: "kmeans++", n_init: 1, max_iterations: 300, tolerance: 0.0001, seed: 0, standardize: true)Creates a reusable KMeansPlan. Each setting can be supplied independently.
ml.minibatch_kmeans(clusters: 8, batch_size: 1024, max_iterations: 100, n_init: 1, seed: 0, standardize: true)Creates a mini batch KMeansPlan with a fixed sampling budget per restart.
plan.fit(training, max_bytes: 67108864, workers: 0)Returns a FittedKMeans from an authorized training view.
plan.cross_validate(training, folds: 5, seed: 42)Returns held out mean squared distance for each fold. Each fold learns its own scaling and centers.
model.predict(observations)Assigns each observation to its nearest center. prediction.values() exposes the assignments and prediction.row_id(i) identifies the corresponding observation.
model.evaluate(held_out)Returns mean squared distance to the nearest fitted center on protected validation or test observations.
model.centers(), model.center(), model.scale()Return the cluster centers and the fitted feature offsets and scales in feature order.
model.inertia(), model.iterations(), model.converged()Report summed squared training distance, completed Lloyd updates or sampling epochs, and whether a convergence criterion was met.
model.align_inputs(observations, columns)Maps present numerical features in independent unlabeled observations into fitted order and converts compatible units.
model.save(path), ml.load_kmeans(path, training_anchor)Save a refit checkpoint and verify its fingerprint when reopening it with a matching trusted training view.

By default, the fit subtracts each training feature mean and divides by its population standard deviation. A constant feature uses a scale of one. Distances and cluster centers use these fitted coordinates. Convert a center back to the input units by multiplying each coordinate by its fitted scale and adding its fitted offset. Set standardize: false to use raw magnitudes. Features must be present and finite.

The plan supports seeded "kmeans++" and "random" initialization. It keeps the first restart with the smallest training inertia. Lloyd updates stop when assignments stabilize or maximum center movement meets tolerance. Equal distances select the lowest cluster ID. An empty cluster retains its previous center. Between updates, exact centroid sums change only for rows that move between clusters. The plan accepts up to 256 clusters, 32 restarts, and 1,000 iterations per restart. The cluster count must fit each training population. Admission also checks the worst case coordinate work implied by the plan and training shape before starting a fit.

The CPU Float64 fit uses bounded worker phases and deterministic reductions. Use workers: 0 for automatic allocation or workers: 1 for serial work. Larger values cap concurrency for eligible fits, up to 16 and within the available CPU budget. cross_validate and load_kmeans accept the same max_bytes and workers settings as fit. The byte budget covers fitted state and numerical scratch, including any admitted temporary feature cache. When the cache does not fit, the full batch solver streams blocks of up to 2,048 rows from the source. Input tables, worker runtime overhead, and allocator overhead are outside the managed budget. model.summary() reports the input cache size, managed peak bound, and requested and effective worker counts.

Mini batch K means

The mini batch plan is available in the Aner 0.0.8 development runtime starting with 0.0.8. It uses the same fitted prediction, grouped validation, and checkpoint methods.

aner
let plan = ml.minibatch_kmeans(clusters: 3, batch_size: 512, max_iterations: 10, seed: 42)
let model = plan.fit(parts.train())
let assignments = model.predict(parts.test())

Each restart uses seeded k means++ on a bounded sample of the training rows. At each seed selection it evaluates several distance weighted candidates and keeps the first one with the lowest resulting sample inertia. Within an update, the plan draws rows with replacement and assigns the entire batch to the current centers. Each center becomes the cumulative mean of the sampled rows assigned to it. A center that receives no rows in an update keeps its previous value. The fit scores each restart on all training rows and keeps the first one with the lowest inertia.

batch_size accepts 1 through 65,536 and clips to the training row count. An epoch takes enough full batches to draw at least as many rows as the training population. Individual rows can appear several times or be absent in an epoch. max_iterations counts these epochs per restart. The plan runs its fixed budget and reports converged: false. The fitted summary includes the effective batch size, update count, and number of sampled rows.

The initialization sample contains up to three times the larger of the effective batch size and cluster count, clipped to the training row count. The byte budget admits this sample, update batches, and numerical scratch. The fit also checks the requested updates and coordinate work before training. An optional feature cache accelerates repeated access when it fits alongside that workspace. With the same ordered training data and settings, cached and streamed fits give identical results across admitted worker counts. Checkpoints retain the estimator and batch size, and ml.load_kmeans verifies the fitted result against the trusted training view. Full batch Lloyd checkpoints retain their existing format.

See the Machine learning module reference for the shared API.

Aner documentation · Reference and guides