Created
January 15, 2015 02:18
-
-
Save 46bit/059a03dc6fff3fce9639 to your computer and use it in GitHub Desktop.
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 random, heapq | |
def ax2_bx_c(x, (a, b, c)): | |
return a * x**2 + b * x + c | |
def ax2_bx_c_fitness(x_range, ideal_params, test_params): | |
fitness = 0.0 | |
for x in x_range: | |
x = float(x) | |
fitness += ax2_bx_c(x, test_params) - ax2_bx_c(x, ideal_params) | |
return abs(fitness) | |
def ax2_bx_c_successors((a, b, c), ignore_params): | |
successor_params = [ | |
(a + 1, b, c), | |
(a - 1, b, c), | |
(a, b + 1, c), | |
(a, b - 1, c), | |
(a, b, c + 1), | |
(a, b, c - 1) | |
] | |
return [ps for ps in successor_params if ps not in ignore_params] | |
params_heapq = [] | |
tested_params = [] | |
x_test_range = range(-1000000000, 1000000000, 5000000) | |
ideal_a = 2.3 | |
ideal_b = 9.7 | |
ideal_c = 2.3 | |
ideal_params = (ideal_a, ideal_b, ideal_c) | |
ideal_fitness = 0.0 | |
# generate a random uniform (0.0, 10.0) value for a, b, c, | |
# make sole element of new heapq | |
initial_a = random.uniform(0.0, 10.0) | |
initial_b = random.uniform(0.0, 10.0) | |
initial_c = random.uniform(0.0, 10.0) | |
initial_params = (initial_a, initial_b, initial_c) | |
best_fitness = ax2_bx_c_fitness(x_test_range, ideal_params, initial_params) | |
params_heapq.append((best_fitness, initial_params)) | |
# pop (fitness, (a, b, c)) from heapq, | |
# for 3 variations: a+ a- b+ b- c+ c-, | |
# evaluate ax2_bx_c(random.uniform(-100.0, 100.0), a, b, c) | |
# new fitness is the difference between that and for oa, ob, oc | |
# add (new fitness, (a, b, c)) to heapq | |
successors_round = 0 | |
while best_fitness > 0.1 and len(params_heapq) > 0: | |
successors_round += 1 | |
best_fitness, best_params = heapq.heappop(params_heapq) | |
tested_params.append(best_params) | |
successors_params = ax2_bx_c_successors(best_params, tested_params) | |
print("Finding successors for #", successors_round, best_params, "scoring", best_fitness) | |
for successor_params in successors_params: | |
successor_fitness = ax2_bx_c_fitness(x_test_range, ideal_params, successor_params) | |
heapq.heappush(params_heapq, (successor_fitness, successor_params)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment