Last active
March 12, 2024 16:59
-
-
Save pablormier/0caff10a5f76e87857b44f63757729b0 to your computer and use it in GitHub Desktop.
Small and efficient implementation of the Differential Evolution algorithm using the rand/1/bin schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def de(fobj, bounds, mut=0.8, crossp=0.7, popsize=20, its=1000): | |
dimensions = len(bounds) | |
pop = np.random.rand(popsize, dimensions) | |
min_b, max_b = np.asarray(bounds).T | |
diff = np.fabs(min_b - max_b) | |
pop_denorm = min_b + pop * diff | |
fitness = np.asarray([fobj(ind) for ind in pop_denorm]) | |
best_idx = np.argmin(fitness) | |
best = pop_denorm[best_idx] | |
for i in range(its): | |
for j in range(popsize): | |
idxs = [idx for idx in range(popsize) if idx != j] | |
a, b, c = pop[np.random.choice(idxs, 3, replace = False)] | |
mutant = np.clip(a + mut * (b - c), 0, 1) | |
cross_points = np.random.rand(dimensions) < crossp | |
if not np.any(cross_points): | |
cross_points[np.random.randint(0, dimensions)] = True | |
trial = np.where(cross_points, mutant, pop[j]) | |
trial_denorm = min_b + trial * diff | |
f = fobj(trial_denorm) | |
if f < fitness[j]: | |
fitness[j] = f | |
pop[j] = trial | |
if f < fitness[best_idx]: | |
best_idx = j | |
best = trial_denorm | |
yield best, fitness[best_idx] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi how should I change the code to get best/1/bin