Skip to main content

MLCore

MLCore

Classes

Name
struct MLCore::ConversionConfig
Configuration for TensorData → arma::mat conversion.
struct MLCore::ConvertedFeatures
Result of converting a TensorData to arma::mat.
struct MLCore::LabelSourceTimeGroups
Describes a label source based on entity groups of time entities.
struct MLCore::LabelSourceIntervals
Describes a label source based on a DigitalIntervalSeries.
struct MLCore::LabelSourceEntityGroups
Describes a label source based on entity groups on data objects.
struct MLCore::TensorValidationResult
Result of standalone tensor validation.
struct MLCore::FeatureLabelValidationResult
Full validation result including label compatibility.
struct MLCore::LabelFromIntervals
Configuration for binary labeling from a DigitalIntervalSeries.
struct MLCore::LabelFromTimeEntityGroups
Configuration for multi-class labeling from TimeEntity groups.
struct MLCore::LabelFromDataEntityGroups
Configuration for multi-class labeling from data-object entity groups.
struct MLCore::LabelFromEvents
Configuration for binary labeling from a DigitalEventSeries.
struct MLCore::AssembledLabels
Result of label assembly.
struct MLCore::BinaryClassificationMetrics
Metrics for a binary (two-class) classification problem.
struct MLCore::MultiClassMetrics
Metrics for a multi-class classification problem.
class MLCore::MLDimReductionOperation
Abstract base for dimensionality reduction operations.
class MLCore::MLModelOperation
Abstract base for all ML model operations.
struct MLCore::MLModelParametersBase
Abstract base for all model-specific parameter sets.
struct MLCore::RandomForestParameters
Parameters for Random Forest classifier.
struct MLCore::NaiveBayesParameters
Parameters for Naive Bayes classifier.
struct MLCore::LogisticRegressionParameters
Parameters for Logistic Regression classifier.
struct MLCore::SoftmaxRegressionParameters
Parameters for Softmax Regression (multi-class logistic regression).
struct MLCore::KMeansParameters
Parameters for K-Means clustering.
struct MLCore::DBSCANParameters
Parameters for DBSCAN clustering.
struct MLCore::GMMParameters
Parameters for Gaussian Mixture Model clustering.
struct MLCore::PCAParameters
Parameters for PCA dimensionality reduction.
struct MLCore::TSNEParameters
Parameters for t-SNE dimensionality reduction.
struct MLCore::RobustPCAParameters
Parameters for Robust PCA (ROSL) dimensionality reduction.
struct MLCore::ICAParameters
Parameters for ICA (RADICAL algorithm) dimensionality reduction.
struct MLCore::LogitProjectionParameters
Parameters for Logit Projection (supervised dimensionality reduction).
struct MLCore::LARSProjectionParameters
Parameters for LARS Projection (supervised dimensionality reduction).
struct MLCore::SupervisedPCAParameters
Parameters for Supervised PCA dimensionality reduction.
struct MLCore::SupervisedRobustPCAParameters
Parameters for Supervised Robust PCA dimensionality reduction.
struct MLCore::HMMParameters
Parameters for Hidden Markov Model (Gaussian emissions).
class MLCore::MLModelRegistry
Factory registry for ML model operations.
class MLCore::MLSupervisedDimReductionOperation
Abstract base for supervised dimensionality reduction operations.
class MLCore::HiddenMarkovModelOperation
Gaussian HMM classifier wrapping mlpack::HMM<GaussianDistribution<>>.
class MLCore::LARSProjectionOperation
LARS-based supervised feature selection.
class MLCore::LogisticRegressionOperation
Logistic Regression classifier wrapping mlpack::LogisticRegression.
class MLCore::LogitProjectionOperation
Supervised linear projection via softmax logit extraction.
class MLCore::NaiveBayesOperation
Naive Bayes classifier wrapping mlpack::NaiveBayesClassifier.
class MLCore::RandomForestOperation
Random Forest classifier wrapping mlpack::RandomForest.
class MLCore::SoftmaxRegressionOperation
Multi-class Softmax Regression classifier wrapping mlpack::SoftmaxRegression.
class MLCore::SupervisedPCAOperation
Supervised PCA dimensionality reduction.
class MLCore::SupervisedRobustPCAOperation
Supervised Robust PCA dimensionality reduction.
class MLCore::DBSCANOperation
DBSCAN clustering wrapping mlpack::DBSCAN.
class MLCore::GaussianMixtureOperation
Gaussian Mixture Model clustering wrapping mlpack::GMM.
class MLCore::ICAOperation
ICA via mlpack’s RADICAL algorithm.
class MLCore::KMeansOperation
K-Means clustering wrapping mlpack::KMeans.
class MLCore::PCAOperation
PCA dimensionality reduction via mlpack.
class MLCore::RobustPCAOperation
Robust PCA dimensionality reduction via ROSL.
class MLCore::TSNEOperation
t-SNE dimensionality reduction via tapkee
struct MLCore::PredictionOutput
Encapsulates the output of a classification or clustering model.
struct MLCore::PredictionWriterConfig
Configuration for how predictions are written to the DataManager.
struct MLCore::PredictionWriterResult
Summary of what the PredictionWriter produced.
struct MLCore::BoundingSpan
A closed temporal range [min_time, max_time].
struct MLCore::FilteredRows
Result of filtering features and times to a bounding span.
struct MLCore::FilteredTrainingRows
Result of filtering feature rows + labels to a set of intervals.
struct MLCore::FilteredPredictions
Result of filtering predictions to a set of intervals.
struct MLCore::PredictionRegionConfig
Specifies where prediction should be performed.
struct MLCore::ClassificationPipelineConfig
Full configuration for the classification pipeline.
struct MLCore::ClassificationPipelineResult
Complete result of a classification pipeline run.
struct MLCore::ClusterAssignmentRegion
Specifies where cluster assignment should be performed.
struct MLCore::ClusteringOutputConfig
Configuration for the clustering pipeline output.
struct MLCore::ClusteringPipelineConfig
Full configuration for the clustering pipeline.
struct MLCore::ClusteringPipelineResult
Complete result of a clustering pipeline run.
struct MLCore::DimReductionOutputConfig
Output configuration for the dimensionality reduction pipeline.
struct MLCore::DimReductionPipelineConfig
Full configuration for the dimensionality reduction pipeline.
struct MLCore::DimReductionPipelineResult
Complete result of a dimensionality reduction pipeline run.
struct MLCore::SequenceSegment
A single contiguous temporal segment of features and labels.
struct MLCore::SequenceAssemblerConfig
Configuration for sequence segmentation.
class MLCore::SequenceAssembler
Segments flat matrices into contiguous temporal sequences.
struct MLCore::SupervisedDimReductionPipelineConfig
Full configuration for the supervised dimensionality reduction pipeline.
struct MLCore::SupervisedDimReductionPipelineResult
Complete result of a supervised dimensionality reduction pipeline run.
struct MLCore::BalancingConfig
Configuration for class balancing.
struct MLCore::BalancedData
Result of a class balancing operation.

Types

Name
enum class RowCompatibility { Compatible, EmptyTensor, Not2D, NoColumns, RowTypeMismatch, TimeFrameMismatch, RowCountMismatch}
Reason why a feature tensor is incompatible with a label source.
enum class RegularizationType { LASSO, Ridge, ElasticNet}
Regularization mode for LARS Projection.
enum class MLTaskType { BinaryClassification, MultiClassClassification, Clustering, DimensionalityReduction, SupervisedDimensionalityReduction}
Describes the type of ML task a model operation supports.
enum class ClassificationStage { ValidatingFeatures, ConvertingFeatures, AssemblingLabels, BalancingClasses, SegmentingSequences, Training, Predicting, ComputingMetrics, WritingOutput, Complete, Failed}
Stages of the classification pipeline.
enum class ClusteringStage { ValidatingFeatures, ConvertingFeatures, Fitting, AssigningClusters, WritingOutput, Complete, Failed}
Stages of the clustering pipeline.
enum class DimReductionStage { ValidatingFeatures, ConvertingFeatures, FittingAndTransforming, WritingOutput, Complete, Failed}
Stages of the dimensionality reduction pipeline.
enum class SupervisedDimReductionStage { ValidatingFeatures, ConvertingFeatures, AssemblingLabels, FilteringTrainingRegion, FittingAndTransforming, WritingOutput, Complete, Failed}
Stages of the supervised dimensionality reduction pipeline.
enum class BalancingStrategy { Subsample, Oversample}
Strategy used for class balancing.
using std::variant< LabelSourceTimeGroups, LabelSourceIntervals, LabelSourceEntityGroups > LabelSourceDescriptor
Describes the expected label source for validation.
using std::variant< LabelFromIntervals, LabelFromTimeEntityGroups, LabelFromDataEntityGroups, LabelFromEvents > LabelAssemblyConfig
Configuration variant for label assembly.
using mlpack::HMM< mlpack::GaussianDistribution<> > GaussianHMM
using mlpack::HMM< mlpack::DiagonalGaussianDistribution<> > DiagonalGaussianHMM
using mlpack::HMM< mlpack::GMM > GMMEmissionHMM
using mlpack::HMM< mlpack::DiagonalGMM > DiagonalGMMEmissionHMM
using mlpack::LogisticRegression< arma::mat > LRModel
typedef mlpack::SoftmaxRegression< arma::mat > SRModel
using mlpack::NaiveBayesClassifier<> NBModel
using mlpack::RandomForest< mlpack::GiniGain, mlpack::MultipleRandomDimensionSelect > RFModel
using std::function< void(ClassificationStage, std::string const &)> PipelineProgressCallback
Optional callback for pipeline progress reporting.
using std::function< void(ClusteringStage, std::string const &)> ClusteringProgressCallback
Optional callback for pipeline progress reporting.
using std::function< void(DimReductionStage, std::string const &)> DimReductionProgressCallback
Progress callback type.
using std::function< void(SupervisedDimReductionStage, std::string const &)> SupervisedDimReductionProgressCallback
Progress callback type.

Functions

Name
std::vector< EntityId > registerTimeEntities(DataManager & dm, std::string const & time_key_str, std::span< TimeFrameIndex const > frames)
Register a set of arbitrary TimeFrameIndex values as TimeEntities.
std::vector< EntityId > intervalsToTimeEntities(DataManager & dm, DigitalIntervalSeries const & intervals, std::string const & time_key_str)
Expand a DigitalIntervalSeries into individual TimeEntity IDs.
std::shared_ptr< DigitalIntervalSeries > timeEntitiesToIntervals(DataManager & dm, GroupId group_id, std::string const & time_key_str)
Convert a group of TimeEntity IDs into a DigitalIntervalSeries.
std::pair< std::vector< double >, std::vector< double > > zscoreNormalize(arma::mat & matrix, double epsilon =1e-10)
Apply z-score normalization to an arma::mat in-place.
void applyZscoreNormalization(arma::mat & matrix, std::vector< double > const & means, std::vector< double > const & stds, double epsilon =1e-10)
Apply previously computed z-score parameters to new data.
ConvertedFeatures convertTensorToArma(TensorData const & tensor, ConversionConfig const & config ={})
Convert a TensorData feature matrix to the arma::mat format expected by mlpack.
ConvertedFeatures convertTensorToArmaRowMajor(TensorData const & tensor, ConversionConfig const & config ={})
Convert a TensorData to a row-major arma::mat (observations × features).
std::string toString(RowCompatibility rc)
Human-readable description of a RowCompatibility value.
TensorValidationResult validateFeatureTensor(TensorData const & features)
Validate that a TensorData is structurally suitable as an ML feature matrix.
std::size_t countNonFiniteRows(TensorData const & features)
Check if a feature tensor contains any NaN or Inf values.
std::vector< std::size_t > findNonFiniteRows(TensorData const & features)
Get the indices of rows that contain NaN or Inf values.
FeatureLabelValidationResult validateFeatureLabelCompatibility(TensorData const & features, LabelSourceDescriptor const & label_source)
Validate that a feature tensor is compatible with a label source.
AssembledLabels assembleLabelsFromIntervals(DigitalIntervalSeries const & intervals, TimeFrame const & source_time_frame, std::span< TimeFrameIndex const > row_times, LabelFromIntervals const & config ={})
Assemble binary labels from a DigitalIntervalSeries.
AssembledLabels assembleLabelsFromTimeEntityGroups(EntityGroupManager const & groups, EntityRegistry const & registry, std::span< TimeFrameIndex const > row_times, LabelFromTimeEntityGroups const & config)
Assemble multi-class labels from TimeEntity groups.
AssembledLabels assembleLabelsFromDataEntityGroups(EntityGroupManager const & groups, EntityRegistry const & registry, std::span< TimeFrameIndex const > row_times, LabelFromDataEntityGroups const & config)
Assemble multi-class labels from data-object entity groups.
AssembledLabels assembleLabelsFromEvents(DigitalEventSeries const & events, TimeFrame const & source_time_frame, std::span< TimeFrameIndex const > row_times, LabelFromEvents const & config ={})
Assemble binary labels from a DigitalEventSeries.
std::vector< std::string > getClassNamesFromGroups(EntityGroupManager const & groups, std::vector< GroupId > const & class_group_ids)
Retrieve human-readable class names from groups.
std::size_t countRowsInsideIntervals(DigitalIntervalSeries const & intervals, TimeFrame const & source_time_frame, std::span< TimeFrameIndex const > row_times)
Count how many row_times fall inside intervals.
BinaryClassificationMetrics computeBinaryMetrics(arma::Row< std::size_t > const & predictions, arma::Row< std::size_t > const & truth)
Compute binary classification metrics from predictions and ground truth.
MultiClassMetrics computeMultiClassMetrics(arma::Row< std::size_t > const & predictions, arma::Row< std::size_t > const & truth, std::size_t num_classes)
Compute multi-class classification metrics.
MultiClassMetrics computeMultiClassMetrics(arma::Row< std::size_t > const & predictions, arma::Row< std::size_t > const & truth)
Infer the number of classes from label vectors and compute multi-class metrics.
std::string formatBinaryMetrics(BinaryClassificationMetrics const & metrics)
Format a BinaryClassificationMetrics struct as a human-readable string.
std::string formatMultiClassMetrics(MultiClassMetrics const & metrics, std::vector< std::string > const & class_names ={})
Format a MultiClassMetrics struct as a human-readable string.
std::string toString(MLTaskType task)
Human-readable string for an MLTaskType.
std::vector< std::string > writePredictionsAsIntervals(DataManager & dm, PredictionOutput const & output, std::vector< std::string > const & class_names, PredictionWriterConfig const & config ={})
Write class predictions as DigitalIntervalSeries.
std::vector< std::string > writeProbabilitiesAsAnalog(DataManager & dm, PredictionOutput const & output, std::vector< std::string > const & class_names, PredictionWriterConfig const & config ={})
Write per-class probabilities as AnalogTimeSeries.
std::vector< GroupId > writeTimePredictionsToGroups(DataManager & dm, PredictionOutput const & output, std::vector< std::string > const & class_names, PredictionWriterConfig const & config ={})
Write time-entity predictions to putative groups.
std::vector< GroupId > writeClusterAssignmentsToGroups(EntityGroupManager & groups, arma::Row< std::size_t > const & assignments, std::span< EntityId const > entity_ids, std::string const & group_prefix =“Cluster:”)
Write cluster assignments to putative entity groups.
PredictionWriterResult writePredictions(DataManager & dm, PredictionOutput const & output, std::vector< std::string > const & class_names, PredictionWriterConfig const & config ={})
Write all configured prediction outputs in one call.
std::optional< BoundingSpan > computeIntervalBounds(DigitalIntervalSeries const & intervals)
Compute the bounding span of all intervals in a series.
std::optional< BoundingSpan > computeRowTimeBounds(std::vector< TimeFrameIndex > const & row_times)
Compute the bounding span of a vector of time indices.
BoundingSpan mergeSpans(BoundingSpan a, BoundingSpan b)
Merge two bounding spans into their union (the span covering both).
FilteredRows filterRowsToSpan(arma::mat const & features, std::vector< TimeFrameIndex > const & times, BoundingSpan span)
Filter feature columns and times to only those within a bounding span.
FilteredPredictions filterPredictionsToIntervals(arma::Row< std::size_t > const & predictions, std::optional< arma::mat > const & probabilities, std::vector< TimeFrameIndex > const & times, DigitalIntervalSeries const & intervals)
Filter predictions to only frames that fall within any interval.
FilteredTrainingRows filterTrainingRowsToIntervals(arma::mat const & features, arma::Row< std::size_t > const & labels, std::vector< TimeFrameIndex > const & times, DigitalIntervalSeries const & intervals)
Filter training features, labels, and times to only rows within intervals.
std::string toString(ClassificationStage stage)
Human-readable description of a pipeline stage.
ClassificationPipelineResult runClassificationPipeline(DataManager & dm, MLModelRegistry const & registry, ClassificationPipelineConfig const & config, PipelineProgressCallback const & progress =[nullptr])
Run the full supervised classification pipeline.
std::string toString(ClusteringStage stage)
Human-readable description of a pipeline stage.
ClusteringPipelineResult runClusteringPipeline(DataManager & dm, MLModelRegistry const & registry, ClusteringPipelineConfig const & config, ClusteringProgressCallback const & progress =[nullptr])
Run the full unsupervised clustering pipeline.
std::string toString(DimReductionStage stage)
Human-readable description of a pipeline stage.
DimReductionPipelineResult runDimReductionPipeline(DataManager & dm, MLModelRegistry const & registry, DimReductionPipelineConfig const & config, DimReductionProgressCallback const & progress =[nullptr])
Run the full dimensionality reduction pipeline.
std::string toString(SupervisedDimReductionStage stage)
Human-readable description of a pipeline stage.
SupervisedDimReductionPipelineResult runSupervisedDimReductionPipeline(DataManager & dm, MLModelRegistry const & registry, SupervisedDimReductionPipelineConfig const & config, SupervisedDimReductionProgressCallback const & progress =[nullptr])
Run the full supervised dimensionality reduction pipeline.
BalancedData balanceClasses(arma::mat const & features, arma::Row< std::size_t > const & labels, BalancingConfig const & config ={})
Balance training data according to the given strategy.
std::vector< std::pair< std::size_t, std::size_t > > getClassDistribution(arma::Row< std::size_t > const & labels)
Compute per-class sample counts from a label vector.
bool isBalanced(arma::Row< std::size_t > const & labels, double max_acceptable_ratio =1.0)
Check whether a dataset is balanced within a given tolerance.
std::string toString(BalancingStrategy strategy)
Convert a BalancingStrategy enum to a human-readable string.

Types Documentation

enum RowCompatibility

Enumerator Value Description
Compatible Feature tensor is compatible with label source.
EmptyTensor Tensor has no storage or zero rows.
Not2D Tensor is not 2-dimensional.
NoColumns Tensor has zero columns.
RowTypeMismatch e.g., tensor has Interval rows but labels expect TimeFrameIndex
TimeFrameMismatch Feature and label time frames are different objects (different clocks).
RowCountMismatch Number of tensor rows != expected label count.

Reason why a feature tensor is incompatible with a label source.

enum RegularizationType

Enumerator Value Description
LASSO
Ridge
ElasticNet

Regularization mode for LARS Projection.

