Class AutoMLModelBase<T, TInput, TOutput>
Base class for AutoML models that automatically search for optimal model configurations
public abstract class AutoMLModelBase<T, TInput, TOutput> : IAutoMLModel<T, TInput, TOutput>, IFullModel<T, TInput, TOutput>, IModel<TInput, TOutput, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, TInput, TOutput>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, TInput, TOutput>>, IGradientComputable<T, TInput, TOutput>, IJitCompilable<T>
Type Parameters
TThe numeric type used for calculations
TInputThe input data type
TOutputThe output data type
- Inheritance
-
AutoMLModelBase<T, TInput, TOutput>
- Implements
-
IAutoMLModel<T, TInput, TOutput>IFullModel<T, TInput, TOutput>IModel<TInput, TOutput, ModelMetadata<T>>IParameterizable<T, TInput, TOutput>ICloneable<IFullModel<T, TInput, TOutput>>IGradientComputable<T, TInput, TOutput>
- Derived
- Inherited Members
- Extension Methods
Fields
_candidateModels
protected readonly List<ModelType> _candidateModels
Field Value
_constraints
protected readonly List<SearchConstraint> _constraints
Field Value
_earlyStoppingMinDelta
protected double _earlyStoppingMinDelta
Field Value
_earlyStoppingPatience
protected int? _earlyStoppingPatience
Field Value
- int?
_lock
protected readonly object _lock
Field Value
_maximize
protected bool _maximize
Field Value
_modelEvaluator
protected IModelEvaluator<T, TInput, TOutput>? _modelEvaluator
Field Value
- IModelEvaluator<T, TInput, TOutput>
_optimizationMetric
protected MetricType _optimizationMetric
Field Value
_optimizationMetricExplicitlySet
protected bool _optimizationMetricExplicitlySet
Field Value
_searchSpace
protected readonly Dictionary<string, ParameterRange> _searchSpace
Field Value
_trialHistory
protected readonly List<TrialResult> _trialHistory
Field Value
_trialsSinceImprovement
protected int _trialsSinceImprovement
Field Value
Properties
BestModel
Gets the best model found so far
public IFullModel<T, TInput, TOutput>? BestModel { get; protected set; }
Property Value
- IFullModel<T, TInput, TOutput>
BestScore
Gets the best score achieved
public double BestScore { get; protected set; }
Property Value
DefaultLossFunction
Gets the default loss function for gradient computation.
public virtual ILossFunction<T> DefaultLossFunction { get; }
Property Value
Remarks
AutoML delegates to the best model found during search. If no best model exists yet, returns Mean Squared Error as a sensible default.
FeatureNames
Gets the feature names
public virtual string[] FeatureNames { get; set; }
Property Value
- string[]
MaximizeOptimizationMetric
Gets a value indicating whether higher metric values are better.
public bool MaximizeOptimizationMetric { get; }
Property Value
Remarks
For Beginners: For some metrics higher is better (Accuracy). For error metrics lower is better (RMSE).
OptimizationMetric
Gets the optimization metric used to rank trials.
public MetricType OptimizationMetric { get; }
Property Value
Remarks
This is safe to expose and does not reveal proprietary hyperparameter values or model internals.
For Beginners: This is the score AutoML tries to make better (like Accuracy or RMSE).
ParameterCount
Gets the number of parameters
public virtual int ParameterCount { get; }
Property Value
Status
Gets the current optimization status
public AutoMLStatus Status { get; protected set; }
Property Value
SupportsJitCompilation
Gets whether this model currently supports JIT compilation.
public virtual bool SupportsJitCompilation { get; }
Property Value
- bool
True if the best model found supports JIT compilation, false otherwise.
Remarks
AutoML models delegate JIT compilation support to their best model. If no best model has been found yet, JIT compilation is not supported.
For Beginners: AutoML models can only be JIT compiled if the best model they found supports it.
Since AutoML searches across multiple model types, JIT support depends on:
- Whether a best model has been selected
- Whether that specific model supports JIT compilation
Before running SearchAsync, this will return false. After finding a best model, it delegates to that model's JIT support.
TimeLimit
Gets or sets the time limit for the AutoML search
public TimeSpan TimeLimit { get; set; }
Property Value
TrialLimit
Gets or sets the maximum number of trials to run
public int TrialLimit { get; set; }
Property Value
Type
Gets the model type
public virtual ModelType Type { get; }
Property Value
Methods
ApplyGradients(Vector<T>, T)
Applies gradients by delegating to the best model.
public virtual void ApplyGradients(Vector<T> gradients, T learningRate)
Parameters
gradientsVector<T>learningRateT
Clone()
Creates a memberwise clone of the AutoML model using MemberwiseClone(). This performs a shallow copy where reference types are shared between the original and clone.
public virtual IFullModel<T, TInput, TOutput> Clone()
Returns
- IFullModel<T, TInput, TOutput>
A memberwise clone of the current AutoML model
Remarks
For a deep copy with independent collections and state, use DeepCopy() instead.
ComputeGradients(TInput, TOutput, ILossFunction<T>?)
Computes gradients by delegating to the best model.
public virtual Vector<T> ComputeGradients(TInput input, TOutput target, ILossFunction<T>? lossFunction = null)
Parameters
inputTInputtargetTOutputlossFunctionILossFunction<T>
Returns
- Vector<T>
ConfigureSearchSpace(Dictionary<string, ParameterRange>)
Configures the search space for hyperparameter optimization
public virtual void ConfigureSearchSpace(Dictionary<string, ParameterRange> searchSpace)
Parameters
searchSpaceDictionary<string, ParameterRange>Dictionary defining parameter ranges to search
CreateInstanceForCopy()
Factory method for creating a new instance for deep copy. Derived classes must implement this to return a new instance of themselves. This ensures each copy has its own collections and lock object.
protected abstract AutoMLModelBase<T, TInput, TOutput> CreateInstanceForCopy()
Returns
- AutoMLModelBase<T, TInput, TOutput>
A fresh instance of the derived class with default parameters
Remarks
When implementing this method, derived classes should create a fresh instance with default parameters, and should not attempt to preserve runtime or initialization state from the original instance. The deep copy logic will transfer relevant state (trial history, search space, etc.) after construction.
CreateModelAsync(ModelType, Dictionary<string, object>)
Creates a model instance for the given type and parameters
protected abstract Task<IFullModel<T, TInput, TOutput>> CreateModelAsync(ModelType modelType, Dictionary<string, object> parameters)
Parameters
modelTypeModelTypeparametersDictionary<string, object>
Returns
- Task<IFullModel<T, TInput, TOutput>>
DeepCopy()
Creates a deep copy of the AutoML model
public virtual IFullModel<T, TInput, TOutput> DeepCopy()
Returns
- IFullModel<T, TInput, TOutput>
Deserialize(byte[])
Deserializes the model from bytes
public virtual void Deserialize(byte[] data)
Parameters
databyte[]
EnableEarlyStopping(int, double)
Enables early stopping
public virtual void EnableEarlyStopping(int patience, double minDelta = 0.001)
Parameters
EnableNAS(bool)
Enables Neural Architecture Search (NAS) for automatic network design
public virtual void EnableNAS(bool enabled = true)
Parameters
enabledboolWhether to enable NAS
EvaluateModelAsync(IFullModel<T, TInput, TOutput>, TInput, TOutput)
Evaluates a model on the validation set
protected virtual Task<double> EvaluateModelAsync(IFullModel<T, TInput, TOutput> model, TInput validationInputs, TOutput validationTargets)
Parameters
modelIFullModel<T, TInput, TOutput>validationInputsTInputvalidationTargetsTOutput
Returns
ExportComputationGraph(List<ComputationNode<T>>)
Exports the computation graph for JIT compilation by delegating to the best model.
public virtual ComputationNode<T> ExportComputationGraph(List<ComputationNode<T>> inputNodes)
Parameters
inputNodesList<ComputationNode<T>>List to populate with input computation nodes.
Returns
- ComputationNode<T>
The output computation node representing the model's prediction.
Remarks
AutoML models delegate graph export to their best model found during search. The graph structure and complexity depends on the specific best model type.
For Beginners: This creates a computation graph from the best model found.
AutoML itself doesn't have a fixed computation structure since it tries multiple model types. Instead, it delegates to the best model it found:
- If the best model is a neural network, you get a neural network graph
- If it's a regression model, you get a regression graph
- And so on
This only works after SearchAsync has found and selected a best model.
Exceptions
- InvalidOperationException
Thrown when no best model exists (SearchAsync not called yet).
- NotSupportedException
Thrown when the best model does not support JIT compilation.
ExtractMetricFromEvaluation(ModelEvaluationData<T, TInput, TOutput>)
Extracts the appropriate metric value from the evaluation results
protected virtual double ExtractMetricFromEvaluation(ModelEvaluationData<T, TInput, TOutput> evaluationData)
Parameters
evaluationDataModelEvaluationData<T, TInput, TOutput>
Returns
GetActiveFeatureIndices()
Gets the indices of active features
public virtual IEnumerable<int> GetActiveFeatureIndices()
Returns
GetDefaultSearchSpace(ModelType)
Gets the default search space for a model type
protected abstract Dictionary<string, ParameterRange> GetDefaultSearchSpace(ModelType modelType)
Parameters
modelTypeModelType
Returns
GetFeatureImportance()
Gets the feature importance scores
public virtual Dictionary<string, T> GetFeatureImportance()
Returns
- Dictionary<string, T>
GetFeatureImportanceAsync()
Gets feature importance from the best model
public virtual Task<Dictionary<int, double>> GetFeatureImportanceAsync()
Returns
- Task<Dictionary<int, double>>
GetModelMetadata()
Gets model metadata
public virtual ModelMetadata<T> GetModelMetadata()
Returns
GetParameters()
Gets the model parameters
public virtual Vector<T> GetParameters()
Returns
- Vector<T>
GetResults()
Gets the results of all trials performed during search
public virtual List<TrialResult> GetResults()
Returns
- List<TrialResult>
List of trial results with scores and parameters
GetTrialHistory()
Gets the history of all trials
public virtual List<TrialResult> GetTrialHistory()
Returns
IsFeatureUsed(int)
Checks if a feature is used
public virtual bool IsFeatureUsed(int featureIndex)
Parameters
featureIndexint
Returns
LoadModel(string)
Loads the model from a file
public virtual void LoadModel(string filePath)
Parameters
filePathstring
LoadState(Stream)
Loads the AutoML model's state from a stream.
public virtual void LoadState(Stream stream)
Parameters
streamStreamThe stream to read the model state from.
Remarks
This method deserializes a best model that was previously saved with SaveState. It uses the existing Deserialize method after reading data from the stream.
For Beginners: This is like loading a saved snapshot of your best AutoML model.
When you call LoadState:
- The best model is read from the stream
- All parameters and configuration are restored
After loading, the model can:
- Make predictions using the restored best model
- Be further optimized if needed
- Be deployed to production
This is essential for:
- Loading the best model after AutoML search
- Deploying optimized models to production
- Knowledge distillation workflows
Exceptions
- ArgumentNullException
Thrown when stream is null.
- IOException
Thrown when there's an error reading from the stream.
- InvalidOperationException
Thrown when the stream contains invalid or incompatible data, or when BestModel is not initialized.
Predict(double[][])
Makes predictions using the best model (legacy method)
public virtual double[] Predict(double[][] inputs)
Parameters
inputsdouble[][]
Returns
- double[]
Predict(TInput)
Makes predictions using the best model found
public virtual TOutput Predict(TInput input)
Parameters
inputTInput
Returns
- TOutput
ReportTrialFailureAsync(Dictionary<string, object>, Exception, TimeSpan)
Reports a failed trial result without terminating the full AutoML run.
protected virtual Task ReportTrialFailureAsync(Dictionary<string, object> parameters, Exception error, TimeSpan duration)
Parameters
parametersDictionary<string, object>The parameters used in the trial.
errorExceptionThe exception that caused the trial to fail.
durationTimeSpanThe duration of the failed trial.
Returns
ReportTrialResultAsync(Dictionary<string, object>, double, TimeSpan)
Reports the result of a trial
public virtual Task ReportTrialResultAsync(Dictionary<string, object> parameters, double score, TimeSpan duration)
Parameters
parametersDictionary<string, object>scoredoubledurationTimeSpan
Returns
Run(TInput, TOutput, TInput, TOutput)
Runs the AutoML optimization process (alternative name for Search)
public virtual void Run(TInput inputs, TOutput targets, TInput validationInputs, TOutput validationTargets)
Parameters
inputsTInputTraining inputs
targetsTOutputTraining targets
validationInputsTInputValidation inputs
validationTargetsTOutputValidation targets
SaveModel(string)
Saves the model to a file
public virtual void SaveModel(string filePath)
Parameters
filePathstring
SaveState(Stream)
Saves the AutoML model's current state to a stream.
public virtual void SaveState(Stream stream)
Parameters
streamStreamThe stream to write the model state to.
Remarks
This method serializes the best model found during the AutoML search. It uses the existing Serialize method and writes the data to the provided stream.
For Beginners: This is like creating a snapshot of your best AutoML model.
When you call SaveState:
- The best model found during search is written to the stream
- All model parameters and configuration are preserved
This is particularly useful for:
- Saving the best model after AutoML search
- Checkpointing during long-running searches
- Knowledge distillation from AutoML-optimized models
- Deploying optimized models to production
You can later use LoadState to restore the model.
Exceptions
- ArgumentNullException
Thrown when stream is null.
- InvalidOperationException
Thrown when no best model exists.
- IOException
Thrown when there's an error writing to the stream.
Search(TInput, TOutput, TInput, TOutput)
Performs the AutoML search process (synchronous version)
public virtual void Search(TInput inputs, TOutput targets, TInput validationInputs, TOutput validationTargets)
Parameters
inputsTInputTraining inputs
targetsTOutputTraining targets
validationInputsTInputValidation inputs
validationTargetsTOutputValidation targets
SearchAsync(TInput, TOutput, TInput, TOutput, TimeSpan, CancellationToken)
Searches for the best model configuration
public abstract Task<IFullModel<T, TInput, TOutput>> SearchAsync(TInput inputs, TOutput targets, TInput validationInputs, TOutput validationTargets, TimeSpan timeLimit, CancellationToken cancellationToken = default)
Parameters
inputsTInputtargetsTOutputvalidationInputsTInputvalidationTargetsTOutputtimeLimitTimeSpancancellationTokenCancellationToken
Returns
- Task<IFullModel<T, TInput, TOutput>>
SearchBestModel(TInput, TOutput, TInput, TOutput)
Searches for the best model configuration (synchronous version)
public virtual IFullModel<T, TInput, TOutput> SearchBestModel(TInput inputs, TOutput targets, TInput validationInputs, TOutput validationTargets)
Parameters
inputsTInputTraining inputs
targetsTOutputTraining targets
validationInputsTInputValidation inputs
validationTargetsTOutputValidation targets
Returns
- IFullModel<T, TInput, TOutput>
Best model found
Serialize()
Serializes the model to bytes
public virtual byte[] Serialize()
Returns
- byte[]
SetActiveFeatureIndices(IEnumerable<int>)
Sets the active feature indices
public virtual void SetActiveFeatureIndices(IEnumerable<int> featureIndices)
Parameters
featureIndicesIEnumerable<int>
SetCandidateModels(List<ModelType>)
Sets the models to consider in the search
public virtual void SetCandidateModels(List<ModelType> modelTypes)
Parameters
SetConstraints(List<SearchConstraint>)
Sets constraints for the search
public virtual void SetConstraints(List<SearchConstraint> constraints)
Parameters
constraintsList<SearchConstraint>
SetModelEvaluator(IModelEvaluator<T, TInput, TOutput>)
Sets the model evaluator to use for evaluating candidate models
public virtual void SetModelEvaluator(IModelEvaluator<T, TInput, TOutput> evaluator)
Parameters
evaluatorIModelEvaluator<T, TInput, TOutput>
SetModelsToTry(List<ModelType>)
Sets which model types should be considered during the search
public virtual void SetModelsToTry(List<ModelType> modelTypes)
Parameters
SetOptimizationMetric(MetricType, bool)
Sets the optimization metric
public virtual void SetOptimizationMetric(MetricType metric, bool maximize = true)
Parameters
metricMetricTypemaximizebool
SetParameters(Vector<T>)
Sets the model parameters
public virtual void SetParameters(Vector<T> parameters)
Parameters
parametersVector<T>
SetSearchSpace(Dictionary<string, ParameterRange>)
Sets the search space for hyperparameters
public virtual void SetSearchSpace(Dictionary<string, ParameterRange> searchSpace)
Parameters
searchSpaceDictionary<string, ParameterRange>
SetTimeLimit(TimeSpan)
Sets the time limit for the AutoML search process
public virtual void SetTimeLimit(TimeSpan timeLimit)
Parameters
timeLimitTimeSpanMaximum time to spend searching for optimal models
SetTrialLimit(int)
Sets the maximum number of trials to execute during search
public virtual void SetTrialLimit(int maxTrials)
Parameters
maxTrialsintMaximum number of model configurations to try
ShouldStop()
Checks if early stopping criteria is met
protected bool ShouldStop()
Returns
SuggestNextTrialAsync()
Suggests the next hyperparameters to try
public abstract Task<Dictionary<string, object>> SuggestNextTrialAsync()
Returns
Train(double[][], double[])
Trains the model (legacy method - use SearchAsync instead)
public virtual void Train(double[][] inputs, double[] outputs)
Parameters
Train(TInput, TOutput)
Trains the AutoML model by searching for the best configuration
public virtual void Train(TInput input, TOutput expectedOutput)
Parameters
inputTInputexpectedOutputTOutput
ValidateConstraints(Dictionary<string, object>, IFullModel<T, TInput, TOutput>?)
Validates constraints for a given configuration
protected bool ValidateConstraints(Dictionary<string, object> parameters, IFullModel<T, TInput, TOutput>? model = null)
Parameters
parametersDictionary<string, object>modelIFullModel<T, TInput, TOutput>
Returns
WithParameters(Vector<T>)
Creates a new instance with the given parameters
public virtual IFullModel<T, TInput, TOutput> WithParameters(Vector<T> parameters)
Parameters
parametersVector<T>
Returns
- IFullModel<T, TInput, TOutput>