Fitted principal component analysis
Fit protected training projections, retain observation identity, inspect variance and replay bounded cached or streamed CPU execution.
ImplementedAner 0.1.0 or newerAner 0.0.8 adds principal component analysis for numerical features in an AdaptiveFrame. Fit the projection on protected training rows. Transforming a view from the experiment preserves its row IDs, group and target fields, split role, and fitted preprocessing provenance.
let projection = ml.pca(components: 2).fit(parts.train())
let training = projection.transform(parts.train())
let testing = projection.transform(parts.test())
let clusters = ml.kmeans(clusters: 3).fit(training)
let assignments = clusters.predict(testing)Run the survey example from the source root
with aner run examples/pca_surveys.aner.
Plan, fit, and inspection
| Operation | Behavior |
|---|---|
ml.pca(components: 2, standardize: false) | Creates a PCAPlan with the requested positive component count. |
plan.fit(training, max_bytes: 67108864, workers: 0) | Returns a FittedPCA from a protected training view. |
plan.cross_validate(training, folds: 5, seed: 42, max_bytes: 67108864, workers: 0) | Returns a List of mean squared reconstruction distances, one per held out group fold. Each fold learns its own centering, scaling, and basis. |
model.transform(observations) | Returns an AdaptiveFrame with principal components as its feature columns, using the fitted byte budget. |
model.evaluate(held_out) | Returns mean squared reconstruction distance per observation in fitted coordinates. |
model.components(), model.center(), model.scale() | Return a K × D basis and 1 × D fitted feature offsets and scales in input order. |
model.explained_variance(), model.explained_variance_ratio() | Return 1 × K Tensors containing each retained component's sample variance and fraction of total training variance. |
model.align_inputs(observations, columns) | Maps an independent unlabeled frame into fitted input order and converts compatible units before projection. |
model.summary() | Reports fitted dimensions, numerical solver, rank, variance, workers, cache size, and managed memory. |
model.save(path), ml.load_pca(path, training_anchor, max_bytes: 67108864, workers: 0) | Save a refit checkpoint and verify the fitted projection when reopening it with a trusted training view. |
Here D is the input feature count and K is the requested component count.
Declared row IDs, groups, and targets never enter the decomposition. Both
unlabeled observations and frames with a declared target are accepted.
Coordinates and scientific scope
PCA centers every feature using its training mean. Raw PCA requires a common
feature unit and preserves that unit in PC1, PC2, and subsequent component
columns. With standardize: true, the fit also divides by the training
population standard deviation and the component columns are dimensionless.
Constant features use a scale of one. Feature values must be present and
finite. Declared targets stay available for downstream fitting. Component
names start at PC1. A deterministic suffix avoids collisions with preserved
identity, group, or target names.
The fit requires at least two training rows. The requested component count
must fit both the training row count and feature count. Component variance
uses the sample denominator rows - 1. Explained variance ratios are zero
when all training features are constant. Repeated singular values can admit
multiple bases for the same subspace.
evaluate averages the squared residual norm over held out observations,
after applying the fitted centering and optional scaling. It sums over input
features rather than averaging over them. The returned Float64 therefore
represents squared input units for raw PCA and a dimensionless distance for
standardized PCA. It requires a disjoint protected validation or test view.
Training data cannot be relabeled as held out. Transformation itself also
accepts training rows, so its output can feed a later fitted model.
Grouped cross validation accepts 2 through 32 folds, keeps each declared
group together, and processes folds sequentially. Every fitting fold must
have at least two rows and enough rows and features for components.
Cross validate a PCA plan on the original protected training features so
centering, scaling, and the basis are learned within each fold.
Memory and local CPU workers
The CPU Float64 fit uses fixed QR blocks and a small singular value
decomposition. On supported systems, each numerical worker uses
single threaded Accelerate routines. A portable solver serves other builds.
workers: 0 selects workers automatically within the available CPU budget.
workers: 1 runs serially. A larger value requests a concurrency cap within
the available allocation. This PCA solver uses at most 16 effective workers.
The count can be lower for small inputs or a tighter memory budget. These
workers run locally.
max_bytes defaults to 64 MiB and limits managed fitting payload. This covers
fitted membership, centers and scales, component values, numerical scratch,
and any temporary feature cache. The fit admits a row major cache only when the
cache and decomposition workspace fit together. Otherwise it rereads bounded
feature blocks from the immutable source table. Set the budget and worker
count when fitting.
let plan = ml.pca(components: 2)
let model = plan.fit(parts.train(), max_bytes: 8388608, workers: 1)
print(model.summary())
let projected = model.transform(parts.test())For unscaled fits with one worker and resident Float64 columns, preparation validates values and accumulates exact training means in small tiles while retaining the cache and fingerprint in source row order. Cached QR combines centering with matrix packing and omits the unused row scratch buffer. These paths preserve the fitted coordinates and exact replay contract.
Streamed fits use bounded batches for the initial validation, mean, and fingerprint scan. Eligible unscaled fits with one worker and resident Float64 columns then write centered values directly into the QR buffers, omitting the intermediate row packing scratch. Other inputs use the bounded feature adapter with the same validation and numerical contracts.
A small fit can still admit a cache with an 8 MiB cap. A zero
input_cache_bytes value identifies a streamed fit. Streaming avoids a full
additional feature matrix. The source DataTable may still reside in memory.
Existing input tables and contextual views, object and allocator overhead,
worker runtime overhead, and numerical provider internal allocations are
outside this managed cap. CSV collection has its own memory budget. Process
resident memory includes all these allocations and is a separate measure.
Transformation uses the fitted cap to admit the retained model, output
component columns, a shared source row index map, and a small numerical row
buffer. It has no separate max_bytes or workers arguments. A fit can
therefore succeed while transformation of a larger observation set exceeds
the cap. Input frames retain their existing row and schema limits.
model.summary() includes solver, workers_requested,
workers_effective, input_cache_bytes, managed_peak_bound, and
retained_model_bytes. The managed peak accounts for the selected execution,
rather than measuring process memory. Admission first checks a conservative
workspace bound. Omitting unused scratch can lower the reported peak without
lowering that admission minimum, so the reported peak is not a guaranteed
minimum accepted max_bytes value.
Exact replay and checkpoints
For the same ordered input, options, solver, and supported numerical environment, cached and streamed fits produce identical Float64 centers, scales, components, variances, projections, and reconstruction scores. Changing an admitted worker count preserves these results. Fixed QR blocks and ordered merges keep the arithmetic order independent of scheduling. Worker count, cache choice, and byte cap do not change the checkpoint's fitted state identity. This contract does not promise identical bases across different solvers, compilers, or numerical providers.
save writes a compact refit checkpoint to a new path. Loading requires the
live trusted training view, refits with the recorded solver, and verifies
ordered source and feature provenance, fitted preparation, and complete
decomposition state. A changed training anchor or unavailable recorded solver
fails verification. The checkpoint is not a standalone copy of the training
data. Reload can use a different admitted byte cap or worker count, including
switching between a cached fit and a streamed fit.
See the Machine learning module reference for the shared API.