public FullyConnectedNeuralNetworkModel[] CreateNextGeneration(FullyConnectedNeuralNetworkModel[] parents, int populationSize) { var children = new FullyConnectedNeuralNetworkModel[populationSize - parents.Length]; var indexesBred = new ConcurrentDictionary <int, List <int> >(); Parallel.For(0, children.Length, childIndex => { var motherIndex = 0; var fatherIndex = 0; var motherHasChildren = false; while (motherIndex == fatherIndex || motherHasChildren && indexesBred[motherIndex].Contains(fatherIndex)) { var parentIndexes = new[] { random.Next(parents.Length), random.Next(parents.Length) }.OrderBy(i => i); motherIndex = parentIndexes.ElementAt(0); fatherIndex = parentIndexes.ElementAt(1); motherHasChildren = indexesBred.ContainsKey(motherIndex); } children[childIndex] = modelBreeder.Breed(parents[motherIndex], parents[fatherIndex]); indexesBred.AddOrUpdate(motherIndex, new List <int>() { fatherIndex }, (key, value) => { value.Add(fatherIndex); return(value); }); }); return(children); }
public FullyConnectedNeuralNetworkModel[] CreateNextGeneration(FullyConnectedNeuralNetworkModel[] parents, int populationSize) { var children = new List <FullyConnectedNeuralNetworkModel>(); var remainingParentIndexes = Enumerable.Range(0, parents.Length).ToList(); while (children.Count < populationSize - parents.Length) { var randomRemainingParentIndex = random.Next(1, remainingParentIndexes.Count); var motherIndex = remainingParentIndexes[0]; var fatherIndex = remainingParentIndexes[randomRemainingParentIndex]; var child = modelBreeder.Breed(parents[motherIndex], parents[fatherIndex]); children.Add(child); remainingParentIndexes.Remove(motherIndex); remainingParentIndexes.Remove(fatherIndex); } return(children.ToArray()); }