Skip to main content

Pipelines

End-to-end classification and clustering orchestration

Overview

MLCore provides two pipeline entry points that compose all lower-level components into single-call workflows. Both pipelines follow the same pattern: configure → run → check result.

Classification Pipeline

ClassificationPipeline (pipelines/ClassificationPipeline.hpp) orchestrates supervised classification end-to-end.

Pipeline Stages

For frame-based models (Random Forest, Naive Bayes, Logistic Regression):

ValidatingFeatures → ConvertingFeatures → AssemblingLabels →
BalancingClasses → Training → Predicting → ComputingMetrics → WritingOutput → Complete

For sequence models (HMM):

ValidatingFeatures → ConvertingFeatures → AssemblingLabels →
BalancingClasses → SegmentingSequences → Training → Predicting →
ComputingMetrics → WritingOutput → Complete

The SegmentingSequences stage uses SequenceAssembler::segment() to split the feature matrix and labels into contiguous temporal segments (based on gaps in TimeFrameIndex). Training then routes through trainSequences() and prediction through predictSequences(), preserving temporal structure for models like HMMs. When constrained_decoding is enabled and training labels are available, prediction uses predictSequencesConstrained() to clamp the HMM’s initial distribution at segment boundaries where the ground truth state is known.

Configuration

ClassificationPipelineConfig config;

// Model
config.model_name = "Random Forest";
config.model_params = &rf_params;  // or nullptr for defaults

// Features
config.feature_tensor_key = "ml_features";

// Labels (variant — pick one mode)
config.label_config = LabelFromIntervals{"Contact", "No Contact"};
config.label_interval_key = "contact_intervals";

// Conversion
config.conversion_config.zscore_normalize = true;

// Balancing (optional)
config.balance_classes = true;
config.balancing_config.strategy = BalancingStrategy::Subsample;

// Prediction region
config.prediction_region.predict_all_rows = true;
// Optional: filter output to a specific interval (runs Viterbi on full span
// for temporal context, writes only frames within the interval)
// config.prediction_region.prediction_interval_key = "target_region";
// config.prediction_region.constrained_decoding = true; // HMM warm-start

// Output
config.output_config.output_prefix = "Predicted:";
config.time_key_str = "camera";

Entry Point

auto result = runClassificationPipeline(dm, registry, config, progress_callback);

if (result.success) {
    // result.training_observations, result.num_classes
    // result.binary_train_metrics or result.multi_class_train_metrics
    // result.writer_result contains created DataManager keys
    // result.trained_model can be reused or saved
}

Result Fields

Field Description
success Whether the pipeline completed
error_message Human-readable error (if failed)
failed_stage Which stage failed
training_observations Count after NaN dropping and balancing
num_features / num_classes Training dimensions
class_names From label assembly
rows_dropped_nan NaN/Inf rows removed
was_balanced Whether balancing was applied
binary_train_metrics Accuracy, sensitivity, specificity, F1, confusion matrix
multi_class_train_metrics Per-class precision/recall/F1, overall accuracy
prediction_observations Count of predicted frames
writer_result Created DataManager keys, group IDs
trained_model Ownership transferred — reusable or saveable

Progress Callback

auto progress = [](ClassificationStage stage, std::string const & msg) {
    spdlog::info("Pipeline: {} — {}", toString(stage), msg);
};

Clustering Pipeline

ClusteringPipeline (pipelines/ClusteringPipeline.hpp) orchestrates unsupervised clustering end-to-end.

Pipeline Stages

ValidatingFeatures → ConvertingFeatures → Fitting →
AssigningClusters → WritingOutput → Complete

Configuration

ClusteringPipelineConfig config;

// Model
config.model_name = "K-Means";
config.model_params = &kmeans_params;

// Features
config.feature_tensor_key = "pca_features";

// Conversion
config.conversion_config.zscore_normalize = true;

// Assignment region
config.assignment_region.assign_all_rows = true;

// Output
config.output_config.output_prefix = "Cluster:";
config.output_config.write_to_putative_groups = true;
config.output_config.write_intervals = true;
config.output_config.write_probabilities = true;  // GMM only
config.time_key_str = "camera";

Entry Point

auto result = runClusteringPipeline(dm, registry, config, progress_callback);

if (result.success) {
    // result.num_clusters, result.cluster_sizes, result.cluster_names
    // result.interval_keys — created DigitalIntervalSeries keys
    // result.probability_keys — created AnalogTimeSeries keys (GMM)
    // result.putative_group_ids — created entity group IDs
    // result.fitted_model — reusable
}

Result Fields

Field Description
success Whether the pipeline completed
error_message Human-readable error (if failed)
fitting_observations Count after NaN dropping
num_features / num_clusters Fitting dimensions
noise_points DBSCAN noise count (0 for others)
cluster_sizes Per-cluster observation counts
cluster_names "{prefix}{index}" format
interval_keys Created DigitalIntervalSeries DataManager keys
probability_keys Created AnalogTimeSeries keys (GMM soft assignments)
putative_group_ids Created entity group IDs
fitted_model Ownership transferred — reusable

Error Handling

Both pipelines use early-return on failure. The failed_stage field indicates where the problem occurred. Common failure modes:

  • ValidatingFeatures: Feature tensor not found, not 2D, or empty
  • ConvertingFeatures: All rows dropped due to NaN/Inf
  • AssemblingLabels: No labels found, incompatible row types
  • SegmentingSequences: No contiguous sequences meeting minimum length
  • Training/Fitting: Model failed internally (rare with valid data)
  • WritingOutput: DataManager write failure

Bounding Span (Prediction Region Filtering)

See Prediction Regions for the full design of bounding span computation, output filtering, and constrained Viterbi warm-start.

Summary: BoundingSpan.hpp (pipelines/BoundingSpan.hpp) provides utilities for computing and applying temporal bounding spans when prediction is restricted to a specific interval. When prediction_interval_key is set, the pipeline computes the temporal union of training and prediction intervals, filters features to that range (preserving HMM context), runs prediction, then filters output back to the requested frames.

Function Description
computeIntervalBounds(series) Returns [min(start), max(end)] of all intervals
computeRowTimeBounds(times) Returns [min, max] of a time vector
mergeSpans(a, b) Returns the union span covering both inputs
filterRowsToSpan(features, times, span) Filters columns and times to span
filterPredictionsToIntervals(preds, probs, times, intervals) Keeps only frames within intervals

Dimensionality Reduction Pipeline

DimReductionPipeline (pipelines/DimReductionPipeline.hpp) orchestrates dimensionality reduction end-to-end.

Pipeline Stages

ValidatingFeatures → ConvertingFeatures → FittingAndTransforming → WritingOutput → Complete

Configuration

DimReductionPipelineConfig config;

// Model
config.model_name = "PCA";
config.model_params = &pca_params;  // or nullptr for defaults

// Features
config.feature_tensor_key = "encoder_features";

// Conversion
config.conversion_config.drop_nan = true;
config.conversion_config.zscore_normalize = false;

// Output
config.output_config.output_key = "encoder_features_pca";
config.output_config.time_key_str = "camera";

// Thread safety (defer writes for background execution)
config.defer_dm_writes = true;

Entry Point

auto result = runDimReductionPipeline(dm, registry, config, progress_callback);

if (result.success) {
    // result.num_observations, result.num_input_features, result.num_output_components
    // result.explained_variance_ratio — per-component (PCA only)
    // result.output_key — DataManager key of new TensorData
    // result.fitted_model — reusable for re-projection
}

Result Fields

Field Description
success Whether the pipeline completed
error_message Human-readable error (if failed)
num_observations Count after NaN dropping
num_input_features / num_output_components Dimensions
rows_dropped_nan Rows dropped due to NaN/Inf
explained_variance_ratio Per-component variance (PCA; empty for others)
output_key Created TensorData DataManager key
deferred_output shared_ptr<TensorData> for main-thread writing
fitted_model Ownership transferred — reusable

Row Preservation

The output TensorData preserves the input’s RowDescriptor type:

  • TimeFrameIndex: Filtered time indices are stored using SparseTimeIndexStorage
  • Interval: Filtered intervals are carried through
  • Ordinal: Row count matches observation count after NaN dropping

Column names are auto-generated: "PC1", "PC2", … for PCA; "Dim1", "Dim2", … for other algorithms.

Data Layout Convention

WarningArmadillo ↔︎ TensorData layout mismatch

Armadillo stores matrices in column-major order, while TensorData factories (createTimeSeries2D, createOrdinal2D, createFromIntervals) expect flat data in row-major order. When converting an arma::fmat to TensorData, you must not use memptr() directly — this produces column-major data that will be silently reinterpreted as row-major, scrambling all values across observations. Instead, extract elements in explicit row-major order:

arma::fmat output_fmat = /* ... */;
std::vector<float> flat_data(output_fmat.n_elem);
for (arma::uword r = 0; r < output_fmat.n_rows; ++r) {
    for (arma::uword c = 0; c < output_fmat.n_cols; ++c) {
        flat_data[r * output_fmat.n_cols + c] = output_fmat(r, c);
    }
}

Supervised Dimensionality Reduction Pipeline

SupervisedDimReductionPipeline (pipelines/SupervisedDimReductionPipeline.hpp) combines label assembly with supervised projection to produce a logit-space TensorData output.

The pipeline trains on labeled observations only, then transforms all valid rows (labeled and unlabeled) to produce a complete output tensor. This enables scatter visualization where both labeled clusters and unlabeled context points are visible.

Pipeline Stages

ValidatingFeatures → ConvertingFeatures → AssemblingLabels →
FilteringTrainingRegion → FittingAndTransforming → WritingOutput → Complete

Configuration

SupervisedDimReductionPipelineConfig config;

// Model
config.model_name = "Logit Projection";        // must be SupervisedDimensionalityReduction
config.model_params = &logit_params;            // or nullptr for defaults

// Features
config.feature_tensor_key = "encoder_features"; // must have RowType::TimeFrameIndex

// Labels (variant — choose one mode)
config.label_config = LabelFromIntervals{"Contact", "NoContact"};
config.label_interval_key = "contact_intervals";

// Conversion
config.conversion_config.drop_nan = true;
config.conversion_config.zscore_normalize = false;

// Training region (optional — restrict which labeled rows are used for fitting)
config.training_interval_key = "training_intervals"; // empty = use all labeled rows

// Output
config.output_key = "logit_projection";
config.time_key_str = "camera";
config.defer_dm_writes = false;                 // set true for background thread

Label Modes

The pipeline supports the same 4 label modes as ClassificationPipeline:

Mode Type Notes
LabelFromIntervals DigitalIntervalSeries key Binary: inside/outside interval
LabelFromTimeEntityGroups EntityGroupManager group IDs Per-group class assignment
LabelFromDataEntityGroups EntityGroupManager group IDs Per-entity group membership
LabelFromEvents DigitalEventSeries key Event proximity labeling

Group-based modes produce unlabeled rows (rows with no group assignment), marked with sentinel value num_classes. These rows are excluded from training but still projected by the fitted model into the output tensor.

Training Region

When training_interval_key is set (non-empty), the FilteringTrainingRegion stage restricts the labeled training rows to only those whose TimeFrameIndex falls within any interval of the specified DigitalIntervalSeries. This uses the same filterTrainingRowsToIntervals() utility from BoundingSpan.hpp as the classification pipeline.

  • If the key references a missing DigitalIntervalSeries, the pipeline fails at FilteringTrainingRegion with an error message.
  • If training_interval_key is empty, the stage is a no-op and all labeled rows are used.
  • The transform is still applied to all valid rows — only training (fitting) is restricted.
  • result.rows_excluded_by_training_region reports how many labeled rows were excluded.

Column Naming

Output columns are named "Logit:<ClassName>" using the actual class names from label assembly, not generic indices. For LabelFromIntervals{"Contact", "NoContact"}:

  • Class 0 (negative/outside) → "Logit:NoContact"
  • Class 1 (positive/inside) → "Logit:Contact"

Note: Class 0 is always the negative/outside class for interval-based labeling. Use the actual class names to identify columns — do not rely on column order.

Entry Point

auto result = runSupervisedDimReductionPipeline(dm, registry, config, progress_callback);

if (result.success) {
    // result.num_observations — all valid rows (NaN-dropped)
    // result.num_training_observations — labeled subset used for fitting
    // result.unlabeled_count — rows projected but excluded from training
    // result.num_classes, result.class_names
    // result.output_key — DataManager key of new TensorData
    // result.fitted_model — reusable for re-projection
}

Result Fields

Field Description
success Whether the pipeline completed
error_message Human-readable error (if failed)
failed_stage Which stage failed
num_observations All valid rows after NaN dropping
num_training_observations Labeled rows used for fitting
num_input_features Number of input tensor columns
num_output_dimensions Number of classes (output columns)
rows_dropped_nan Rows dropped due to NaN/Inf
unlabeled_count Rows excluded from training (group modes)
rows_excluded_by_training_region Labeled rows excluded by training region filter
num_classes Number of classes discovered
class_names Class name per output column (no “Logit:” prefix)
output_key Created TensorData DataManager key
deferred_output shared_ptr<TensorData> for main-thread writing
fitted_model Ownership transferred — reusable

Relationship to Other Pipelines

Pipeline Labels Transforms Output
DimReductionPipeline None (unsupervised) All rows TensorData: reduced space
ClassificationPipeline Required Labeled rows Predictions + metrics
SupervisedDimReductionPipeline Required for training All rows TensorData: logit space

The SupervisedDimReductionPipeline is unique in that it trains on a labeled subset but produces output that covers all valid inputs — filling in logit-space projections even for rows with no label.