Skip to content

Instantly share code, notes, and snippets.

@fedden
Created December 13, 2017 15:37
Show Gist options
  • Save fedden/821649596801759254f891b131847740 to your computer and use it in GitHub Desktop.
Save fedden/821649596801759254f891b131847740 to your computer and use it in GitHub Desktop.
def naive_dfo(solution_size=5, population_size=1000000, iteration_count=100):
size = population_size
disturbance_threshold = 0.01
target_solution = np.zeros((solution_size,))
lower = -1.0
upper = 1.0
population = np.array([np.random.uniform(lower, upper, solution_size)
for _ in range(size)])
all_time_best = None
all_time_best_score = np.finfo(np.float32).max
best_neighbour = np.zeros_like(population[0])
iteration_amount = 100
for _ in range(iteration_count):
fitnesses = np.zeros(len(population))
for i in range(len(population)):
fitnesses[i] = np.linalg.norm(target_solution - population[i])
swarms_best_index = np.argmin(fitnesses)
swarms_best = population[swarms_best_index]
if np.amin(fitnesses) <= all_time_best_score:
all_time_best_score = np.amin(fitnesses)
all_time_best = swarms_best
r = np.random.uniform(0.0, 1.0, population.shape)
for i, p in enumerate(population):
left = i - 1
right = i + 1
if i == 0:
left = len(population) - 1
if i == (len(population) - 1):
right = 0
best_neighbour = population[left] if fitnesses[left] < fitnesses[right] else population[right]
for x in range(len(p)):
if r[i][x] < disturbance_threshold:
p[x] = np.random.uniform(lower, upper)
else:
update = swarms_best[x] - best_neighbour[x]
p[x] = best_neighbour[x] + np.random.uniform(0.0, 1.0) * update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment