Created
April 23, 2019 12:52
-
-
Save ahmedfgad/623f457708f3f1ad36367e82642cc24b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def crossover(parents, img_shape, n_individuals=8): | |
| new_population = numpy.empty(shape=(n_individuals, functools.reduce(operator.mul, img_shape)), dtype=numpy.uint8) | |
| #Previous parents (best elements). | |
| new_population[0:parents.shape[0], :] = parents | |
| # Getting how many offspring to be generated. If the population size is 8 and number of parents mating is 4, then number of offspring to be generated is 4. | |
| num_newly_generated = n_individuals-parents.shape[0] | |
| # Getting all possible permutations of the selected parents. | |
| parents_permutations = list(itertools.permutations(iterable=numpy.arange(0, parents.shape[0]), r=2)) | |
| # Randomly selecting the parents permutations to generate the offspring. | |
| selected_permutations = random.sample(range(len(parents_permutations)), | |
| num_newly_generated) | |
| comb_idx = parents.shape[0] | |
| for comb in range(len(selected_permutations)): | |
| # Generating the offspring using the permutations previously selected randmly. | |
| selected_comb_idx = selected_permutations[comb] | |
| selected_comb = parents_permutations[selected_comb_idx] | |
| # Applying crossover by exchanging half of the genes between two parents. | |
| half_size = numpy.int32(new_population.shape[1]/2) | |
| new_population[comb_idx+comb, 0:half_size] = parents[selected_comb[0], | |
| 0:half_size] | |
| new_population[comb_idx+comb, half_size:] = parents[selected_comb[1], | |
| half_size:] | |
| return new_population |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment