# How does crossover work in a genetic algorithm?

If I had the weights of a certain number of "parents" that I wanted to crossbreed, and I used whatever method to pick out the "best parents" (I used a roulette wheel option, if that's any relevant), would I be doing this correctly?

For example, suppose I have picked the following two parents.

\begin{align} P_1 &= [0.5, -0.02, 0.4, 0.1, -0.9] \\ P_2 &= [0.42, 0.55, 0.18, -0.3, 0.12] \end{align}

When I'm iterating through each index (or gene) of the parents, I am selecting a weight from one parent only. I called this rate the "cross-rate", which in my case is $$0.2$$ (i.e. with $$20$$% chance, I will switch to choosing the other parents' weight).

So, using our example above, this is what would happen:

\begin{align} P_1 &=[\mathbf{0.5}, \mathbf{-0.02}, 0.4, 0.1, \mathbf{-0.9}] \\ P_2 &= [0.42, 0.55, \mathbf{0.18}, \mathbf{-0.3}, 0.12] \end{align}

So the child would be

$$C = [0.5, -0.02, 0.18, -0.3, -0.9]$$

I would choose $$0.5$$ from $$P_1$$, but for every time I choose a weight from $$P_1$$, there's a 20% chance that I actually choose the corresponding gene from $$P_2$$. But, for the first weight, I end up not landing on that 20% chance. So I move onto the second weight, $$-0.02$$. This time, we hit the 20% chance, so now we swap over. Our next weight is now from $$P_2$$, which is $$0.18$$. And so on, until we hit another 20% chance.

We keep doing this until we hit the end of the indexes ($$P_1$$ and $$P_2$$ have the same number of indexes, of course).

Is this the correct way to form a child from 2 parents? Is this the correct "crossbreeding" method when it comes to genetic algorithms?

As far as I know, there isn't a "specified correct way". The whole idea is that you want the population to converge and increase the sample rate in that more optimal looking place. What works best all depends upon your fitness landscape.

You could also crossover by doing something like

crossover_point = random_number_size_genome
child[:] = parent_a[:crossover_point] + parent_b[crossover_point:]


Or have multiple points of crossover or more exotic types of crossover. As far as I know, the impact on your algorithm because of the different crossover algorithms shouldn't be that different.

Fitness function and how you select the fittest has a way bigger impact. You have understood the crossover step correctly, looking at your example.