/// <inheritdoc /> public override void TrainingBatch(IGenerateRandom rnd) { for (var i = 0; i < _active.Length; i++) { _active[i] = rnd.NextDouble() > DropoutProbability; } }
/// <inheritdoc/> public int PerformAntiSelection(IGenerateRandom rnd, ISpecies species) { int worstIndex = rnd.NextInt(species.Members.Count); IGenome worst = species.Members[worstIndex]; BasicEA.CalculateScoreAdjustment(worst, Trainer.ScoreAdjusters); for (int i = 0; i < this.Rounds; i++) { int competitorIndex = rnd.NextInt(species.Members.Count); IGenome competitor = species.Members[competitorIndex]; // force an invalid genome to lose if (double.IsInfinity(competitor.AdjustedScore) || double.IsNaN(competitor.AdjustedScore)) { return competitorIndex; } BasicEA.CalculateScoreAdjustment(competitor, Trainer.ScoreAdjusters); if (!Trainer.SelectionComparer.IsBetterThan(competitor, worst)) { worst = competitor; worstIndex = competitorIndex; } } return worstIndex; }
/// <summary> /// Create an initial population. /// </summary> /// <param name="rnd">Random number generator.</param> /// <param name="codec">The codec, the type of network to use.</param> /// <returns>The population.</returns> public static IPopulation InitPopulation(IGenerateRandom rnd, RBFNetworkGenomeCODEC codec) { // Create a RBF network to get the length. var network = new RBFNetwork(codec.InputCount, codec.RbfCount, codec.OutputCount); int size = network.LongTermMemory.Length; // Create a new population, use a single species. IPopulation result = new BasicPopulation(PopulationSize, new DoubleArrayGenomeFactory(size)); var defaultSpecies = new BasicSpecies {Population = result}; result.Species.Add(defaultSpecies); // Create a new population of random networks. for (int i = 0; i < PopulationSize; i++) { var genome = new DoubleArrayGenome(size); network.Reset(rnd); Array.Copy(network.LongTermMemory, 0, genome.Data, 0, size); defaultSpecies.Add(genome); } // Set the genome factory to use the double array genome. result.GenomeFactory = new DoubleArrayGenomeFactory(size); return result; }
/// <inheritdoc /> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var parent = (DoubleArrayGenome) parents[parentIndex]; offspring[offspringIndex] = parent.Population.GenomeFactory.Factor(); var child = (DoubleArrayGenome) offspring[offspringIndex]; for (int i = 0; i < parent.Count; i++) { double value = parent.Data[i]; value += (perturbAmount - (rnd.NextDouble()*perturbAmount*2)); child.Data[i] = value; } }
/// <inheritdoc /> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var mother = (IntegerArrayGenome) parents[parentIndex]; var father = (IntegerArrayGenome) parents[parentIndex + 1]; var offspring1 = (IntegerArrayGenome) _owner.Population.GenomeFactory.Factor(); var offspring2 = (IntegerArrayGenome) _owner.Population.GenomeFactory.Factor(); offspring[offspringIndex] = offspring1; offspring[offspringIndex + 1] = offspring2; int geneLength = mother.Count; // the chromosome must be cut at two positions, determine them int cutpoint1 = rnd.NextInt(geneLength - _cutLength); int cutpoint2 = cutpoint1 + _cutLength; // keep track of which genes have been taken in each of the two // offspring, defaults to false. var taken1 = new HashSet<int>(); var taken2 = new HashSet<int>(); // handle cut section for (int i = 0; i < geneLength; i++) { if (!((i < cutpoint1) || (i > cutpoint2))) { offspring1.Copy(father, i, i); offspring2.Copy(mother, i, i); taken1.Add(father.Data[i]); taken2.Add(mother.Data[i]); } } // handle outer sections for (int i = 0; i < geneLength; i++) { if ((i < cutpoint1) || (i > cutpoint2)) { offspring1.Data[i] = GetNotTaken(mother, taken1); offspring2.Data[i] = GetNotTaken(father, taken2); } } }
/// <summary> /// /// </summary> /// <param name="rnd"></param> /// <param name="parent"></param> /// <param name="current"></param> /// <param name="index"></param> /// <param name="reservoir"></param> private void InternalSampleRandomNode(IGenerateRandom rnd, TreeGenomeNode parent, TreeGenomeNode current, int[] index, RandomNodeResult reservoir) { int currentIndex = index[0]; index[0]++; // determine if we replace the reservoir int j = rnd.NextInt(0, currentIndex + 1); if (j == 0) { reservoir.Parent = parent; reservoir.Child = current; } // traverse on to the children foreach (TreeGenomeNode child in current.Children) { InternalSampleRandomNode(rnd, current, child, index, reservoir); } }
/// <inheritdoc /> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var parent = (IArrayGenome) parents[parentIndex]; offspring[offspringIndex] = owner.Population.GenomeFactory.Factor(); var child = (IArrayGenome) offspring[offspringIndex]; child.Copy(parent); int length = parent.Count; var iswap1 = (int) (rnd.NextDouble()*length); var iswap2 = (int) (rnd.NextDouble()*length); // can't be equal if (iswap1 == iswap2) { // move to the next, but // don't go out of bounds if (iswap1 > 0) { iswap1--; } else { iswap1++; } } // make sure they are in the right order if (iswap1 > iswap2) { int temp = iswap1; iswap1 = iswap2; iswap2 = temp; } child.Swap(iswap1, iswap2); }
/// <inheritdoc /> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var parent1 = (TreeGenome) parents[parentIndex]; EvaluateTree eval = parent1.Evaluator; var off1 = (TreeGenome) _owner.Population.GenomeFactory.Factor(parent1); RandomNodeResult off1Point = eval.SampleRandomNode(rnd, off1.Root); int len = rnd.NextInt(1, _maxGraftLength + 1); TreeGenomeNode randomSequence = eval.Grow(rnd, len); if (off1Point.Parent == null) { off1.Root = randomSequence; } else { int idx = off1Point.Parent.Children.IndexOf(off1Point.Child); off1Point.Parent.Children[idx] = randomSequence; } offspring[0] = off1; }
/// <inheritdoc /> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var mother = (IArrayGenome) parents[parentIndex]; var father = (IArrayGenome) parents[parentIndex + 1]; var offspring1 = (IArrayGenome) _owner.Population.GenomeFactory.Factor(); var offspring2 = (IArrayGenome) _owner.Population.GenomeFactory.Factor(); offspring[offspringIndex] = offspring1; offspring[offspringIndex + 1] = offspring2; int geneLength = mother.Count; // the chromosome must be cut at two positions, determine them int cutpoint1 = rnd.NextInt(geneLength - _cutLength); int cutpoint2 = cutpoint1 + _cutLength; // handle cut section for (int i = 0; i < geneLength; i++) { if (!((i < cutpoint1) || (i > cutpoint2))) { offspring1.Copy(father, i, i); offspring2.Copy(mother, i, i); } } // handle outer sections for (int i = 0; i < geneLength; i++) { if ((i < cutpoint1) || (i > cutpoint2)) { offspring1.Copy(mother, i, i); offspring2.Copy(father, i, i); } } }
/// <inheritdoc/> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { var parent1 = (TreeGenome) parents[parentIndex]; var parent2 = (TreeGenome) parents[parentIndex]; EvaluateTree eval = parent1.Evaluator; var off1 = (TreeGenome) _owner.Population.GenomeFactory.Factor(parent1); var replacePoint = eval.SampleRandomNode(rnd, off1.Root); var copySource = eval.SampleRandomNode(rnd, parent2.Root); var actualCopy = copySource.Child.Copy(); if (replacePoint.Parent == null) { off1.Root = actualCopy; } else { var idx = replacePoint.Parent.Children.IndexOf(replacePoint.Child); replacePoint.Parent.Children[idx] = actualCopy; } offspring[0] = off1; }
/// <summary> /// The constructor. /// </summary> /// <param name="k">The number of folds.</param> /// <param name="training">The training set.</param> /// <param name="rnd">A random number generator.</param> public CrossValidate(int k, IEnumerable<BasicData> training, IGenerateRandom rnd) { IList<BasicData> temp = new List<BasicData>(); temp = temp.Union(training).ToList(); // Setup k validation sets. for (int i = 0; i < k; i++) { _folds.Add(new CrossValidateFold()); } // Divide over the k sets. int leaveOutSet = 0; while (temp.Count > 0) { int idx = rnd.NextInt(temp.Count); BasicData item = temp[idx]; temp.RemoveAt(idx); _folds[leaveOutSet].ValidationSet.Add(item); for (int includeSet = 0; includeSet < _folds.Count; includeSet++) { if (includeSet != leaveOutSet) { _folds[includeSet].TrainingSet.Add(item); } } leaveOutSet++; if (leaveOutSet >= k) { leaveOutSet = 0; } } }
/// <summary> /// Generate a random path through cities. /// </summary> /// <param name="rnd">Random number generator.</param> /// <returns>A genome.</returns> private IntegerArrayGenome RandomGenome(IGenerateRandom rnd) { var result = new IntegerArrayGenome(_cities.Length); int[] organism = result.Data; var taken = new bool[_cities.Length]; for (int i = 0; i < organism.Length - 1; i++) { int icandidate; do { icandidate = rnd.NextInt(0, organism.Length); } while (taken[icandidate]); organism[i] = icandidate; taken[icandidate] = true; if (i == organism.Length - 2) { icandidate = 0; while (taken[icandidate]) { icandidate++; } organism[i + 1] = icandidate; } } return result; }
/// <summary> /// Place the cities in random locations. /// </summary> /// <param name="rnd">Random number.</param> private void InitCities(IGenerateRandom rnd) { _cities = new City[Cities]; for (int i = 0; i < _cities.Length; i++) { int xPos = rnd.NextInt(0, MapSize); int yPos = rnd.NextInt(0, MapSize); _cities[i] = new City(xPos, yPos); } }
/// <summary> /// Generate a random choice, based on the probabilities provided to the constructor. /// </summary> /// <param name="theGenerator"></param> /// <returns>The random choice.</returns> public int Generate(IGenerateRandom theGenerator) { var r = theGenerator.NextDouble(); var sum = 0.0; for (var i = 0; i < _probabilities.Length; i++) { sum += _probabilities[i]; if (r < sum) { return i; } } for (var i = 0; i < _probabilities.Length; i++) { if (_probabilities[i] != 0.0) { return i; } } throw new AIFHError("Invalid probabilities."); }
/// <summary> /// Generate a random choice, but skip one of the choices. /// </summary> /// <param name="theGenerator">Random number generator.</param> /// <param name="skip">The choice to skip.</param> /// <returns>The random choice.</returns> public int Generate(IGenerateRandom theGenerator, int skip) { var totalProb = 1.0 - _probabilities[skip]; var throwValue = theGenerator.NextDouble()*totalProb; var accumulator = 0.0; for (var i = 0; i < skip; i++) { accumulator += _probabilities[i]; if (accumulator > throwValue) { return i; } } for (var i = skip + 1; i < _probabilities.Length; i++) { accumulator += _probabilities[i]; if (accumulator > throwValue) { return i; } } for (var i = 0; i < skip; i++) { if (_probabilities[i] != 0.0) { return i; } } for (var i = skip + 1; i < _probabilities.Length; i++) { if (_probabilities[i] != 0.0) { return i; } } return -1; }
/// <inheritdoc /> public void TrainingBatch(IGenerateRandom rnd) { throw new NotImplementedException(); }
/// <summary> /// The constructor. /// </summary> /// <param name="theAlgorithm">The algorithm to fit.</param> /// <param name="theScore">The score function.</param> /// <param name="thePopulationSize">The population size.</param> public ContinuousACO(IMLMethod theAlgorithm, IScoreFunction theScore, int thePopulationSize) { Epsilon = .75; _algorithm = theAlgorithm; _populationSize = thePopulationSize; _score = theScore; Random = new MersenneTwisterGenerateRandom(); _paramCount = theAlgorithm.LongTermMemory.Length; _population = new ContinuousAnt[thePopulationSize * 2]; _weighting = new double[thePopulationSize]; for (int i = 0; i < _population.Length; i++) { _population[i] = new ContinuousAnt(_paramCount, _score.ShouldMinimize); for (int j = 0; j < _paramCount; j++) { _population[i].Params[j] = Random.NextDouble(-1, 1); } } UpdateScore(); Array.Sort(_population); ComputeWeighting(); SampleSolutions(); Array.Sort(_population); }
/// <inheritdoc /> public override void TrainingBatch(IGenerateRandom rnd) { // nothing to do }
/// <summary> /// v = k * U(0,1) * v /// The components of the vector are multiplied /// by k and a random number. /// A new random number is generated for each /// component. /// </summary> /// <param name="rnd">Random number generator.</param> /// <param name="v">Array of doubles.</param> /// <param name="k">A scaler.</param> public static void MulRand(IGenerateRandom rnd, double[] v, double k) { for (var i = 0; i < v.Length; i++) { v[i] *= k*rnd.NextDouble(); } }
/// <inheritdoc /> public object Sample(IGenerateRandom rnd) { return _categories[rnd.NextInt(_categories.Count)]; }
/// <summary> /// v = U(0, 0.1) /// </summary> /// <param name="rnd">A random number generator.</param> /// <param name="v">an array of doubles</param> public static void Randomise(IGenerateRandom rnd, double[] v) { Randomise(rnd, v, 0.1); }
public RouletteService(ICacheMiddleware <List <Roulette> > cacheMiddleware, IGenerateRandom generateRandom) { this.cacheMiddleware = cacheMiddleware; this.generateRandom = generateRandom; this.LoadCache(); }
/// <summary> /// Construct the data division processor. /// </summary> /// <param name="theShuffle">Should we shuffle?</param> /// <param name="theRandom">Random number generator, often seeded to be consistent. </param> public PerformDataDivision(bool theShuffle, IGenerateRandom theRandom) { _shuffle = theShuffle; _rnd = theRandom; }
/// <summary> /// Create an initial random population of random paths through the cities. /// </summary> /// <param name="rnd">The random population.</param> /// <returns>The population</returns> private IPopulation InitPopulation(IGenerateRandom rnd) { IPopulation result = new BasicPopulation(PopulationSize, null); var defaultSpecies = new BasicSpecies(); defaultSpecies.Population = result; for (int i = 0; i < PopulationSize; i++) { IntegerArrayGenome genome = RandomGenome(rnd); defaultSpecies.Add(genome); } result.GenomeFactory = new IntegerArrayGenomeFactory(_cities.Length); result.Species.Add(defaultSpecies); return result; }
public RandomModelSelection() { Random = new MersenneTwisterGenerateRandom(); }
/// <inheritdoc/> public void PerformOperation(IGenerateRandom rnd, IGenome[] parents, int parentIndex, IGenome[] offspring, int offspringIndex) { IEvolutionaryOperator opp = _components.Pick(rnd); opp.PerformOperation(rnd, parents, parentIndex, offspring, offspringIndex); }
/// <summary> /// Choose a random object. /// </summary> /// <param name="theGenerator">Random number generator.</param> /// <returns>The random choice.</returns> public T Pick(IGenerateRandom theGenerator) { int index = _chooser.Generate(theGenerator); return(_list[index].Obj); }
/// <summary> /// Randomize the weights. /// </summary> /// <param name="rand">Random number generator.</param> public void Reset(IGenerateRandom rand) { for (var i = 0; i < _currentState.Length; i++) { _currentState[i] = 0; } for (var i = 0; i < _weights.Length; i++) { _weights[i] = 0; } }
/// <inheritdoc /> public object Sample(IGenerateRandom rnd) { return(rnd.NextDouble(_start, _stop)); }
/// <summary> /// v = U(-1, 1) * maxValue /// <p /> /// Randomise each component of a vector to /// [-maxValue, maxValue]. /// </summary> /// <param name="rnd">Random number generator.</param> /// <param name="v">An array of doubles.</param> /// <param name="maxValue">Maximum value +/-.</param> public static void Randomise(IGenerateRandom rnd, double[] v, double maxValue) { for (var i = 0; i < v.Length; i++) { v[i] = (2*rnd.NextDouble() - 1)*maxValue; } }
/// <summary> /// Choose a random opcode, choose between both leafs and nodes. /// </summary> /// <param name="rnd">A random number generator.</param> /// <returns>A random opcode.</returns> public int ChooseRandomOpcode(IGenerateRandom rnd) { return rnd.NextInt(0, OpcodeCount); }
/// <summary> /// The constructor. /// </summary> /// <param name="theGraph">The graph that we are seeking a minimal path through.</param> /// <param name="theAntCount">The number of ants to use.</param> public DiscreteACO(ICostGraph theGraph, int theAntCount) { Alpha = 1; Beta = 5; Evaporation = 0.5; Q = 500; PR = 0.01; Random = new MersenneTwisterGenerateRandom(); int len = theGraph.Count; _graph = theGraph; _pheromone = new double[len][]; _bestPath = new int[len]; _bestCost = double.PositiveInfinity; for (int i = 0; i < len; i++) { _pheromone[i] = new double[len]; for (int j = 0; j < len; j++) { _pheromone[i][j] = INITIAL_PHEROMONE; } } for (int i = 0; i < theAntCount; i++) { _ants.Add(new DiscreteAnt(len)); } }
/// <summary> /// Choose a random opcode, choose between only leafs. /// </summary> /// <param name="rnd">A random number generator.</param> /// <returns>A random opcode.</returns> public int ChooseRandomLeafOpcode(IGenerateRandom rnd) { return VarConstOpcode + rnd.NextInt(NumVar + NumConst); }
/// <summary> /// Choose a random opcode, choose between only nodes. /// </summary> /// <param name="rnd">A random number generator.</param> /// <returns>A random opcode.</returns> public int ChooseRandomNodeOpcode(IGenerateRandom rnd) { return rnd.NextInt(VarConstOpcode); }
/// <summary> /// Grow the tree randomly by the specified max depth. /// </summary> /// <param name="rnd">A random number generator.</param> /// <param name="maxDepth">The max depth.</param> /// <returns>The tree.</returns> public TreeGenomeNode Grow(IGenerateRandom rnd, int maxDepth) { if (maxDepth == 1) { return new TreeGenomeNode(ChooseRandomLeafOpcode(rnd)); } var result = new TreeGenomeNode(ChooseRandomNodeOpcode(rnd)); int childCount = DetermineChildCount(result.Opcode); for (int i = 0; i < childCount; i++) { result.Children.Add(Grow(rnd, maxDepth - 1)); } return result; }
/// <inheritdoc /> public object Sample(IGenerateRandom rnd) { return rnd.NextDouble(_start, _stop); }
/** * Construct an evaluator with 1 variable, and 100 constants ranging between (-5,5) * * @param rnd A random number generator. */ public EvaluateExpression(IGenerateRandom rnd) : this(rnd, 100, 1, -5, 5) { }