Exemplo n.º 1
0
 private void Awake()
 {
     car           = GetComponent <CarControllerV2>();
     startPosition = transform.position;
     startRotation = transform.rotation.eulerAngles;
     network       = new NNet();
     network.Initialize(neurons, layers);
 }
Exemplo n.º 2
0
    private void Crossover(NNet[] newPopulation)
    {
        for (int i = 0; i < numberToCrossover; i += 2)
        {
            // These are indexes of the parents.
            int indexA = i;
            int indexB = i + 1;

            if (genePool.Count >= 1)
            {
                // We need to ensure that these are not the same.
                // Because if two parents are the same, we're not gonna get a new child.
                indexA = genePool[Random.Range(0, genePool.Count)];
                do
                {
                    indexB = genePool[Random.Range(0, genePool.Count)];
                }while (indexA == indexB);
            }

            NNet child1 = new NNet();
            NNet child2 = new NNet();

            child1.Initialize(carBrain.layers, carBrain.neurons);
            child2.Initialize(carBrain.layers, carBrain.neurons);

            child1.fitness = 0;
            child2.fitness = 0;

            for (int w = 0; w < child1.weights.Count; w++)
            {
                if (Random.Range(0f, 1f) < 0.5f)
                {
                    child1.weights[w] = population[indexA].weights[w];
                    child2.weights[w] = population[indexB].weights[w];
                }
                else
                {
                    child1.weights[w] = population[indexB].weights[w];
                    child2.weights[w] = population[indexA].weights[w];
                }
            }

            for (int b = 0; b < child1.biases.Count; b++)
            {
                if (Random.Range(0f, 1f) < 0.5f)
                {
                    child1.biases[b] = population[indexA].biases[b];
                    child2.biases[b] = population[indexB].biases[b];
                }
                else
                {
                    child1.biases[b] = population[indexB].biases[b];
                    child2.biases[b] = population[indexA].biases[b];
                }
            }

            newPopulation[naturallySelected] = child1;
            naturallySelected++;

            newPopulation[naturallySelected] = child2;
            naturallySelected++;
        }
    }