Last active
July 25, 2023 21:16
-
-
Save gdetor/9f8d1fe6bf00cde62261f588983af859 to your computer and use it in GitHub Desktop.
A minimal evolutionary computing algorithm
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 | |
import matplotlib.pylab as plt | |
def f(x): | |
return 50 - x**2 | |
if __name__ == '__main__': | |
np.random.seed(12345) | |
PI = np.sqrt(2 / np.pi) | |
M = 10 # population size | |
pop = np.random.uniform(-100, 100, (M, 1)) | |
print(pop) | |
print("===============") | |
delta = 1.0 | |
fit = f(pop) | |
births = 0 | |
for g in range(10000): | |
parent = pop[np.random.randint(0, M)] | |
offspring = parent.copy() | |
# offspring += np.random.choice(np.array([-delta, delta])) | |
offspring += np.random.normal(0, delta / PI, (1,)) | |
births += 1 | |
die = np.random.randint(0, M) | |
if f(pop[die]) < f(offspring): | |
pop[die] = offspring.copy() | |
if births % 10 == 0: | |
print(f(pop)) | |
print(pop) | |
births = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment