Class NSGAIISampler
- Namespace
- OptunaSharp.Samplers
- Assembly
- OptunaSharp.dll
Multi-objective sampler using the NSGA-II algorithm. Port of
optuna/samplers/nsgaii/_sampler.py: NSGAIISampler.
NSGA-II ("Nondominated Sorting Genetic Algorithm II") is a fast, elitist multi-objective genetic algorithm. See Deb et al. (2002).
Parity. The default (UniformCrossover + no mutation object) path is bit-exact against Optuna: uniform crossover copies parent values verbatim and mutated-away parameters are resampled by the independent RandomSampler (both MT19937). Every RNG draw runs through LazyRandomState, and the generation / parent-cache system attributes are byte-identical, so full study state matches. The arithmetic crossovers (BLX-α/SBX/vSBX/SPX) stay bit-exact; UNDXCrossover is tolerance-bounded for ≥2 numerical parameters (managed QR vs LAPACK — see its note) but keeps RNG lock-step.
Conditional parameters. To optimize conditional (define-by-run, branch-defined) hyperparameters — which otherwise fall out of the intersection search space and are resampled at random on every trial — use NSGAIIICptSampler (NSGA-III-CPT), the OptunaSharp variant that carries a ConditionalParams rule set. This sampler itself is a bit-exact Optuna port with no such extension.
public class NSGAIISampler : BaseGASampler
- Inheritance
-
NSGAIISampler
- Derived
- Inherited Members
Constructors
NSGAIISampler(int, BaseMutation?, double?, BaseCrossover?, double, double, int?, Func<FrozenTrial, IEnumerable<double>>?, Func<Study, List<FrozenTrial>, List<FrozenTrial>>?, Func<Study, OrderedDict<string, BaseDistribution>, List<FrozenTrial>, OrderedDict<string, object?>>?, Action<Study, FrozenTrial, TrialState, IReadOnlyList<double>?>?)
Configures NSGA-II population selection, crossover, mutation, and trial-completion hooks.
public NSGAIISampler(int populationSize = 50, BaseMutation? mutation = null, double? mutationProb = null, BaseCrossover? crossover = null, double crossoverProb = 0.9, double swappingProb = 0.5, int? seed = null, Func<FrozenTrial, IEnumerable<double>>? constraintsFunc = null, Func<Study, List<FrozenTrial>, List<FrozenTrial>>? elitePopulationSelectionStrategy = null, Func<Study, OrderedDict<string, BaseDistribution>, List<FrozenTrial>, OrderedDict<string, object?>>? childGenerationStrategy = null, Action<Study, FrozenTrial, TrialState, IReadOnlyList<double>?>? afterTrialStrategy = null)
Parameters
populationSizeintNumber of individuals (trials) in a generation. Must be >=
crossover.NParents(3 for UNDXCrossover/SPXCrossover, else 2).mutationBaseMutationMutation applied when creating child individuals. If
null, the parameter selected for mutation is instead resampled independently using RandomSampler.mutationProbdouble?Probability of mutating each parameter. If
null,1 / len(parent.params)is used.crossoverBaseCrossoverCrossover applied when creating child individuals. UniformCrossover is always applied to categorical parameters, and by default to the others.
crossoverProbdoubleProbability that a crossover occurs when creating a new individual.
swappingProbdoubleProbability of swapping each parameter of the parents during crossover.
seedint?Seed for random number generator.
constraintsFuncFunc<FrozenTrial, IEnumerable<double>>Deprecated (v5.0.0). Optional function computing objective constraints (a value strictly larger than 0 means a constraint is violated). Handled by constrained domination.
elitePopulationSelectionStrategyFunc<Study, List<FrozenTrial>, List<FrozenTrial>>Experimental (v3.3.0). Overrides elite selection.
childGenerationStrategyFunc<Study, OrderedDict<string, BaseDistribution>, List<FrozenTrial>, OrderedDict<string, object>>Experimental (v3.3.0). Overrides child generation.
afterTrialStrategyAction<Study, FrozenTrial, TrialState, IReadOnlyList<double>>Experimental (v3.3.0). Overrides the after-trial procedure.
Exceptions
- ValueError
Population size is below two or the crossover parent count, or a configured reproduction probability is invalid.
Methods
AfterTrial(Study, FrozenTrial, TrialState, IReadOnlyList<double>?)
Trial post-processing: called after the objective function returns and right before the trial is finished and its state is stored.
public override void AfterTrial(Study study, FrozenTrial trial, TrialState state, IReadOnlyList<double>? values)
Parameters
studyStudyStudy that owns the trial being finished.
trialFrozenTrialTrial snapshot before its terminal state is written to storage.
stateTrialStateTerminal state being recorded: complete, pruned, or failed.
valuesIReadOnlyList<double>Resulting trial values in objective order; non-null for a successful trial.
Exceptions
- Exception
A configured after-trial or constraint callback fails; its exception propagates.
BeforeTrial(Study, FrozenTrial)
Trial pre-processing: called during trial initialization, just before the InferRelativeSearchSpace(Study, FrozenTrial) call.
public override void BeforeTrial(Study study, FrozenTrial trial)
Parameters
studyStudyStudy that owns the newly initialized trial.
trialFrozenTrialNew trial snapshot available before search-space inference.
InferRelativeSearchSpace(Study, FrozenTrial)
Infer the search space that will be used by relative sampling in the target trial.
This method is called right before SampleRelative(Study, FrozenTrial, OrderedDict<string, BaseDistribution>), and the search space returned by this method is passed to it. The parameters not contained in the search space will be sampled by using SampleIndependent(Study, FrozenTrial, string, BaseDistribution).
public override OrderedDict<string, BaseDistribution> InferRelativeSearchSpace(Study study, FrozenTrial trial)
Parameters
studyStudyStudy supplying trial history, directions, and storage.
trialFrozenTrialCurrent trial snapshot; copy it before modifying its contents.
Returns
- OrderedDict<string, BaseDistribution>
Parameter distributions eligible for joint sampling, in sampler-defined order.
ReseedRng()
Reseed sampler's random number generator.
Parallel optimization calls this hook before a worker's sequential trial loop. Concrete samplers refresh their random streams so workers do not deliberately reuse a seeded sequence. OptunaSharp workers share the study's sampler instance; this hook does not clone it or make concurrent sampling reproducible.
public override void ReseedRng()
SampleIndependent(Study, FrozenTrial, string, BaseDistribution)
Sample a parameter for a given distribution.
This method is called only for the parameters not contained in the search space returned by SampleRelative(Study, FrozenTrial, OrderedDict<string, BaseDistribution>). This method is suitable for sampling algorithms that do not use relationship between parameters such as random sampling and TPE.
public override object? SampleIndependent(Study study, FrozenTrial trial, string paramName, BaseDistribution paramDistribution)
Parameters
studyStudyStudy supplying trial history, directions, and storage.
trialFrozenTrialCurrent trial snapshot; copy it before modifying its contents.
paramNamestringName of the parameter being suggested.
paramDistributionBaseDistributionDistribution defining the parameter's domain and scale.
Returns
- object
A value in the distribution's external representation, including null categorical choices.
SampleRelative(Study, FrozenTrial, OrderedDict<string, BaseDistribution>)
Sample parameters in a given search space.
The trial invokes this method lazily when it first needs relative parameters and caches the result for its remaining suggestions. This method is suitable for sampling algorithms that use relationship between parameters such as Gaussian Process and CMA-ES.
public override OrderedDict<string, object?> SampleRelative(Study study, FrozenTrial trial, OrderedDict<string, BaseDistribution> searchSpace)
Parameters
studyStudyStudy supplying trial history, directions, and storage.
trialFrozenTrialCurrent trial snapshot; copy it before modifying its contents.
searchSpaceOrderedDict<string, BaseDistribution>Distributions returned by InferRelativeSearchSpace(Study, FrozenTrial).
Returns
- OrderedDict<string, object>
Jointly sampled external parameter values; omitted parameters use independent sampling.
SelectParent(Study, int)
Select parent trials from the population for the given generation. Called once per generation; the result is cached in the study system attributes.
public override List<FrozenTrial> SelectParent(Study study, int generation)
Parameters
studyStudyStudy supplying trial history, objective directions, and storage.
generationintZero-based generation whose individuals or optimizer state are requested.
Returns
- List<FrozenTrial>
The selected parent trials for the requested generation.