Controls which penalty terms are active in the LARS objective: min_β 0.5 ||Xβ − y||₂² + λ₁||β||₁ + 0.5 λ₂||β||₂²

  • LASSO: λ₁ > 0, λ₂ = 0 (L1 only → sparse coefficients)
  • Ridge: λ₁ = 0, λ₂ > 0 (L2 only → dense, shrunken coefficients)
  • ElasticNet: λ₁ > 0, λ₂ > 0 (L1 + L2 → grouped sparsity)

enum MLTaskType

Enumerator Value Description
BinaryClassification Two-class supervised classification.
MultiClassClassification N-class supervised classification (N ≥ 2).
Clustering Unsupervised clustering (assign to K groups).
DimensionalityReduction Unsupervised dimensionality reduction (PCA, t-SNE, etc.).
SupervisedDimensionalityReduction Supervised projection using class labels (Logit Projection, LDA, etc.).

Describes the type of ML task a model operation supports.

enum ClassificationStage

Enumerator Value Description
ValidatingFeatures
ConvertingFeatures
AssemblingLabels
BalancingClasses
SegmentingSequences
Training
Predicting
ComputingMetrics
WritingOutput
Complete
Failed

Stages of the classification pipeline.

enum ClusteringStage

Enumerator Value Description
ValidatingFeatures
ConvertingFeatures
Fitting
AssigningClusters
WritingOutput
Complete
Failed

Stages of the clustering pipeline.

enum DimReductionStage

Enumerator Value Description
ValidatingFeatures
ConvertingFeatures
FittingAndTransforming
WritingOutput
Complete
Failed

Stages of the dimensionality reduction pipeline.

enum SupervisedDimReductionStage

Enumerator Value Description
ValidatingFeatures
ConvertingFeatures
AssemblingLabels
FilteringTrainingRegion
FittingAndTransforming
WritingOutput
Complete
Failed

Stages of the supervised dimensionality reduction pipeline.

enum BalancingStrategy

Enumerator Value Description
Subsample Down-sample majority classes to minority count × ratio.
Oversample Up-sample minority classes to majority count × ratio.

Strategy used for class balancing.

using LabelSourceDescriptor

using MLCore::LabelSourceDescriptor =  std::variant<
        LabelSourceTimeGroups,
        LabelSourceIntervals,
        LabelSourceEntityGroups>;

Describes the expected label source for validation.

This is a lightweight descriptor — it captures only the metadata needed to validate compatibility with a feature tensor, without requiring access to the full DataManager or EntityGroupManager.

using LabelAssemblyConfig

using MLCore::LabelAssemblyConfig =  std::variant<
        LabelFromIntervals,
        LabelFromTimeEntityGroups,
        LabelFromDataEntityGroups,
        LabelFromEvents>;

Configuration variant for label assembly.

Select one of the four labeling modes.

using GaussianHMM

using MLCore::GaussianHMM =  mlpack::HMM<mlpack::GaussianDistribution<>>;

using DiagonalGaussianHMM

using MLCore::DiagonalGaussianHMM =  mlpack::HMM<mlpack::DiagonalGaussianDistribution<>>;

using GMMEmissionHMM

using MLCore::GMMEmissionHMM =  mlpack::HMM<mlpack::GMM>;

using DiagonalGMMEmissionHMM

using MLCore::DiagonalGMMEmissionHMM =  mlpack::HMM<mlpack::DiagonalGMM>;

using LRModel

using MLCore::LRModel =  mlpack::LogisticRegression<arma::mat>;

typedef SRModel

typedef mlpack::SoftmaxRegression< arma::mat > MLCore::SRModel =  mlpack::SoftmaxRegression<arma::mat>;

using NBModel

using MLCore::NBModel =  mlpack::NaiveBayesClassifier<>;

using RFModel

using MLCore::RFModel =  mlpack::RandomForest<
    mlpack::GiniGain,
    mlpack::MultipleRandomDimensionSelect>;

using PipelineProgressCallback

using MLCore::PipelineProgressCallback =  std::function<void(ClassificationStage, std::string const &)>;

Optional callback for pipeline progress reporting.

Called at the start of each pipeline stage. The string parameter provides a human-readable status message.

using ClusteringProgressCallback

using MLCore::ClusteringProgressCallback =  std::function<void(ClusteringStage, std::string const &)>;

Optional callback for pipeline progress reporting.

Called at the start of each pipeline stage. The string parameter provides a human-readable status message.

using DimReductionProgressCallback

using MLCore::DimReductionProgressCallback = 
        std::function<void(DimReductionStage, std::string const &)>;

Progress callback type.

using SupervisedDimReductionProgressCallback

using MLCore::SupervisedDimReductionProgressCallback = 
        std::function<void(SupervisedDimReductionStage, std::string const &)>;

Progress callback type.

Functions Documentation

function registerTimeEntities

std::vector< EntityId > registerTimeEntities(
    DataManager & dm,
    std::string const & time_key_str,
    std::span< TimeFrameIndex const > frames
)

Register a set of arbitrary TimeFrameIndex values as TimeEntities.

Parameters:

Return: Vector of EntityIds, one per input frame (same order)

Each frame in frames is registered (or retrieved if already present) via DataManager::ensureTimeEntityId(). The returned vector is parallel to frames — result[i] is the EntityId for frames[i].

function intervalsToTimeEntities

std::vector< EntityId > intervalsToTimeEntities(
    DataManager & dm,
    DigitalIntervalSeries const & intervals,
    std::string const & time_key_str
)

Expand a DigitalIntervalSeries into individual TimeEntity IDs.

Parameters:

Return: Vector of EntityIds, sorted ascending by time value

Note: The resulting vector may contain fewer elements than the sum of interval lengths if intervals overlap.

For each interval [start, end] in intervals, registers every integer index in [start, end] as a TimeEntity. Returns the full set of EntityIds across all intervals, sorted by TimeFrameIndex value.

Duplicate registrations (overlapping intervals) are handled idempotently by the underlying EntityRegistry.

function timeEntitiesToIntervals

std::shared_ptr< DigitalIntervalSeries > timeEntitiesToIntervals(
    DataManager & dm,
    GroupId group_id,
    std::string const & time_key_str
)

Convert a group of TimeEntity IDs into a DigitalIntervalSeries.

Parameters:

Return: Shared pointer to a DigitalIntervalSeries containing the merged intervals, or nullptr if the group is empty or has no matching TimeEntities

Retrieves all TimeEntity members of group_id whose data_key matches time_key_str, sorts by TimeFrameIndex value, and merges adjacent frames (difference == 1) into contiguous intervals.

Non-TimeEntity members and TimeEntities from other clocks are silently skipped.

function zscoreNormalize

std::pair< std::vector< double >, std::vector< double > > zscoreNormalize(
    arma::mat & matrix,
    double epsilon =1e-10
)

Apply z-score normalization to an arma::mat in-place.

Parameters:

  • matrix The matrix to normalize (modified in-place)
  • epsilon Added to std to prevent division by zero

Return: Pair of {means, stds} vectors (one per row/feature)

Normalizes each row (feature) of a features × observations matrix to zero mean and unit standard deviation.

function applyZscoreNormalization

void applyZscoreNormalization(
    arma::mat & matrix,
    std::vector< double > const & means,
    std::vector< double > const & stds,
    double epsilon =1e-10
)

Apply previously computed z-score parameters to new data.

Parameters:

  • matrix The matrix to normalize (features × observations, modified in-place)
  • means Per-feature means (size must == matrix.n_rows)
  • stds Per-feature standard deviations (size must == matrix.n_rows)
  • epsilon Added to std to prevent division by zero

Exceptions:

  • std::invalid_argument if means/stds size doesn’t match matrix rows

Useful for normalizing prediction-time data with the same parameters used during training.

function convertTensorToArma

ConvertedFeatures convertTensorToArma(
    TensorData const & tensor,
    ConversionConfig const & config ={}
)

Convert a TensorData feature matrix to the arma::mat format expected by mlpack.

Parameters:

  • tensor The feature tensor (must be 2D, non-empty)
  • config Conversion parameters

Exceptions:

  • std::invalid_argument if tensor is empty or not 2D

Return: ConvertedFeatures with the matrix and metadata

Postcondition:

  • If config.drop_nan is true, result.matrix contains no NaN or Inf values
  • If config.zscore_normalize is true, each row (feature) of result.matrix has mean≈0 and std≈1, and result.zscore_means / result.zscore_stds are populated for re-application to new data via applyZscoreNormalization()
  • result.valid_row_indices maps each matrix column back to the original tensor row index

This is the primary conversion entry point. It:

  1. Validates the tensor is non-empty and 2D
  2. Materializes all columns (handles lazy backends transparently)
  3. Converts float → double
  4. Optionally drops rows containing NaN/Inf values
  5. Optionally z-score normalizes each column
  6. Transposes to mlpack layout (features × observations)

function convertTensorToArmaRowMajor

ConvertedFeatures convertTensorToArmaRowMajor(
    TensorData const & tensor,
    ConversionConfig const & config ={}
)

Convert a TensorData to a row-major arma::mat (observations × features).

Parameters:

  • tensor The feature tensor
  • config Conversion parameters

Exceptions:

  • std::invalid_argument if tensor is empty or not 2D

Return: ConvertedFeatures with matrix in observations × features layout

Similar to convertTensorToArma but preserves the TensorData’s natural layout where rows are observations and columns are features. Useful when you need the matrix in the same orientation as the tensor (e.g., for visualization).

function toString

std::string toString(
    RowCompatibility rc
)

Human-readable description of a RowCompatibility value.

function validateFeatureTensor

TensorValidationResult validateFeatureTensor(
    TensorData const & features
)

Validate that a TensorData is structurally suitable as an ML feature matrix.

Parameters:

  • features The tensor to validate

Return: Validation result with reason and human-readable message

Checks:

  • Non-empty (has storage)
  • 2D (rows × columns)
  • Has at least one column
  • Has at least one row

Does NOT check label compatibility — use validateFeatureLabelCompatibility() for that.

function countNonFiniteRows

std::size_t countNonFiniteRows(
    TensorData const & features
)

Check if a feature tensor contains any NaN or Inf values.

Parameters:

  • features The feature tensor to check

Return: Number of rows containing at least one NaN or Inf value

Scans all columns for non-finite values. Useful as a pre-flight check before conversion, since mlpack cannot handle NaN/Inf.

function findNonFiniteRows

std::vector< std::size_t > findNonFiniteRows(
    TensorData const & features
)

Get the indices of rows that contain NaN or Inf values.

Parameters:

  • features The feature tensor to check

Return: Sorted vector of row indices containing non-finite values

function validateFeatureLabelCompatibility

FeatureLabelValidationResult validateFeatureLabelCompatibility(
    TensorData const & features,
    LabelSourceDescriptor const & label_source
)

Validate that a feature tensor is compatible with a label source.

Parameters:

  • features The feature tensor (built by TensorDesigner)
  • label_source Description of the label source

Return: Detailed validation result

Performs all checks from validateFeatureTensor(), plus:

  • Row count matches the label source’s expected count
  • For time-indexed features with time-indexed labels: verifies compatible row types

function assembleLabelsFromIntervals

AssembledLabels assembleLabelsFromIntervals(
    DigitalIntervalSeries const & intervals,
    TimeFrame const & source_time_frame,
    std::span< TimeFrameIndex const > row_times,
    LabelFromIntervals const & config ={}
)

Assemble binary labels from a DigitalIntervalSeries.

Parameters:

  • intervals The interval series defining the positive class
  • source_time_frame The TimeFrame that row_times are expressed in. This is typically the feature tensor’s TimeFrame from RowDescriptor.
  • row_times The time indices of each feature tensor row
  • config Configuration with class names (defaults: “Outside”, “Inside”)

Exceptions:

  • std::invalid_argument if row_times is empty

Return: Binary labels aligned with row_times (unlabeled_count always 0)

Precondition: row_times must not be empty (enforcement: exception)

For each row_time, checks if it falls inside any interval in the series. Inside → label 1, outside → label 0. Every row receives a label.

function assembleLabelsFromTimeEntityGroups

AssembledLabels assembleLabelsFromTimeEntityGroups(
    EntityGroupManager const & groups,
    EntityRegistry const & registry,
    std::span< TimeFrameIndex const > row_times,
    LabelFromTimeEntityGroups const & config
)

Assemble multi-class labels from TimeEntity groups.

Parameters:

  • groups The entity group manager
  • registry The entity registry (for descriptor lookup)
  • row_times The time indices of each feature tensor row
  • config Configuration with group IDs and time key

Exceptions:

  • std::invalid_argument if class_groups or row_times is empty

Return: Multi-class labels aligned with row_times

Precondition:

  • config.class_groups must not be empty (enforcement: exception)
  • row_times must not be empty (enforcement: exception)

Retrieves entities from each group, looks up their EntityDescriptor in the registry, and builds a mapping from TimeFrameIndex value → class label. Only entities matching the configured time_key and EntityKind::TimeEntity are considered.

Rows whose time value is not found in any group receive a sentinel label equal to num_classes and are counted as unlabeled.

function assembleLabelsFromDataEntityGroups

AssembledLabels assembleLabelsFromDataEntityGroups(
    EntityGroupManager const & groups,
    EntityRegistry const & registry,
    std::span< TimeFrameIndex const > row_times,
    LabelFromDataEntityGroups const & config
)

Assemble multi-class labels from data-object entity groups.

Parameters:

  • groups The entity group manager
  • registry The entity registry (for descriptor lookup)
  • row_times The time indices of each feature tensor row
  • config Configuration with data key and group IDs

Exceptions:

  • std::invalid_argument if class_groups or row_times is empty

Return: Multi-class labels aligned with row_times

Precondition:

  • config.class_groups must not be empty (enforcement: exception)
  • row_times must not be empty (enforcement: exception)

Similar to assembleLabelsFromTimeEntityGroups but matches entities by data_key rather than time_key. Accepts entities of any EntityKind (LineEntity, PointEntity, EventEntity, etc.) as long as data_key matches.

function assembleLabelsFromEvents

AssembledLabels assembleLabelsFromEvents(
    DigitalEventSeries const & events,
    TimeFrame const & source_time_frame,
    std::span< TimeFrameIndex const > row_times,
    LabelFromEvents const & config ={}
)

Assemble binary labels from a DigitalEventSeries.

Parameters:

  • events The event series defining the positive class
  • source_time_frame The TimeFrame that row_times are expressed in. This is typically the feature tensor’s TimeFrame from RowDescriptor.
  • row_times The time indices of each feature tensor row
  • config Configuration with class names (defaults: “NoEvent”, “Event”)

Exceptions:

  • std::invalid_argument if row_times is empty

Return: Binary labels aligned with row_times (unlabeled_count always 0)

Precondition: row_times must not be empty (enforcement: exception)

For each row_time, checks if an event exists at that time. Event exists → label 1, no event → label 0. Every row receives a label.

function getClassNamesFromGroups

std::vector< std::string > getClassNamesFromGroups(
    EntityGroupManager const & groups,
    std::vector< GroupId > const & class_group_ids
)

Retrieve human-readable class names from groups.

Parameters:

  • groups The entity group manager
  • class_group_ids The group IDs to get names for

Return: Vector of class names in the same order as class_group_ids

For each group ID, returns the group name from EntityGroupManager. If a group doesn’t exist, returns “Class_” as fallback.

function countRowsInsideIntervals

std::size_t countRowsInsideIntervals(
    DigitalIntervalSeries const & intervals,
    TimeFrame const & source_time_frame,
    std::span< TimeFrameIndex const > row_times
)

Count how many row_times fall inside intervals.

Parameters:

  • intervals The interval series
  • source_time_frame The TimeFrame that row_times are expressed in
  • row_times The time indices to check

Return: Number of row_times that fall inside at least one interval

Utility for UI display — counts how many feature rows would be labeled positive in a binary interval-based labeling scenario.

function computeBinaryMetrics

BinaryClassificationMetrics computeBinaryMetrics(
    arma::Row< std::size_t > const & predictions,
    arma::Row< std::size_t > const & truth
)

Compute binary classification metrics from predictions and ground truth.

Parameters:

  • predictions Predicted labels (0 or 1), one per observation
  • truth Ground truth labels (0 or 1), one per observation

Exceptions:

  • std::invalid_argument if vectors have different sizes

Return: BinaryClassificationMetrics with all fields populated

Note: If both vectors are empty, returns a default (invalid) metrics struct.

Labels must be binary (0 or 1). Non-binary values are ignored with a warning count in the returned struct. Label 1 is treated as positive, 0 as negative.

function computeMultiClassMetrics

MultiClassMetrics computeMultiClassMetrics(
    arma::Row< std::size_t > const & predictions,
    arma::Row< std::size_t > const & truth,
    std::size_t num_classes
)

Compute multi-class classification metrics.

Parameters:

  • predictions Predicted class labels, one per observation
  • truth Ground truth class labels, one per observation
  • num_classes Total number of classes (labels are expected in [0, num_classes-1])

Exceptions:

  • std::invalid_argument if vectors have different sizes or num_classes is zero

Return: MultiClassMetrics with confusion matrix and per-class metrics

Note: If both vectors are empty, returns a default (invalid) metrics struct.

function computeMultiClassMetrics

MultiClassMetrics computeMultiClassMetrics(
    arma::Row< std::size_t > const & predictions,
    arma::Row< std::size_t > const & truth
)

Infer the number of classes from label vectors and compute multi-class metrics.

Parameters:

  • predictions Predicted class labels
  • truth Ground truth class labels

Exceptions:

  • std::invalid_argument if vectors have different sizes

Return: MultiClassMetrics

Convenience overload that determines num_classes as max(predictions, truth) + 1.

function formatBinaryMetrics

std::string formatBinaryMetrics(
    BinaryClassificationMetrics const & metrics
)

Format a BinaryClassificationMetrics struct as a human-readable string.

Parameters:

  • metrics The metrics to format

Return: Formatted string

Useful for logging and debugging. Example output:

Accuracy: 0.9400  Sensitivity: 0.9180  Specificity: 0.9540  Dice/F1: 0.9200
TP: 45  TN: 50  FP: 3  FN: 3

function formatMultiClassMetrics

std::string formatMultiClassMetrics(
    MultiClassMetrics const & metrics,
    std::vector< std::string > const & class_names ={}
)

Format a MultiClassMetrics struct as a human-readable string.

Parameters:

  • metrics The metrics to format
  • class_names Optional class names for labeling rows/columns

Return: Formatted string including confusion matrix and per-class metrics

function toString

inline std::string toString(
    MLTaskType task
)

Human-readable string for an MLTaskType.

function writePredictionsAsIntervals

std::vector< std::string > writePredictionsAsIntervals(
    DataManager & dm,
    PredictionOutput const & output,
    std::vector< std::string > const & class_names,
    PredictionWriterConfig const & config ={}
)

Write class predictions as DigitalIntervalSeries.

Parameters:

  • dm DataManager to write into
  • output The prediction output (uses class_predictions and prediction_times)
  • class_names Names for each class
  • config Writer configuration

Return: DataManager keys of created interval series (one per class)

Note: prediction_times must be sorted in ascending order for correct interval merging

For each class, scans prediction_times for contiguous runs where that class was predicted, and creates an interval for each run. Each class produces one DigitalIntervalSeries stored under “{config.output_prefix}{class_name}”.

function writeProbabilitiesAsAnalog

std::vector< std::string > writeProbabilitiesAsAnalog(
    DataManager & dm,
    PredictionOutput const & output,
    std::vector< std::string > const & class_names,
    PredictionWriterConfig const & config ={}
)

Write per-class probabilities as AnalogTimeSeries.

Parameters:

  • dm DataManager to write into
  • output The prediction output (uses class_probabilities and prediction_times)
  • class_names Names for each class
  • config Writer configuration

Return: DataManager keys of created analog series (one per class), empty if no probabilities

For each class, extracts the probability row from output.class_probabilities and creates an AnalogTimeSeries with the same time indices as prediction_times. Output keys: “{config.output_prefix}prob_{class_name}”

function writeTimePredictionsToGroups

std::vector< GroupId > writeTimePredictionsToGroups(
    DataManager & dm,
    PredictionOutput const & output,
    std::vector< std::string > const & class_names,
    PredictionWriterConfig const & config ={}
)

Write time-entity predictions to putative groups.

Parameters:

  • dm DataManager (used for TimeEntity registration via ensureTimeEntityId)
  • output The prediction output
  • class_names Names for each class
  • config Writer configuration

Return: GroupIds of created groups (one per class)

For each class, creates a group named “{config.output_prefix}{class_name}” and populates it with TimeEntity IDs corresponding to prediction_times where that class was predicted.

function writeClusterAssignmentsToGroups

std::vector< GroupId > writeClusterAssignmentsToGroups(
    EntityGroupManager & groups,
    arma::Row< std::size_t > const & assignments,
    std::span< EntityId const > entity_ids,
    std::string const & group_prefix ="Cluster:"
)

Write cluster assignments to putative entity groups.

Parameters:

  • groups EntityGroupManager to create groups in
  • assignments Per-observation cluster indices
  • entity_ids Entity IDs corresponding to each observation
  • group_prefix Prefix for group names (default: “Cluster:”)

Exceptions:

  • std::invalid_argument if sizes don’t match

Return: GroupIds of created groups (one per cluster)

Precondition: assignments.n_elem == entity_ids.size()

For unsupervised clustering output. Creates groups named “{group_prefix}{cluster_index}” and assigns the corresponding entities.

function writePredictions

PredictionWriterResult writePredictions(
    DataManager & dm,
    PredictionOutput const & output,
    std::vector< std::string > const & class_names,
    PredictionWriterConfig const & config ={}
)

Write all configured prediction outputs in one call.

Parameters:

  • dm DataManager to write output data into
  • output The model’s prediction output
  • class_names Human-readable names for each class (size = num_classes)
  • config Writer configuration

Exceptions:

  • std::invalid_argument if preconditions are violated

Return: Summary of all created outputs

Precondition:

  • output.class_predictions.n_elem == output.prediction_times.size()
  • class_names.size() >= max(output.class_predictions) + 1

This is the main entry point. It:

  1. Converts class predictions → DigitalIntervalSeries per class (if enabled)
  2. Converts class probabilities → AnalogTimeSeries per class (if enabled)
  3. Creates putative entity groups with TimeEntity members (if enabled)

function computeIntervalBounds

std::optional< BoundingSpan > computeIntervalBounds(
    DigitalIntervalSeries const & intervals
)

Compute the bounding span of all intervals in a series.

Return: [min(start), max(end)] across all intervals, or nullopt if empty

Precondition: intervals must not be empty

function computeRowTimeBounds

std::optional< BoundingSpan > computeRowTimeBounds(
    std::vector< TimeFrameIndex > const & row_times
)

Compute the bounding span of a vector of time indices.

Return: [min, max] of all times, or nullopt if empty

Precondition: row_times must not be empty

function mergeSpans

BoundingSpan mergeSpans(
    BoundingSpan a,
    BoundingSpan b
)

Merge two bounding spans into their union (the span covering both).

function filterRowsToSpan

FilteredRows filterRowsToSpan(
    arma::mat const & features,
    std::vector< TimeFrameIndex > const & times,
    BoundingSpan span
)

Filter feature columns and times to only those within a bounding span.

Parameters:

  • features Feature matrix (rows = features, cols = observations)
  • times Time index for each observation column
  • span Bounding span to filter to

Return: Filtered features and times (may be empty if no rows fall in span)

Precondition: features.n_cols == times.size()

Keeps only columns (observations) whose corresponding time falls within [span.min_time, span.max_time] (inclusive).

function filterPredictionsToIntervals

FilteredPredictions filterPredictionsToIntervals(
    arma::Row< std::size_t > const & predictions,
    std::optional< arma::mat > const & probabilities,
    std::vector< TimeFrameIndex > const & times,
    DigitalIntervalSeries const & intervals
)

Filter predictions to only frames that fall within any interval.

Parameters:

  • predictions Per-observation class labels
  • probabilities Optional probability matrix (num_classes x num_obs)
  • times Time index for each observation
  • intervals The target intervals to filter to

Return: Filtered predictions, probabilities, and times

Precondition:

  • predictions.n_elem == times.size()
  • If probabilities has a value, probabilities->n_cols == times.size()

Keeps only observations whose corresponding time is contained in at least one interval of the provided series (start <= time <= end).

function filterTrainingRowsToIntervals

FilteredTrainingRows filterTrainingRowsToIntervals(
    arma::mat const & features,
    arma::Row< std::size_t > const & labels,
    std::vector< TimeFrameIndex > const & times,
    DigitalIntervalSeries const & intervals
)

Filter training features, labels, and times to only rows within intervals.

Parameters:

  • features Feature matrix (rows = features, cols = observations)
  • labels Per-observation class label
  • times Time index for each observation column
  • intervals The interval series to filter against

Return: Filtered features, labels, and times (may be empty)

Precondition: features.n_cols == labels.n_elem == times.size()

Keeps only columns (observations) whose corresponding time is contained in at least one interval (start <= time <= end).

function toString

std::string toString(
    ClassificationStage stage
)

Human-readable description of a pipeline stage.

function runClassificationPipeline

ClassificationPipelineResult runClassificationPipeline(
    DataManager & dm,
    MLModelRegistry const & registry,
    ClassificationPipelineConfig const & config,
    PipelineProgressCallback const & progress =nullptr
)

Run the full supervised classification pipeline.

Parameters:

  • dm DataManager containing the feature tensor, label sources, and output targets
  • registry Model registry containing the model factory
  • config Full pipeline configuration
  • progress Optional callback for progress reporting

Return: Complete pipeline result with metrics, outputs, and trained model

Precondition: config.conversion_config.zscore_normalize should be true for scale-sensitive classifiers (Logistic Regression, Softmax Regression). Tree-based methods (Random Forest) are scale-invariant. This is the sole mechanism for feature scaling — individual algorithms no longer scale internally. (enforcement: none) [IMPORTANT]

Orchestrates:

  1. Validate — checks feature tensor exists and is valid

  2. Convert — TensorData → arma::mat (NaN dropping, optional z-score)

  3. Assemble labels — from intervals, time-entity groups, or data-entity groups

  4. Balance — optional class balancing (subsample/oversample)

  5. Segment — (sequence models only) split into contiguous temporal sequences

  6. Train — trains the selected model

  7. Predict — on training data or a separate prediction tensor

  8. Metrics — computes classification metrics on predictions

  9. Write output — writes predictions as intervals, probabilities, and/or groups

function toString

std::string toString(
    ClusteringStage stage
)

Human-readable description of a pipeline stage.

function runClusteringPipeline

ClusteringPipelineResult runClusteringPipeline(
    DataManager & dm,
    MLModelRegistry const & registry,
    ClusteringPipelineConfig const & config,
    ClusteringProgressCallback const & progress =nullptr
)

Run the full unsupervised clustering pipeline.

Parameters:

  • dm DataManager containing the feature tensor and output targets
  • registry Model registry containing the clustering model factory
  • config Full pipeline configuration
  • progress Optional callback for progress reporting

Return: Complete pipeline result with cluster info, outputs, and fitted model

Precondition: config.conversion_config.zscore_normalize should be true for distance-based clustering algorithms (K-Means, DBSCAN, GMM). This is the sole mechanism for feature scaling — individual algorithms no longer scale internally. (enforcement: none) [IMPORTANT]

Orchestrates:

  1. Validate — checks feature tensor exists and is valid
  2. Convert — TensorData → arma::mat (NaN dropping, optional z-score)
  3. Fit — fits the selected clustering model
  4. Assign — assigns clusters to fitting data or separate tensor
  5. Write output — writes cluster assignments as interval series, putative entity groups, and optionally probability analog series

function toString

std::string toString(
    DimReductionStage stage
)

Human-readable description of a pipeline stage.

function runDimReductionPipeline

DimReductionPipelineResult runDimReductionPipeline(
    DataManager & dm,
    MLModelRegistry const & registry,
    DimReductionPipelineConfig const & config,
    DimReductionProgressCallback const & progress =nullptr
)

Run the full dimensionality reduction pipeline.

Parameters:

  • dm DataManager containing the feature tensor
  • registry Model registry containing the dim reduction model factory
  • config Full pipeline configuration
  • progress Optional callback for progress reporting

Return: Complete pipeline result

Precondition: config.conversion_config.zscore_normalize should be true for PCA-family algorithms that compare across features. This is the sole mechanism for feature scaling — individual algorithms no longer scale internally. (enforcement: none) [IMPORTANT]

Orchestrates:

  1. Validate — checks feature tensor exists, is 2D
  2. Convert — TensorData → arma::mat (NaN dropping, optional z-score)
  3. Fit+Transform — fits the model and produces reduced matrix
  4. Write output — creates a new TensorData and stores in DataManager

function toString

std::string toString(
    SupervisedDimReductionStage stage
)

Human-readable description of a pipeline stage.

function runSupervisedDimReductionPipeline

SupervisedDimReductionPipelineResult runSupervisedDimReductionPipeline(
    DataManager & dm,
    MLModelRegistry const & registry,
    SupervisedDimReductionPipelineConfig const & config,
    SupervisedDimReductionProgressCallback const & progress =nullptr
)

Run the full supervised dimensionality reduction pipeline.

Parameters:

  • dm DataManager containing the feature tensor and label sources
  • registry Model registry containing the supervised dim reduction factory
  • config Full pipeline configuration
  • progress Optional callback for progress reporting

Return: Complete pipeline result

Precondition: config.conversion_config.zscore_normalize should be true for supervised projection algorithms (Logit Projection, Supervised PCA). This is the sole mechanism for feature scaling — individual algorithms no longer scale internally. (enforcement: none) [IMPORTANT]

Orchestrates:

  1. Validate — checks feature tensor exists and is valid
  2. Convert — TensorData → arma::mat (NaN dropping, optional z-score)
  3. Assemble labels — from intervals, entity groups, or events
  4. Fit+Transform — fits on labeled rows, transforms ALL valid rows
  5. Write output — creates a TensorData and stores in DataManager

The output TensorData contains ALL rows that survived NaN conversion, including unlabeled rows (which are still projected by the fitted model). This lets the scatter plot show the complete dataset.

Column names in the output use actual class names: “Logit:”.

function balanceClasses

BalancedData balanceClasses(
    arma::mat const & features,
    arma::Row< std::size_t > const & labels,
    BalancingConfig const & config ={}
)

Balance training data according to the given strategy.

Parameters:

  • features Input feature matrix (features × observations)
  • labels Input label vector (one per observation column)
  • config Balancing configuration

Exceptions:

  • std::invalid_argument if features.n_cols != labels.n_elem, or if max_ratio < 1.0, or if data is empty

Return: BalancedData with balanced features, labels, and metadata

Precondition:

  • features.n_cols == labels.n_elem
  • config.max_ratio >= 1.0
  • features.n_cols > 0

This is the primary entry point. Features are in mlpack layout (features × observations), and labels is a row vector of class indices.

function getClassDistribution

std::vector< std::pair< std::size_t, std::size_t > > getClassDistribution(
    arma::Row< std::size_t > const & labels
)

Compute per-class sample counts from a label vector.

Parameters:

  • labels Label vector

Return: Map from class label → count (sorted by label)

function isBalanced

bool isBalanced(
    arma::Row< std::size_t > const & labels,
    double max_acceptable_ratio =1.0
)

Check whether a dataset is balanced within a given tolerance.

Parameters:

  • labels Label vector
  • max_acceptable_ratio Maximum allowed ratio (default 1.0 = perfectly balanced)

Return: true if already balanced within tolerance

A dataset is considered balanced if the ratio of the largest class to the smallest (non-zero) class is <= max_acceptable_ratio.

function toString

std::string toString(
    BalancingStrategy strategy
)

Convert a BalancingStrategy enum to a human-readable string.


Updated on 2026-11-13 at 20:25:41 +0000