{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "b4461ad9-e7cd-489e-9e6f-0f8c55a1a87a", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "def tournament_selection(population, fitnesses, tournament_size=3):\n", " \"\"\"\n", " This function takes the entire current population, randomly selects \n", " tournament_size (default=3) chromosomes from the population as candidate \n", " parents and returns the candidate with the highest fitness.\n", " \n", " :param population: current population \n", " :param fitnesses: array of fitnesses for all chromosomes in the current population.\n", " :param tournament_size: number of candidate solutions to compare based on their fitness.\n", " :return: chosen_parents[min_fitness_idx]: the single parent candidate with the highest fitness.\n", " \"\"\"\n", "\n", " indices_list = np.random.choice(len(population), tournament_size, replace=False)\n", " \n", " chosen_parents = np.array([population[i] for i in indices_list])\n", "\n", " parent_fitnesses = np.array([fitnesses[i] for i in indices_list])\n", "\n", " min_fitness_idx = np.argmin(parent_fitnesses)\n", "\n", " return chosen_parents[min_fitness_idx]" ] } ], "metadata": { "kernelspec": { "display_name": "Python", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }