Class GeneticBase<T, TInput, TOutput>
Provides a base implementation of IGeneticModel that handles common genetic algorithm operations.
public abstract class GeneticBase<T, TInput, TOutput> : IGeneticAlgorithm<T, TInput, TOutput, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelParameterGene<T>>
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.
- Inheritance
-
GeneticBase<T, TInput, TOutput>
- Implements
-
IGeneticAlgorithm<T, TInput, TOutput, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelParameterGene<T>>
- Derived
- Inherited Members
Remarks
This abstract base class implements the IGeneticModel interface, providing standard implementations for common genetic algorithm operations while allowing derived classes to customize behavior specific to their genetic model type.
For Beginners: This class provides a ready-to-use foundation for genetic algorithm models. It handles:
- Managing a population of candidate solutions
- Evolving the population through selection, crossover, and mutation
- Tracking statistics about the evolutionary process
- Saving and loading populations
When creating your own genetic model, you can inherit from this class and focus on the specific implementation details of your model type rather than reimplementing the entire genetic algorithm framework.
Constructors
GeneticBase(IFitnessCalculator<T, TInput, TOutput>, IModelEvaluator<T, TInput, TOutput>)
Initializes a new instance of the GeneticModelBase class.
protected GeneticBase(IFitnessCalculator<T, TInput, TOutput> fitnessCalculator, IModelEvaluator<T, TInput, TOutput> modelEvaluator)
Parameters
fitnessCalculatorIFitnessCalculator<T, TInput, TOutput>The fitness calculator to use.
modelEvaluatorIModelEvaluator<T, TInput, TOutput>
Properties
BestIndividual
The best individual found so far.
protected ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>? BestIndividual { get; set; }
Property Value
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
CrossoverOperators
A dictionary mapping crossover operator names to implementations.
protected Dictionary<string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>>> CrossoverOperators { get; set; }
Property Value
- Dictionary<string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>>>
CurrentStats
The current evolution statistics.
protected EvolutionStats<T, TInput, TOutput> CurrentStats { get; set; }
Property Value
- EvolutionStats<T, TInput, TOutput>
EvolutionStopwatch
A stopwatch for tracking evolution time.
protected Stopwatch EvolutionStopwatch { get; set; }
Property Value
FitnessCalculator
The fitness calculator used to evaluate individuals.
protected IFitnessCalculator<T, TInput, TOutput> FitnessCalculator { get; set; }
Property Value
- IFitnessCalculator<T, TInput, TOutput>
GeneticParams
The parameters for the genetic algorithm.
protected GeneticParameters GeneticParams { get; set; }
Property Value
ModelEvaluator
The fitness calculator used to evaluate individuals.
protected IModelEvaluator<T, TInput, TOutput> ModelEvaluator { get; set; }
Property Value
- IModelEvaluator<T, TInput, TOutput>
MutationOperators
A dictionary mapping mutation operator names to implementations.
protected Dictionary<string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>> MutationOperators { get; set; }
Property Value
- Dictionary<string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>>
NumOps
protected INumericOperations<T> NumOps { get; set; }
Property Value
- INumericOperations<T>
Population
The current population of individuals.
protected List<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> Population { get; set; }
Property Value
- List<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
Random
The random number generator used for stochastic operations.
protected Random Random { get; set; }
Property Value
TrainingInputForInitialization
The training input data, stored before population initialization so derived classes can use it to determine proper parameter dimensions when models have empty parameters.
protected TInput? TrainingInputForInitialization { get; set; }
Property Value
- TInput
Methods
AddCrossoverOperator(string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>>)
Adds a custom crossover operator.
public virtual void AddCrossoverOperator(string name, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>> crossoverOperator)
Parameters
namestringThe name of the crossover operator.
crossoverOperatorFunc<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>>The crossover function.
AddDefaultCrossoverOperators()
Adds default crossover operators.
protected virtual void AddDefaultCrossoverOperators()
AddDefaultMutationOperators()
Adds default mutation operators.
protected virtual void AddDefaultMutationOperators()
AddMutationOperator(string, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>)
Adds a custom mutation operator.
public virtual void AddMutationOperator(string name, Func<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> mutationOperator)
Parameters
namestringThe name of the mutation operator.
mutationOperatorFunc<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>The mutation function.
CalculateDiversity()
Calculates the genetic diversity of the population.
protected virtual T CalculateDiversity()
Returns
- T
A measure of genetic diversity.
CalculateGeneticDistance(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>)
Calculates the genetic distance between two individuals.
protected virtual T CalculateGeneticDistance(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual1, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual2)
Parameters
individual1ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The first individual.
individual2ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The second individual.
Returns
- T
A measure of genetic distance.
ConfigureGeneticParameters(GeneticParameters)
Configures the genetic algorithm parameters.
public virtual void ConfigureGeneticParameters(GeneticParameters parameters)
Parameters
parametersGeneticParametersThe genetic algorithm parameters to use.
CreateIndividual(ICollection<ModelParameterGene<T>>)
Creates a new individual with the specified genes.
public abstract ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> CreateIndividual(ICollection<ModelParameterGene<T>> genes)
Parameters
genesICollection<ModelParameterGene<T>>The genes to include in the individual.
Returns
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
A new individual with the specified genes.
CreateNextGeneration(TInput, TOutput, TInput?, TOutput?)
Creates the next generation of individuals through selection, crossover, and mutation.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> CreateNextGeneration(TInput trainingInput, TOutput trainingOutput, TInput? validationInput = default, TOutput? validationOutput = default)
Parameters
trainingInputTInputThe input training data.
trainingOutputTOutputThe expected output for training.
validationInputTInputOptional validation input data.
validationOutputTOutputOptional validation output data.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The new population.
Crossover(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double)
Performs crossover between two parent individuals to produce offspring.
public virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> Crossover(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> parent1, ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> parent2, double crossoverRate)
Parameters
parent1ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The first parent individual.
parent2ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The second parent individual.
crossoverRatedoubleThe probability of crossover occurring.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
One or more offspring produced by crossover.
Deserialize(byte[])
Deserializes the model from a byte array.
public virtual void Deserialize(byte[] data)
Parameters
databyte[]The byte array containing the serialized model.
DeserializeIndividual(byte[])
Deserializes an individual from a byte array.
protected abstract ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> DeserializeIndividual(byte[] data)
Parameters
databyte[]The byte array containing the serialized individual.
Returns
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
The deserialized individual.
DeserializeModelData(byte[])
Deserializes model-specific data.
protected abstract void DeserializeModelData(byte[] data)
Parameters
databyte[]The byte array containing the serialized model data.
DeserializePopulation(byte[])
Deserializes a population from a byte array.
protected abstract ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> DeserializePopulation(byte[] data)
Parameters
databyte[]The byte array containing the serialized population.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The deserialized population.
EvaluateIndividual(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, TInput, TOutput, TInput?, TOutput?)
Evaluates an individual by converting it to a model and generating evaluation data.
public T EvaluateIndividual(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual, TInput trainingInput, TOutput trainingOutput, TInput? validationInput = default, TOutput? validationOutput = default)
Parameters
individualModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The individual to evaluate.
trainingInputTInputThe input training data.
trainingOutputTOutputThe expected output for training.
validationInputTInputOptional validation input data.
validationOutputTOutputOptional validation output data.
Returns
- T
The calculated fitness score for the individual.
EvaluatePopulation(TInput, TOutput, TInput?, TOutput?)
Evaluates all individuals in the population.
protected virtual void EvaluatePopulation(TInput trainingInput, TOutput trainingOutput, TInput? validationInput = default, TOutput? validationOutput = default)
Parameters
trainingInputTInputThe input training data.
trainingOutputTOutputThe expected output for training.
validationInputTInputOptional validation input data.
validationOutputTOutputOptional validation output data.
Evolve(int, TInput, TOutput, TInput?, TOutput?, Func<EvolutionStats<T, TInput, TOutput>, bool>?)
Evolves the population for a specified number of generations.
public virtual EvolutionStats<T, TInput, TOutput> Evolve(int generations, TInput trainingInput, TOutput trainingOutput, TInput? validationInput = default, TOutput? validationOutput = default, Func<EvolutionStats<T, TInput, TOutput>, bool>? stopCriteria = null)
Parameters
generationsintThe number of generations to evolve.
trainingInputTInputThe input training data used for fitness evaluation.
trainingOutputTOutputThe expected output for training used for fitness evaluation.
validationInputTInputOptional validation input data.
validationOutputTOutputOptional validation output data.
stopCriteriaFunc<EvolutionStats<T, TInput, TOutput>, bool>Optional function that determines when to stop evolution.
Returns
- EvolutionStats<T, TInput, TOutput>
Statistics about the evolutionary process.
FindBestIndividual()
Finds the best individual in the current population.
protected virtual ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> FindBestIndividual()
Returns
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
The individual with the best fitness.
GetBestIndividual()
Gets the best individual from the current population.
public ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> GetBestIndividual()
Returns
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
The individual with the highest fitness, or throws an exception if no best individual exists.
GetElites(int)
Gets the elite individuals (best performers) from the population.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> GetElites(int count)
Parameters
countintThe number of elite individuals to get.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The elite individuals.
GetEvolutionStats(IFitnessCalculator<T, TInput, TOutput>)
Gets statistics about the current evolutionary state.
public virtual EvolutionStats<T, TInput, TOutput> GetEvolutionStats(IFitnessCalculator<T, TInput, TOutput> fitnessCalculator)
Parameters
fitnessCalculatorIFitnessCalculator<T, TInput, TOutput>
Returns
- EvolutionStats<T, TInput, TOutput>
Statistics about the current evolutionary state.
GetFitnessCalculator()
Gets the fitness calculator used to evaluate individuals.
public IFitnessCalculator<T, TInput, TOutput> GetFitnessCalculator()
Returns
- IFitnessCalculator<T, TInput, TOutput>
The fitness calculator instance used by this genetic model.
GetGeneticParameters()
Gets the current genetic algorithm parameters.
public virtual GeneticParameters GetGeneticParameters()
Returns
- GeneticParameters
The current genetic algorithm parameters.
GetMetaData()
Gets the metadata for the model.
public abstract ModelMetadata<T> GetMetaData()
Returns
- ModelMetadata<T>
The model metadata.
GetPopulation()
Gets the current population of individuals in the genetic model.
public ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> GetPopulation()
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
A collection of individuals representing the current population.
IndividualToModel(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>)
Converts an individual to a trained model that can make predictions.
public abstract IFullModel<T, TInput, TOutput> IndividualToModel(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual)
Parameters
individualModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The individual to convert.
Returns
- IFullModel<T, TInput, TOutput>
A model capable of making predictions based on the individual's genes.
InitializePopulation(int, InitializationMethod)
Initializes a new population with random individuals.
public abstract ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> InitializePopulation(int populationSize, InitializationMethod initializationMethod)
Parameters
populationSizeintThe size of the population to create.
initializationMethodInitializationMethodThe method to use for initialization.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The newly created population.
InvertFitness(T)
Inverts a fitness score for use in comparisons.
protected virtual T InvertFitness(T fitness)
Parameters
fitnessTThe fitness score to invert.
Returns
- T
The inverted fitness score.
IsBetterFitness(T, T)
Determines if one fitness score is better than another.
protected virtual bool IsBetterFitness(T fitnessA, T fitnessB)
Parameters
fitnessATThe first fitness score.
fitnessBTThe second fitness score.
Returns
- bool
True if fitnessA is better than fitnessB; otherwise, false.
LoadPopulation(string)
Loads a population from a file.
public virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> LoadPopulation(string filePath)
Parameters
filePathstringThe path from which to load the population.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The loaded population.
Mutate(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>, double)
Applies mutation to an individual.
public virtual ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> Mutate(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual, double mutationRate)
Parameters
individualModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The individual to mutate.
mutationRatedoubleThe probability of each gene mutating.
Returns
- ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>
The mutated individual.
MutateGene(ModelParameterGene<T>)
Creates a mutated version of a gene.
protected abstract ModelParameterGene<T> MutateGene(ModelParameterGene<T> gene)
Parameters
geneModelParameterGene<T>The gene to mutate.
Returns
- ModelParameterGene<T>
A mutated copy of the gene.
MutateGeneGaussian(ModelParameterGene<T>)
Creates a mutated version of a gene using Gaussian noise.
protected abstract ModelParameterGene<T> MutateGeneGaussian(ModelParameterGene<T> gene)
Parameters
geneModelParameterGene<T>The gene to mutate.
Returns
- ModelParameterGene<T>
A mutated copy of the gene.
Predict(TInput)
Makes a prediction using the current best model.
public virtual TOutput Predict(TInput input)
Parameters
inputTInputThe input data.
Returns
- TOutput
The predicted output.
RankSelection(int)
Selects individuals using rank selection.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> RankSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
RouletteWheelSelection(int)
Selects individuals using roulette wheel selection.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> RouletteWheelSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
SavePopulation(string)
Saves the current population to a file.
public virtual void SavePopulation(string filePath)
Parameters
filePathstringThe path where the population should be saved.
Select(int, SelectionMethod)
Selects individuals from the population for reproduction.
public virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> Select(int selectionSize, SelectionMethod selectionMethod)
Parameters
selectionSizeintThe number of individuals to select.
selectionMethodSelectionMethodThe method to use for selection (e.g., tournament, roulette wheel).
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
Serialize()
Serializes the model to a byte array.
public virtual byte[] Serialize()
Returns
- byte[]
A byte array containing the serialized model.
SerializeIndividual(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>)
Serializes an individual to a byte array.
protected abstract byte[] SerializeIndividual(ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>> individual)
Parameters
individualModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>The individual to serialize.
Returns
- byte[]
A byte array containing the serialized individual.
SerializeModelData()
Serializes model-specific data.
protected abstract byte[] SerializeModelData()
Returns
- byte[]
A byte array containing the serialized model data.
SerializePopulation()
Serializes the population to a byte array.
protected abstract byte[] SerializePopulation()
Returns
- byte[]
A byte array containing the serialized population.
SetFitnessCalculator(IFitnessCalculator<T, TInput, TOutput>)
Sets the fitness calculator to be used for evaluating individuals.
public void SetFitnessCalculator(IFitnessCalculator<T, TInput, TOutput> fitnessCalculator)
Parameters
fitnessCalculatorIFitnessCalculator<T, TInput, TOutput>The fitness calculator to use.
StochasticUniversalSamplingSelection(int)
Selects individuals using stochastic universal sampling.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> StochasticUniversalSamplingSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
TournamentSelection(int)
Selects individuals using tournament selection.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> TournamentSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
TruncationSelection(int)
Selects individuals using truncation selection.
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> TruncationSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
UniformSelection(int)
Selects individuals using uniform selection (all individuals have equal probability).
protected virtual ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>> UniformSelection(int selectionSize)
Parameters
selectionSizeintThe number of individuals to select.
Returns
- ICollection<ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>>
The selected individuals.
UpdateEvolutionStats()
Updates the evolution statistics based on the current population.
protected virtual void UpdateEvolutionStats()