Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace random.random with np.random.choice in selRoulette #689

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 9 additions & 13 deletions deap/tools/selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,26 +78,22 @@ def selRoulette(individuals, k, fit_attr="fitness"):
:param fit_attr: The attribute of individuals to use as selection criterion
:returns: A list of selected individuals.

This function uses the :func:`~random.random` function from the python base
This function uses the :func:`~random.choices` function from the python base
:mod:`random` module.

.. warning::
The roulette selection by definition cannot be used for minimization
or when the fitness can be smaller or equal to 0.
"""

s_inds = sorted(individuals, key=attrgetter(fit_attr), reverse=True)
sum_fits = sum(getattr(ind, fit_attr).values[0] for ind in individuals)
chosen = []
for i in range(k):
u = random.random() * sum_fits
sum_ = 0
for ind in s_inds:
sum_ += getattr(ind, fit_attr).values[0]
if sum_ > u:
chosen.append(ind)
break

fits = [getattr(ind,fit_attr).values[0] for ind in individuals]
sum_fits = sum(fits)
if sum_fits == 0:
# If all individuals have zero fitness, evenly distribute probability of selection
fitness_proportions = [1/k for i in fits]
else: fitness_proportions = [i/sum_fits for i in fits]

chosen = random.choices(individuals, weights=fitness_proportions, k=k)
return chosen


Expand Down