public void Evolve() { List <NeuralNetwork> allNewNetworks = new List <NeuralNetwork>(); List <NeuralNetwork> networkList = networks.Select(kvp => kvp.Value).ToList(); networkList.Sort((t1, t2) => { return(-fitnesses[t1.GetGuid()].CompareTo(fitnesses[t2.GetGuid()])); }); List <NeuralNetwork> best10 = networkList.Take((int)(networkList.Count * 0.1)).ToList(); List <double> fitness = networkList.Select(n => fitnesses[n.GetGuid()]).ToList(); allNewNetworks.AddRange(networkList.Take(5).Select(n => n)); double[] mutationParams = mutationFunction(maxFitness); allNewNetworks.AddRange(best10.SelectMany(n => n.Mutate(mutationParams[0], mutationParams[1], 4))); while (allNewNetworks.Count < networkList.Count * 0.75) { NeuralNetwork n1 = networkList[RandomValues.RandomInt(0, networkList.Count - 1)]; NeuralNetwork n2 = networkList[RandomValues.RandomInt(0, networkList.Count - 1)]; if (n1.WantsSexyTimeWith(n2) && n2.WantsSexyTimeWith(n1)) { allNewNetworks.Add(n1.DoSexyTimeWith(n2)); } } while (allNewNetworks.Count < networkList.Count) { int[] layers = new int[RandomValues.RandomInt(layerLength.Item1, layerLength.Item2)]; for (int i = 0; i < layers.Length; i++) { layers[i] = RandomValues.RandomInt(layerRange.Item1, layerRange.Item2); } layers[0] = inputs; layers[layers.Length - 1] = outputs; NeuralNetwork network = new NeuralNetwork(layers, activationFunction); allNewNetworks.Add(network); } networks.Clear(); fitnesses.Clear(); foreach (NeuralNetwork network in allNewNetworks) { networks.Add(network.GetGuid(), network); } generation++; }
public void Init() { for (int pop = 0; pop < netPopulations; pop++) { int[] layers = new int[RandomValues.RandomInt(layerLength.Item1, layerLength.Item2)]; for (int i = 0; i < layers.Length; i++) { layers[i] = RandomValues.RandomInt(layerRange.Item1, layerRange.Item2); } layers[0] = inputs; layers[layers.Length - 1] = outputs; for (int net = 0; net < netsPerPopulation; net++) { NeuralNetwork network = new NeuralNetwork(layers, activationFunction); networks.Add(network.Guid, network); } } }