Created
December 11, 2017 15:05
-
-
Save fedden/22831cbfe47b71d71570220ddf6395a7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def create_random_population(size): | |
return np.random.random((size, 10)) | |
for iteration in range(50): | |
size = 100 | |
disturbance_threshold = 0.01 | |
lower = -1.0 | |
upper = 1.0 | |
iteration_amount = 100 | |
population = create_random_population(size) | |
all_time_best = None | |
all_time_best_score = np.finfo(np.float32).max | |
best_neighbour = np.zeros_like(population[0]) | |
done = False | |
while not done: | |
fitnesses = np.array([get_fitness(p) for p in population]) | |
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 | |
if all_time_best_score == 0: | |
done = True | |
break | |
r = np.random.uniform(0.0, 1.0, population.shape) | |
for i, p in enumerate(population): | |
left = (i - 1) if i is not 0 else len(population) - 1 | |
right = (i + 1) if i is not (len(population) - 1) else 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 | |
solution = np.argsort(all_time_best) + 1 | |
print('\nattempt', iteration) | |
print(' * fly solution: ', solution) | |
print(' * difference sum: ', abs(36 - np.sum(solution[:5]))) | |
print(' * difference product: ', abs(360 - np.product(solution[-5:]))) | |
#------------------------------------------------------------ | |
# Code Ouput | |
#------------------------------------------------------------ | |
# attempt 0 | |
# * fly solution: [ 7 8 10 2 9 3 5 4 6 1] | |
# * difference sum: 0 | |
# * difference product: 0 | |
# | |
# attempt 1 | |
# * fly solution: [10 9 8 7 2 1 5 4 6 3] | |
# * difference sum: 0 | |
# * difference product: 0 | |
# | |
# attempt 2 | |
# * fly solution: [ 8 7 9 10 2 3 5 1 6 4] | |
# * difference sum: 0 | |
# * difference product: 0 | |
# | |
# attempt 3 | |
# * fly solution: [ 2 9 8 7 10 1 5 3 6 4] | |
# * difference sum: 0 | |
# * difference product: 0 | |
# | |
# attempt 4 | |
# * fly solution: [ 7 10 8 2 9 3 1 6 4 5] | |
# * difference sum: 0 | |
# * difference product: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment