Class AutoMLEnsembleModel<T>
A simple tabular ensemble model used as a facade-safe AutoML final model.
public sealed class AutoMLEnsembleModel<T> : IFullModel<T, Matrix<T>, Vector<T>>, IModel<Matrix<T>, Vector<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Matrix<T>, Vector<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Matrix<T>, Vector<T>>>, IGradientComputable<T, Matrix<T>, Vector<T>>, IJitCompilable<T>
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
AutoMLEnsembleModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
This ensemble combines multiple IFullModel<T, TInput, TOutput> members by averaging (regression/binary) or voting (multi-class) over their predictions.
For Beginners: Instead of trusting one model, an ensemble uses multiple models and combines their answers. This often improves stability and accuracy.
Constructors
AutoMLEnsembleModel()
Initializes a new instance of the AutoMLEnsembleModel<T> class.
public AutoMLEnsembleModel()
Remarks
This constructor exists for serialization only. Prefer the overload that accepts members.
AutoMLEnsembleModel(IEnumerable<IFullModel<T, Matrix<T>, Vector<T>>>, PredictionType, IReadOnlyList<double>?)
public AutoMLEnsembleModel(IEnumerable<IFullModel<T, Matrix<T>, Vector<T>>> members, PredictionType predictionType, IReadOnlyList<double>? weights = null)
Parameters
membersIEnumerable<IFullModel<T, Matrix<T>, Vector<T>>>predictionTypePredictionTypeweightsIReadOnlyList<double>
Properties
DefaultLossFunction
Gets the default loss function used by this model for gradient computation.
public ILossFunction<T> DefaultLossFunction { get; }
Property Value
Remarks
This loss function is used when calling ComputeGradients(TInput, TOutput, ILossFunction<T>?) without explicitly providing a loss function. It represents the model's primary training objective.
For Beginners: The loss function tells the model "what counts as a mistake". For example: - For regression (predicting numbers): Mean Squared Error measures how far predictions are from actual values - For classification (predicting categories): Cross Entropy measures how confident the model is in the right category
This property provides a sensible default so you don't have to specify the loss function every time, but you can still override it if needed for special cases.
Distributed Training: In distributed training, all workers use the same loss function to ensure consistent gradient computation. The default loss function is automatically used when workers compute local gradients.
Exceptions
- InvalidOperationException
Thrown if accessed before the model has been configured with a loss function.
Members
Gets the member models in the ensemble.
[JsonIgnore]
public IReadOnlyList<IFullModel<T, Matrix<T>, Vector<T>>> Members { get; }
Property Value
- IReadOnlyList<IFullModel<T, Matrix<T>, Vector<T>>>
ParameterCount
Gets the number of parameters in the model.
public int ParameterCount { get; }
Property Value
Remarks
This property returns the total count of trainable parameters in the model. It's useful for understanding model complexity and memory requirements.
PredictionType
Gets or sets the prediction type used to combine outputs (regression vs classification).
public PredictionType PredictionType { get; set; }
Property Value
SupportsJitCompilation
Gets whether this model currently supports JIT compilation.
public bool SupportsJitCompilation { get; }
Property Value
- bool
True if the model can be JIT compiled, false otherwise.
Remarks
Some models may not support JIT compilation due to: - Dynamic graph structure (changes based on input) - Lack of computation graph representation - Use of operations not yet supported by the JIT compiler
For Beginners: This tells you whether this specific model can benefit from JIT compilation.
Models return false if they:
- Use layer-based architecture without graph export (e.g., current neural networks)
- Have control flow that changes based on input data
- Use operations the JIT compiler doesn't understand yet
In these cases, the model will still work normally, just without JIT acceleration.
Weights
Gets or sets the per-member weights used when combining predictions.
public double[] Weights { get; set; }
Property Value
- double[]
Remarks
Weights are normalized to sum to 1.0.
Methods
ApplyGradients(Vector<T>, T)
Applies pre-computed gradients to update the model parameters.
public void ApplyGradients(Vector<T> gradients, T learningRate)
Parameters
gradientsVector<T>The gradient vector to apply.
learningRateTThe learning rate for the update.
Remarks
Updates parameters using: θ = θ - learningRate * gradients
For Beginners: After computing gradients (seeing which direction to move), this method actually moves the model in that direction. The learning rate controls how big of a step to take.
Distributed Training: In DDP/ZeRO-2, this applies the synchronized (averaged) gradients after communication across workers. Each worker applies the same averaged gradients to keep parameters consistent.
Clone()
Creates a shallow copy of this object.
public IFullModel<T, Matrix<T>, Vector<T>> Clone()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
ComputeGradients(Matrix<T>, Vector<T>, ILossFunction<T>?)
Computes gradients of the loss function with respect to model parameters for the given data, WITHOUT updating the model parameters.
public Vector<T> ComputeGradients(Matrix<T> input, Vector<T> target, ILossFunction<T>? lossFunction = null)
Parameters
inputMatrix<T>The input data.
targetVector<T>The target/expected output.
lossFunctionILossFunction<T>The loss function to use for gradient computation. If null, uses the model's default loss function.
Returns
- Vector<T>
A vector containing gradients with respect to all model parameters.
Remarks
This method performs a forward pass, computes the loss, and back-propagates to compute gradients, but does NOT update the model's parameters. The parameters remain unchanged after this call.
Distributed Training: In DDP/ZeRO-2, each worker calls this to compute local gradients on its data batch. These gradients are then synchronized (averaged) across workers before applying updates. This ensures all workers compute the same parameter updates despite having different data.
For Meta-Learning: After adapting a model on a support set, you can use this method to compute gradients on the query set. These gradients become the meta-gradients for updating the meta-parameters.
For Beginners: Think of this as "dry run" training: - The model sees what direction it should move (the gradients) - But it doesn't actually move (parameters stay the same) - You get to decide what to do with this information (average with others, inspect, modify, etc.)
Exceptions
- InvalidOperationException
If lossFunction is null and the model has no default loss function.
DeepCopy()
Creates a deep copy of this object.
public IFullModel<T, Matrix<T>, Vector<T>> DeepCopy()
Returns
- IFullModel<T, Matrix<T>, Vector<T>>
Deserialize(byte[])
Loads a previously serialized model from binary data.
public void Deserialize(byte[] data)
Parameters
databyte[]The byte array containing the serialized model data.
Remarks
This method takes binary data created by the Serialize method and uses it to restore a model to its previous state.
For Beginners: This is like opening a saved file to continue your work.
When you call this method:
- You provide the binary data (bytes) that was previously created by Serialize
- The model rebuilds itself using this data
- After deserializing, the model is exactly as it was when serialized
- It's ready to make predictions without needing to be trained again
For example:
- You download a pre-trained model file for detecting spam emails
- You deserialize this file into your application
- Immediately, your application can detect spam without any training
- The model has all the knowledge that was built into it by its original creator
This is particularly useful when:
- You want to use a model that took days to train
- You need to deploy the same model across multiple devices
- You're creating an application that non-technical users will use
Think of it like installing the brain of a trained expert directly into your application.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the model's computation graph for JIT compilation.
public ComputationNode<T> ExportComputationGraph(List<ComputationNode<T>> inputNodes)
Parameters
inputNodesList<ComputationNode<T>>List to populate with input computation nodes (parameters).
Returns
- ComputationNode<T>
The output computation node representing the model's prediction.
Remarks
This method should construct a computation graph representing the model's forward pass. The graph should use placeholder input nodes that will be filled with actual data during execution.
For Beginners: This method creates a "recipe" of your model's calculations that the JIT compiler can optimize.
The method should:
- Create placeholder nodes for inputs (features, parameters)
- Build the computation graph using TensorOperations
- Return the final output node
- Add all input nodes to the inputNodes list (in order)
Example for a simple linear model (y = Wx + b):
public ComputationNode<T> ExportComputationGraph(List<ComputationNode<T>> inputNodes)
{
// Create placeholder inputs
var x = TensorOperations<T>.Variable(new Tensor<T>(InputShape), "x");
var W = TensorOperations<T>.Variable(Weights, "W");
var b = TensorOperations<T>.Variable(Bias, "b");
// Add inputs in order
inputNodes.Add(x);
inputNodes.Add(W);
inputNodes.Add(b);
// Build graph: y = Wx + b
var matmul = TensorOperations<T>.MatMul(x, W);
var output = TensorOperations<T>.Add(matmul, b);
return output;
}
The JIT compiler will then:
- Optimize the graph (fuse operations, eliminate dead code)
- Compile it to fast native code
- Cache the compiled version for reuse
GetActiveFeatureIndices()
Gets the indices of features that are actively used by this model.
public IEnumerable<int> GetActiveFeatureIndices()
Returns
GetFeatureImportance()
Gets the feature importance scores.
public Dictionary<string, T> GetFeatureImportance()
Returns
- Dictionary<string, T>
GetModelMetadata()
Retrieves metadata and performance metrics about the trained model.
public ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
An object containing metadata and performance metrics about the trained model.
Remarks
This method provides information about the model's structure, parameters, and performance metrics.
For Beginners: Model metadata is like a report card for your machine learning model.
Just as a report card shows how well a student is performing in different subjects, model metadata shows how well your model is performing and provides details about its structure.
This information typically includes:
- Accuracy measures: How well does the model's predictions match actual values?
- Error metrics: How far off are the model's predictions on average?
- Model parameters: What patterns did the model learn from the data?
- Training information: How long did training take? How many iterations were needed?
For example, in a house price prediction model, metadata might include:
- Average prediction error (e.g., off by $15,000 on average)
- How strongly each feature (bedrooms, location) influences the prediction
- How well the model fits the training data
This information helps you understand your model's strengths and weaknesses, and decide if it's ready to use or needs more training.
GetParameters()
Gets the parameters that can be optimized.
public Vector<T> GetParameters()
Returns
- Vector<T>
IsFeatureUsed(int)
Checks if a specific feature is used by this model.
public bool IsFeatureUsed(int featureIndex)
Parameters
featureIndexint
Returns
LoadModel(string)
Loads the model from a file.
public void LoadModel(string filePath)
Parameters
filePathstringThe path to the file containing the saved model.
Remarks
This method provides a convenient way to load a model directly from disk. It combines file I/O operations with deserialization.
For Beginners: This is like clicking "Open" in a document editor. Instead of manually reading from a file and then calling Deserialize(), this method does both steps for you.
Exceptions
- FileNotFoundException
Thrown when the specified file does not exist.
- IOException
Thrown when an I/O error occurs while reading from the file or when the file contains corrupted or invalid model data.
LoadState(Stream)
Loads the model's state (parameters and configuration) from a stream.
public void LoadState(Stream stream)
Parameters
streamStreamThe stream to read the model state from.
Remarks
This method deserializes model state that was previously saved with SaveState, restoring all parameters and configuration to recreate the saved model state.
For Beginners: This is like loading a saved game.
When you call LoadState:
- All the parameters are read from the stream
- The model is configured to match the saved architecture
- The model becomes identical to when SaveState was called
After loading, the model can make predictions using the restored parameters.
Stream Handling: - The stream position will be advanced by the number of bytes read - The stream is not closed (caller must dispose) - Stream data must match the format written by SaveState
Versioning: Implementations should consider: - Including format version number in serialized data - Validating compatibility before deserialization - Providing migration paths for old formats when possible
Usage:
// Load from file
using var stream = File.OpenRead("model.bin");
model.LoadState(stream);
Important: The stream must contain state data saved by SaveState from a compatible model (same architecture and numeric type).
Exceptions
- ArgumentNullException
Thrown when stream is null.
- ArgumentException
Thrown when stream is not readable or contains invalid data.
- InvalidOperationException
Thrown when deserialization fails or data is incompatible with model architecture.
Predict(Matrix<T>)
Uses the trained model to make predictions for new input data.
public Vector<T> Predict(Matrix<T> input)
Parameters
inputMatrix<T>A matrix where each row represents a new example to predict and each column represents a feature.
Returns
- Vector<T>
A vector containing the predicted values for each input example.
Remarks
After training, this method applies the learned patterns to new data to predict outcomes.
For Beginners: Prediction is when the model uses what it learned to make educated guesses about new information.
Continuing the fruit identification example:
- After learning from many examples, the child (model) can now identify new fruits they haven't seen before
- They look at the color, shape, and size to make their best guess
In machine learning:
- You give the model new data it hasn't seen during training
- The model applies the patterns it learned to make predictions
- The output is the model's best estimate based on its training
For example, in a house price prediction model:
- You provide features of a new house (square footage, bedrooms, location)
- The model predicts what price that house might sell for
This method is used after training is complete, when you want to apply your model to real-world data.
SaveModel(string)
Saves the model to a file.
public void SaveModel(string filePath)
Parameters
filePathstringThe path where the model should be saved.
Remarks
This method provides a convenient way to save the model directly to disk. It combines serialization with file I/O operations.
For Beginners: This is like clicking "Save As" in a document editor. Instead of manually calling Serialize() and then writing to a file, this method does both steps for you.
Exceptions
- IOException
Thrown when an I/O error occurs while writing to the file.
- UnauthorizedAccessException
Thrown when the caller does not have the required permission to write to the specified file path.
SaveState(Stream)
Saves the model's current state (parameters and configuration) to a stream.
public void SaveState(Stream stream)
Parameters
streamStreamThe stream to write the model state to.
Remarks
This method serializes all the information needed to recreate the model's current state, including trained parameters, layer configurations, and any internal state variables.
For Beginners: This is like creating a snapshot of your trained model.
When you call SaveState:
- All the learned parameters (weights and biases) are written to the stream
- The model's architecture information is saved
- Any other internal state (like normalization statistics) is preserved
You can later use LoadState to restore the model to this exact state.
Stream Handling: - The stream position will be advanced by the number of bytes written - The stream is flushed but not closed (caller must dispose) - For file-based persistence, wrap in File.Create/FileStream
Usage:
// Save to file
using var stream = File.Create("model.bin");
model.SaveState(stream);
Exceptions
- ArgumentNullException
Thrown when stream is null.
- ArgumentException
Thrown when stream is not writable.
- InvalidOperationException
Thrown when model state cannot be serialized (e.g., uninitialized model).
Serialize()
Converts the current state of a machine learning model into a binary format.
public byte[] Serialize()
Returns
- byte[]
A byte array containing the serialized model data.
Remarks
This method captures all the essential information about a trained model and converts it into a sequence of bytes that can be stored or transmitted.
For Beginners: This is like exporting your work to a file.
When you call this method:
- The model's current state (all its learned patterns and parameters) is captured
- This information is converted into a compact binary format (bytes)
- You can then save these bytes to a file, database, or send them over a network
For example:
- After training a model to recognize cats vs. dogs in images
- You can serialize the model to save all its learned knowledge
- Later, you can use this saved data to recreate the model exactly as it was
- The recreated model will make the same predictions as the original
Think of it like taking a snapshot of your model's brain at a specific moment in time.
SetActiveFeatureIndices(IEnumerable<int>)
Sets the active feature indices for this model.
public void SetActiveFeatureIndices(IEnumerable<int> featureIndices)
Parameters
featureIndicesIEnumerable<int>
SetParameters(Vector<T>)
Sets the model parameters.
public void SetParameters(Vector<T> parameters)
Parameters
parametersVector<T>The parameter vector to set.
Remarks
This method allows direct modification of the model's internal parameters.
This is useful for optimization algorithms that need to update parameters iteratively.
If the length of parameters does not match ParameterCount,
an ArgumentException should be thrown.
Exceptions
- ArgumentException
Thrown when the length of
parametersdoes not match ParameterCount.
Train(Matrix<T>, Vector<T>)
Trains the model using input features and their corresponding target values.
public void Train(Matrix<T> input, Vector<T> expectedOutput)
Parameters
inputMatrix<T>expectedOutputVector<T>
Remarks
This method takes training data and adjusts the model's internal parameters to learn patterns in the data.
For Beginners: Training is like teaching the model by showing it examples.
Imagine teaching a child to identify fruits:
- You show them many examples of apples, oranges, and bananas (input features x)
- You tell them the correct name for each fruit (target values y)
- Over time, they learn to recognize the patterns that distinguish each fruit
In machine learning:
- The x parameter contains features (characteristics) of your data
- The y parameter contains the correct answers you want the model to learn
- During training, the model adjusts its internal calculations to get better at predicting y from x
For example, in a house price prediction model:
- x would contain features like square footage, number of bedrooms, location
- y would contain the actual sale prices of those houses
WithParameters(Vector<T>)
Creates a new instance with the specified parameters.
public IFullModel<T, Matrix<T>, Vector<T>> WithParameters(Vector<T> parameters)
Parameters
parametersVector<T>
Returns
- IFullModel<T, Matrix<T>, Vector<T>>