Challenge: Build a Genetic Algorithm
Swipe to start coding
You are tasked with implementing the main loop of a genetic algorithm to find the maximum value of a mathematical function. The function to optimize is a simple parabola: f(x) = -(x - 3)² + 10. This function has a clear peak at x = 3, where its value is 10.
All the helper functions (init_population, fitness_function, tournament_selection, arithmetic_crossover, mutate) and the main loop structure are provided for you.
Your task is to fill in the core logic of the evolutionary process:
- Inside the main
forloop, you must first evaluate the entirepopulationby applying thefitness_functionto each individual. Store these scores in thefitnesslist. - Find the index of the best-performing individual in the current generation and store it in
gen_best_idx. (Hint:np.argmax()is useful here). - Inside the
while len(new_population) < POP_SIZE:loop, you must create a new individual by:- Selecting
parent1using thetournament_selectionfunction. - Selecting
parent2using thetournament_selectionfunction. - Creating a
childby combining the parents with thearithmetic_crossoverfunction. - Applying variation to the
childusing themutatefunction.
- Selecting
- After the
whileloop, replace the oldpopulationwith thenew_populationto complete the generation.
Solução
Obrigado pelo seu feedback!
single
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Awesome!
Completion rate improved to 6.25
Challenge: Build a Genetic Algorithm
Deslize para mostrar o menu
Swipe to start coding
You are tasked with implementing the main loop of a genetic algorithm to find the maximum value of a mathematical function. The function to optimize is a simple parabola: f(x) = -(x - 3)² + 10. This function has a clear peak at x = 3, where its value is 10.
All the helper functions (init_population, fitness_function, tournament_selection, arithmetic_crossover, mutate) and the main loop structure are provided for you.
Your task is to fill in the core logic of the evolutionary process:
- Inside the main
forloop, you must first evaluate the entirepopulationby applying thefitness_functionto each individual. Store these scores in thefitnesslist. - Find the index of the best-performing individual in the current generation and store it in
gen_best_idx. (Hint:np.argmax()is useful here). - Inside the
while len(new_population) < POP_SIZE:loop, you must create a new individual by:- Selecting
parent1using thetournament_selectionfunction. - Selecting
parent2using thetournament_selectionfunction. - Creating a
childby combining the parents with thearithmetic_crossoverfunction. - Applying variation to the
childusing themutatefunction.
- Selecting
- After the
whileloop, replace the oldpopulationwith thenew_populationto complete the generation.
Solução
Obrigado pelo seu feedback!
single