Class ModelIndividual<T, TInput, TOutput, TGene>
Represents an individual that is also a full model, allowing direct evolution of models without conversion between individuals and models.
public class ModelIndividual<T, TInput, TOutput, TGene> : IEvolvable<TGene, T>, 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> where TGene : class
Type Parameters
TThe numeric type used for calculations (e.g., double, float).
TInputThe type of input data for the model.
TOutputThe type of output data produced by the model.
TGeneThe type representing a gene in the genetic model.
- Inheritance
-
ModelIndividual<T, TInput, TOutput, TGene>
- Implements
-
IEvolvable<TGene, T>IFullModel<T, TInput, TOutput>IModel<TInput, TOutput, ModelMetadata<T>>IParameterizable<T, TInput, TOutput>ICloneable<IFullModel<T, TInput, TOutput>>IGradientComputable<T, TInput, TOutput>
- Inherited Members
- Extension Methods
Remarks
This class implements both IEvolvable and IFullModel interfaces, allowing it to be used directly in genetic algorithms while also providing model prediction capabilities.
For Beginners: This class combines the functionality of an individual in a genetic algorithm with a machine learning model. This means:
- You can evolve the model directly without converting between different representations
- The individual can make predictions like any other model
- It simplifies the implementation of genetic algorithms for model optimization
Use this when you want to directly evolve machine learning models using genetic algorithms.
Constructors
ModelIndividual(IFullModel<T, TInput, TOutput>, ICollection<TGene>, Func<ICollection<TGene>, IFullModel<T, TInput, TOutput>>)
Creates a new model individual by wrapping an existing model.
public ModelIndividual(IFullModel<T, TInput, TOutput> model, ICollection<TGene> genes, Func<ICollection<TGene>, IFullModel<T, TInput, TOutput>> modelFactory)
Parameters
modelIFullModel<T, TInput, TOutput>The model to wrap.
genesICollection<TGene>The genes representing the model.
modelFactoryFunc<ICollection<TGene>, IFullModel<T, TInput, TOutput>>A function that creates a model from genes.
ModelIndividual(ICollection<TGene>, Func<ICollection<TGene>, IFullModel<T, TInput, TOutput>>)
Creates a new model individual with the specified genes and model factory.
public ModelIndividual(ICollection<TGene> genes, Func<ICollection<TGene>, IFullModel<T, TInput, TOutput>> modelFactory)
Parameters
genesICollection<TGene>The genes to initialize with.
modelFactoryFunc<ICollection<TGene>, IFullModel<T, TInput, TOutput>>A function that creates a model from genes.
Properties
DefaultLossFunction
Gets the default loss function for gradient computation by delegating to the inner model.
public ILossFunction<T> DefaultLossFunction { get; }
Property Value
ParameterCount
Gets the number of parameters in the model.
public virtual 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.
SupportsJitCompilation
Gets whether this model currently supports JIT compilation.
public virtual bool SupportsJitCompilation { get; }
Property Value
- bool
True if the inner model supports JIT compilation, false otherwise.
Remarks
Model individuals delegate JIT compilation support to their inner model. Genetic evolution does not affect JIT compilability - it depends on the wrapped model type.
For Beginners: Genetically evolved models can be JIT compiled if their inner model supports it.
The genetic algorithm modifies the model's genes (parameters/structure), but:
- The underlying computation graph can still be JIT compiled
- Evolution happens at the model level, JIT compilation at the execution level
- Both work together: evolution finds good parameters, JIT makes them run fast
Methods
ApplyGradients(Vector<T>, T)
Applies gradients by delegating to the inner model.
public void ApplyGradients(Vector<T> gradients, T learningRate)
Parameters
gradientsVector<T>learningRateT
Clone()
Creates a deep clone of this individual.
public IEvolvable<TGene, T> Clone()
Returns
- IEvolvable<TGene, T>
A new individual with the same genes and fitness.
ComputeGradients(TInput, TOutput, ILossFunction<T>?)
Computes gradients by delegating to the inner model.
public Vector<T> ComputeGradients(TInput input, TOutput target, ILossFunction<T>? lossFunction = null)
Parameters
inputTInputtargetTOutputlossFunctionILossFunction<T>
Returns
- Vector<T>
DeepCopy()
Creates a deep copy of this object.
public IFullModel<T, TInput, TOutput> DeepCopy()
Returns
- IFullModel<T, TInput, TOutput>
Deserialize(byte[])
Deserializes the model from a byte array.
public void Deserialize(byte[] data)
Parameters
databyte[]The byte array containing the serialized model.
ExportComputationGraph(List<ComputationNode<T>>)
Exports the computation graph for JIT compilation by delegating to the inner 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
Model individuals delegate graph export to their inner model. The graph represents the current evolved model's computation.
For Beginners: This creates a computation graph from the evolved model.
When genetic algorithms evolve a model:
- The genes determine the model's parameters or structure
- The inner model is rebuilt from those genes
- That inner model can then be JIT compiled for fast execution
This allows you to:
- Evolve models to find good architectures
- JIT compile the best evolved models for production use
- Get both the benefits of evolution and fast execution
Exceptions
- ArgumentNullException
Thrown when inputNodes is null.
- InvalidOperationException
Thrown when inner model is null.
- NotSupportedException
Thrown when the inner model does not support JIT compilation.
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 virtual Dictionary<string, T> GetFeatureImportance()
Returns
- Dictionary<string, T>
GetFitness()
Gets the fitness of this individual.
public T GetFitness()
Returns
- T
The fitness value.
GetGenes()
Gets the genes of this individual.
public ICollection<TGene> GetGenes()
Returns
- ICollection<TGene>
The collection of genes.
GetMetaData()
Gets the metadata for the model.
public ModelMetadata<T> GetMetaData()
Returns
- ModelMetadata<T>
The model metadata.
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 of the model.
public Vector<T> GetParameters()
Returns
- Vector<T>
The model parameters as a vector.
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 virtual 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 from a stream.
public void LoadState(Stream stream)
Parameters
streamStream
Predict(TInput)
Makes a prediction using the inner model.
public TOutput Predict(TInput input)
Parameters
inputTInputThe input data.
Returns
- TOutput
The predicted output.
SaveModel(string)
Saves the model to a file.
public virtual 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 to a stream.
public void SaveState(Stream stream)
Parameters
streamStream
Serialize()
Serializes the model to a byte array.
public byte[] Serialize()
Returns
- byte[]
A byte array containing the serialized model.
SetActiveFeatureIndices(IEnumerable<int>)
Sets the active feature indices for this model.
public virtual void SetActiveFeatureIndices(IEnumerable<int> featureIndices)
Parameters
featureIndicesIEnumerable<int>
SetFitness(T)
Sets the fitness of this individual.
public void SetFitness(T fitness)
Parameters
fitnessTThe new fitness value.
SetGenes(ICollection<TGene>)
Sets the genes of this individual and updates the inner model.
public void SetGenes(ICollection<TGene> genes)
Parameters
genesICollection<TGene>The new genes.
SetParameters(Vector<T>)
Sets the model parameters.
public virtual 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(TInput, TOutput)
Trains the model using input features and their corresponding target values.
public void Train(TInput input, TOutput expectedOutput)
Parameters
inputTInputexpectedOutputTOutput
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
UpdateParameters(Vector<T>)
Updates the parameters of the model.
public void UpdateParameters(Vector<T> parameters)
Parameters
parametersVector<T>The new parameters.
WithParameters(Vector<T>)
Creates a new model with the specified parameters.
public IFullModel<T, TInput, TOutput> WithParameters(Vector<T> parameters)
Parameters
parametersVector<T>The parameters for the new model.
Returns
- IFullModel<T, TInput, TOutput>
A new model with the specified parameters.