Table of Contents

Class GeneticBase<T, TInput, TOutput>

Namespace
AiDotNet.Genetics
Assembly
AiDotNet.dll

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

T

The numeric type used for calculations (e.g., double, float).

TInput

The type of input data for the model.

TOutput

The 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

fitnessCalculator IFitnessCalculator<T, TInput, TOutput>

The fitness calculator to use.

modelEvaluator IModelEvaluator<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

Stopwatch

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

GeneticParameters

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

Random

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

name string

The name of the crossover operator.

crossoverOperator Func<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

name string

The name of the mutation operator.

mutationOperator Func<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

individual1 ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>

The first individual.

individual2 ModelIndividual<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

parameters GeneticParameters

The 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

genes ICollection<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

trainingInput TInput

The input training data.

trainingOutput TOutput

The expected output for training.

validationInput TInput

Optional validation input data.

validationOutput TOutput

Optional 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

parent1 ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>

The first parent individual.

parent2 ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>

The second parent individual.

crossoverRate double

The 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

data byte[]

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

data byte[]

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

data byte[]

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

data byte[]

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

individual ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>

The individual to evaluate.

trainingInput TInput

The input training data.

trainingOutput TOutput

The expected output for training.

validationInput TInput

Optional validation input data.

validationOutput TOutput

Optional 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

trainingInput TInput

The input training data.

trainingOutput TOutput

The expected output for training.

validationInput TInput

Optional validation input data.

validationOutput TOutput

Optional 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

generations int

The number of generations to evolve.

trainingInput TInput

The input training data used for fitness evaluation.

trainingOutput TOutput

The expected output for training used for fitness evaluation.

validationInput TInput

Optional validation input data.

validationOutput TOutput

Optional validation output data.

stopCriteria Func<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

count int

The 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

fitnessCalculator IFitnessCalculator<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

individual ModelIndividual<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

populationSize int

The size of the population to create.

initializationMethod InitializationMethod

The 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

fitness T

The 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

fitnessA T

The first fitness score.

fitnessB T

The 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

filePath string

The 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

individual ModelIndividual<T, TInput, TOutput, ModelParameterGene<T>>

The individual to mutate.

mutationRate double

The 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

gene ModelParameterGene<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

gene ModelParameterGene<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

input TInput

The 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

selectionSize int

The 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

selectionSize int

The 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

filePath string

The 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

selectionSize int

The number of individuals to select.

selectionMethod SelectionMethod

The 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

individual ModelIndividual<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

fitnessCalculator IFitnessCalculator<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

selectionSize int

The 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

selectionSize int

The 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

selectionSize int

The 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

selectionSize int

The 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()