eckity.genetic_operators.selections.tournament_selection

 1import random
 2from typing import List
 3
 4from overrides import override
 5
 6from eckity.genetic_operators.selections.selection_method import (
 7    SelectionMethod,
 8)
 9from eckity.individual import Individual
10
11
12class TournamentSelection(SelectionMethod):
13    def __init__(
14        self,
15        tournament_size,
16        replace=True,
17        events=None,
18    ):
19        """
20        Tournament Selection method.
21        In this method, small groups (known as tournaments) are created from
22        randomly chosen individuals. The individual(s) with the best fitness
23        scores are selected to reproduce the next generation.
24
25        Parameters
26        ----------
27        tournament_size : int
28            Size of each tournament.
29            larger tournaments focus on exploitation,
30            while small tournaments focus on exploration.
31        replace : bool, optional
32            whether tournaments can contain multiple copies of the same
33            individual, by default False
34        events : List[str], optional
35            selection events, by default None
36        """
37        super().__init__(events=events)
38        self.tournament_size = tournament_size
39        self.replace = replace
40
41    @override
42    def select(
43        self, source_inds: List[Individual], dest_inds: List[Individual]
44    ) -> List[Individual]:
45        if not self.replace and len(source_inds) < self.tournament_size:
46            raise ValueError(
47                f"""Tournament size must be greater or equal to
48                            the number of individuals to be selected from.
49                             Tournament size={self.tournament_size},
50                             number of individuals: {len(source_inds)}"""
51            )
52
53        # The selection should add len(source_inds) individuals to dest_inds,
54        # so the required number of tournaments is the size of source
55        # individuals divided by the number of winners per tournament.
56        # `n_tournaments = len(source_inds) // self.operator_arity`
57        n_tournaments = (len(source_inds) - len(dest_inds)) // self.arity
58
59        # Select the appropriate tournament creation function.
60        # `random.choices` selects k elements with replacements,
61        # `random.sample` selects k unique elements.
62        sel_func = random.choices if self.replace else random.sample
63
64        # create all tournaments beforehand
65        tournaments = [
66            sel_func(source_inds, k=self.tournament_size)
67            for _ in range(n_tournaments)
68        ]
69
70        # pick the winner of each tournament and add all winners to dest_inds
71        winners = [self._pick_tournament_winner(tour) for tour in tournaments]
72        dest_inds.extend(winners)
73
74        self.selected_individuals = dest_inds
75
76        return dest_inds
77
78    def _pick_tournament_winner(self, tournament):
79        winner = tournament[0]
80        for participant in tournament[1:]:
81            if participant.better_than(winner):
82                winner = participant
83        result = winner.clone()
84        result.selected_by.append(type(self).__name__)
85        return result
13class TournamentSelection(SelectionMethod):
14    def __init__(
15        self,
16        tournament_size,
17        replace=True,
18        events=None,
19    ):
20        """
21        Tournament Selection method.
22        In this method, small groups (known as tournaments) are created from
23        randomly chosen individuals. The individual(s) with the best fitness
24        scores are selected to reproduce the next generation.
25
26        Parameters
27        ----------
28        tournament_size : int
29            Size of each tournament.
30            larger tournaments focus on exploitation,
31            while small tournaments focus on exploration.
32        replace : bool, optional
33            whether tournaments can contain multiple copies of the same
34            individual, by default False
35        events : List[str], optional
36            selection events, by default None
37        """
38        super().__init__(events=events)
39        self.tournament_size = tournament_size
40        self.replace = replace
41
42    @override
43    def select(
44        self, source_inds: List[Individual], dest_inds: List[Individual]
45    ) -> List[Individual]:
46        if not self.replace and len(source_inds) < self.tournament_size:
47            raise ValueError(
48                f"""Tournament size must be greater or equal to
49                            the number of individuals to be selected from.
50                             Tournament size={self.tournament_size},
51                             number of individuals: {len(source_inds)}"""
52            )
53
54        # The selection should add len(source_inds) individuals to dest_inds,
55        # so the required number of tournaments is the size of source
56        # individuals divided by the number of winners per tournament.
57        # `n_tournaments = len(source_inds) // self.operator_arity`
58        n_tournaments = (len(source_inds) - len(dest_inds)) // self.arity
59
60        # Select the appropriate tournament creation function.
61        # `random.choices` selects k elements with replacements,
62        # `random.sample` selects k unique elements.
63        sel_func = random.choices if self.replace else random.sample
64
65        # create all tournaments beforehand
66        tournaments = [
67            sel_func(source_inds, k=self.tournament_size)
68            for _ in range(n_tournaments)
69        ]
70
71        # pick the winner of each tournament and add all winners to dest_inds
72        winners = [self._pick_tournament_winner(tour) for tour in tournaments]
73        dest_inds.extend(winners)
74
75        self.selected_individuals = dest_inds
76
77        return dest_inds
78
79    def _pick_tournament_winner(self, tournament):
80        winner = tournament[0]
81        for participant in tournament[1:]:
82            if participant.better_than(winner):
83                winner = participant
84        result = winner.clone()
85        result.selected_by.append(type(self).__name__)
86        return result

Helper class that provides a standard way to create an ABC using inheritance.

TournamentSelection(tournament_size, replace=True, events=None)
14    def __init__(
15        self,
16        tournament_size,
17        replace=True,
18        events=None,
19    ):
20        """
21        Tournament Selection method.
22        In this method, small groups (known as tournaments) are created from
23        randomly chosen individuals. The individual(s) with the best fitness
24        scores are selected to reproduce the next generation.
25
26        Parameters
27        ----------
28        tournament_size : int
29            Size of each tournament.
30            larger tournaments focus on exploitation,
31            while small tournaments focus on exploration.
32        replace : bool, optional
33            whether tournaments can contain multiple copies of the same
34            individual, by default False
35        events : List[str], optional
36            selection events, by default None
37        """
38        super().__init__(events=events)
39        self.tournament_size = tournament_size
40        self.replace = replace

Tournament Selection method. In this method, small groups (known as tournaments) are created from randomly chosen individuals. The individual(s) with the best fitness scores are selected to reproduce the next generation.

Parameters
  • tournament_size (int): Size of each tournament. larger tournaments focus on exploitation, while small tournaments focus on exploration.
  • replace (bool, optional): whether tournaments can contain multiple copies of the same individual, by default False
  • events (List[str], optional): selection events, by default None
tournament_size
replace
@override
def select( self, source_inds: List[eckity.individual.Individual], dest_inds: List[eckity.individual.Individual]) -> List[eckity.individual.Individual]:
42    @override
43    def select(
44        self, source_inds: List[Individual], dest_inds: List[Individual]
45    ) -> List[Individual]:
46        if not self.replace and len(source_inds) < self.tournament_size:
47            raise ValueError(
48                f"""Tournament size must be greater or equal to
49                            the number of individuals to be selected from.
50                             Tournament size={self.tournament_size},
51                             number of individuals: {len(source_inds)}"""
52            )
53
54        # The selection should add len(source_inds) individuals to dest_inds,
55        # so the required number of tournaments is the size of source
56        # individuals divided by the number of winners per tournament.
57        # `n_tournaments = len(source_inds) // self.operator_arity`
58        n_tournaments = (len(source_inds) - len(dest_inds)) // self.arity
59
60        # Select the appropriate tournament creation function.
61        # `random.choices` selects k elements with replacements,
62        # `random.sample` selects k unique elements.
63        sel_func = random.choices if self.replace else random.sample
64
65        # create all tournaments beforehand
66        tournaments = [
67            sel_func(source_inds, k=self.tournament_size)
68            for _ in range(n_tournaments)
69        ]
70
71        # pick the winner of each tournament and add all winners to dest_inds
72        winners = [self._pick_tournament_winner(tour) for tour in tournaments]
73        dest_inds.extend(winners)
74
75        self.selected_individuals = dest_inds
76
77        return dest_inds