Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
sherstpasha committed Sep 3, 2023
1 parent 43e1a0f commit 7062548
Show file tree
Hide file tree
Showing 4 changed files with 359 additions and 47 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[flake8]
exclude = .git,__pycache__,env
max-line-length = 100
max-complexity = 8
max-complexity = 12
ignore = N803,N806,N802,N801

[mypy]
Expand Down
59 changes: 34 additions & 25 deletions src/thefittest/optimizers/_sade2005.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
from functools import partial
from typing import Callable
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Dict


import numpy as np

from ._differentialevolution import DifferentialEvolution
from ..tools import donothing
from ..tools.operators import binomial
from ..tools.operators import rand_1
from ..tools.operators import current_to_best_1
from ..tools.transformations import numpy_group_by
from ..tools.operators import rand_1
from ..tools.random import float_population
from ..tools.transformations import bounds_control
from ..tools.transformations import numpy_group_by


class SaDE2005(DifferentialEvolution):
Expand All @@ -20,11 +24,11 @@ class SaDE2005(DifferentialEvolution):

def __init__(self,
fitness_function: Callable,
genotype_to_phenotype: Callable,
iters: int,
pop_size: int,
left: np.ndarray,
right: np.ndarray,
genotype_to_phenotype: Callable = donothing,
optimal_value: Optional[float] = None,
termination_error_value: float = 0.,
no_increase_num: Optional[int] = None,
Expand All @@ -34,27 +38,26 @@ def __init__(self,
DifferentialEvolution.__init__(
self,
fitness_function=fitness_function,
genotype_to_phenotype=genotype_to_phenotype,
iters=iters,
pop_size=pop_size,
left=left,
right=right,
genotype_to_phenotype=genotype_to_phenotype,
optimal_value=optimal_value,
termination_error_value=termination_error_value,
no_increase_num=no_increase_num,
minimization=minimization,
show_progress_each=show_progress_each,
keep_history=keep_history)

# self.m_sets_keys = list(self.m_sets.keys())
self._m_learning_period: int
self._CR_update_timer: int
self._CR_m_learning_period: int
self._threshold: int

self._Fm = 0.5
self._F_sigma = 0.3
self._CR_sigma = 0.1
self._Fm: float
self._F_sigma: float
self._CR_sigma: float

self.set_strategy()

Expand Down Expand Up @@ -107,12 +110,11 @@ def _update_ns_nf(self,

def _update_proba(self,
ns_i: Dict,
nf_i: Dict) -> Dict:
up = ns_i['rand_1']*(ns_i['current_to_best_1'] +
nf_i['current_to_best_1'])
down = ns_i['current_to_best_1']*(ns_i['rand_1'] + nf_i['rand_1']) + up
nf_i: Dict) -> Dict:
up = ns_i['rand_1'] * (ns_i['current_to_best_1'] + nf_i['current_to_best_1'])
down = ns_i['current_to_best_1'] * (ns_i['rand_1'] + nf_i['rand_1']) + up

p1 = up/down
p1 = up / down
new_m_proba = {'rand_1': p1, 'current_to_best_1': 1 - p1}
return new_m_proba

Expand Down Expand Up @@ -153,28 +155,29 @@ def fit(self):
population_g = float_population(
self._pop_size, self._left, self._right)
else:
population_g = self._initial_population
population_g = self._initial_population.copy()

z_mutation = len(self._mutation_pool)
m_proba = dict(zip(self._mutation_pool.keys(),
np.full(z_mutation, 1/z_mutation)))
np.full(z_mutation, 1 / z_mutation)))
CRm = 0.5
CR_i = self._generate_CR(CRm)

population_ph = self._get_phenotype(population_g)
fitness = self._evaluate(population_ph)
fitness = self._get_fitness(population_ph)

ns = dict(zip(self._mutation_pool.keys(),
np.zeros(z_mutation, dtype=int)))
nf = dict(zip(self._mutation_pool.keys(),
np.zeros(z_mutation, dtype=int)))
CR_s_pool = np.array([], dtype=float)
for i in range(self._iters-1):
self._update_fittest(population_g, population_ph, fitness)
self._update_stats({'population_g': population_g,
'fitness_max': self._thefittest._fitness,
'm_proba': m_proba.copy(),
'CRm': CRm})
self._update_fittest(population_g, population_ph, fitness)
self._update_stats(population_g=population_g,
fitness_max=self._thefittest._fitness,
m_proba=m_proba,
CRm=CRm)
for i in range(self._iters - 1):

self._show_progress(i)
if self._termitation_check():
break
Expand All @@ -184,7 +187,7 @@ def fit(self):
mutation_and_crossover = partial(self._mutation_and_crossover,
population_g)
mutant_cr_g = np.array(list(map(mutation_and_crossover,
population_g, m_operators, CR_i)))
population_g, m_operators, CR_i)))

stack = self._evaluate_and_selection(mutant_cr_g,
population_g,
Expand All @@ -194,7 +197,8 @@ def fit(self):
population_g, population_ph, fitness, succeses = stack

if self._elitism:
population_g[-1], population_ph[-1], fitness[-1] = self._thefittest.get()
population_g[-1], population_ph[-1], fitness[-1] =\
self._thefittest.get().values()

ns, nf = self._update_ns_nf(m_operators, succeses, ns, nf)
CR_s_pool = np.append(CR_s_pool, CR_i[succeses])
Expand All @@ -212,4 +216,9 @@ def fit(self):
if len(CR_s_pool):
CRm = np.mean(CR_s_pool)
CR_s_pool = np.array([], dtype=float)
self._update_fittest(population_g, population_ph, fitness)
self._update_stats(population_g=population_g,
fitness_max=self._thefittest._fitness,
m_proba=m_proba,
CRm=CRm)
return self
46 changes: 25 additions & 21 deletions src/thefittest/optimizers/_selfcga.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
from functools import partial
from typing import Callable
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Dict

import numpy as np

from ._geneticalgorithm import GeneticAlgorithm
from ..tools.transformations import scale_data
from ..tools.transformations import rank_data
from ..tools.transformations import numpy_group_by
from ..tools import donothing
from ..tools.random import binary_string_population
from ..tools.transformations import numpy_group_by
from ..tools.transformations import rank_data
from ..tools.transformations import scale_data


class SelfCGA(GeneticAlgorithm):
def __init__(self,
fitness_function: Callable,
genotype_to_phenotype: Callable,
iters: int,
pop_size: int,
str_len: int,
genotype_to_phenotype: Callable = donothing,
optimal_value: Optional[float] = None,
termination_error_value: float = 0.,
no_increase_num: Optional[int] = None,
Expand All @@ -27,10 +30,10 @@ def __init__(self,
GeneticAlgorithm.__init__(
self,
fitness_function=fitness_function,
genotype_to_phenotype=genotype_to_phenotype,
iters=iters,
pop_size=pop_size,
str_len=str_len,
genotype_to_phenotype=genotype_to_phenotype,
optimal_value=optimal_value,
termination_error_value=termination_error_value,
no_increase_num=no_increase_num,
Expand Down Expand Up @@ -75,11 +78,11 @@ def _choice_operators(self,
def _update_proba(self,
proba_dict: Dict,
operator: str) -> Dict:
proba_dict[operator] += self._K/self._iters
proba_dict[operator] += self._K / self._iters
proba_value = np.array(list(proba_dict.values()))
proba_value -= self._K/(len(proba_dict)*self._iters)
proba_value -= self._K / (len(proba_dict) * self._iters)
proba_value = proba_value.clip(self._threshold, 1)
proba_value = proba_value/proba_value.sum()
proba_value = proba_value / proba_value.sum()
new_proba_dict = dict(zip(proba_dict.keys(), proba_value))
return new_proba_dict

Expand Down Expand Up @@ -163,35 +166,36 @@ def fit(self):
z_mutation = len(self._mutation_set)

s_proba = dict(zip(list(self._selection_set.keys()),
np.full(z_selection, 1/z_selection)))
np.full(z_selection, 1 / z_selection)))
if 'empty' in self._crossover_set.keys():
c_proba = dict(zip(list(self._crossover_set.keys()),
np.full(z_crossover, 0.9/(z_crossover-1))))
np.full(z_crossover, 0.9 / (z_crossover - 1))))
c_proba['empty'] = 0.1
else:
c_proba = dict(zip(list(self._crossover_set.keys()),
np.full(z_crossover, 1/z_crossover)))
np.full(z_crossover, 1 / z_crossover)))
m_proba = dict(zip(list(self._mutation_set.keys()),
np.full(z_mutation, 1/z_mutation)))
np.full(z_mutation, 1 / z_mutation)))

if self._initial_population is None:
population_g = binary_string_population(
self._pop_size, self._str_len)
else:
population_g = self._initial_population
population_g = self._initial_population.copy()

for i in range(self._iters):
population_ph = self._get_phenotype(population_g)
fitness = self._evaluate(population_ph)
fitness = self._get_fitness(population_ph)

self._update_fittest(population_g, population_ph, fitness)
self._update_stats({'population_g': population_g.copy(),
'fitness_max': self._thefittest._fitness,
's_proba': s_proba.copy(),
'c_proba': c_proba.copy(),
'm_proba': m_proba.copy()})
self._update_stats(population_g=population_g,
fitness_max=self._thefittest._fitness,
s_proba=s_proba,
c_proba=c_proba,
m_proba=m_proba)
if self._elitism:
population_g[-1], population_ph[-1], fitness[-1] = self._thefittest.get()
population_g[-1], population_ph[-1], fitness[-1] =\
self._thefittest.get().values()
fitness_scale = scale_data(fitness)

if i > 0:
Expand Down
Loading

0 comments on commit 7062548

Please sign in to comment.