In [ ]:
%matplotlib inline
import cma
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
In [ ]:
sns.set_context("talk")
plt.rcParams['figure.figsize'] = 20,10
In [ ]:
init_lower_bound = -10.
init_higher_bound = 10.
NUM_RUNS = 1000
DIMS = (2, 3, 4, 5, 6)
F_TARGET = 1e-30
fitness = cma.ff.sphere
fitness_name = "Sphere"
fitness = cma.ff.rastrigin
fitness_name = "Rastrigin"
fitness = cma.ff.rosen
fitness_name = "Rosenbrock"
In [ ]:
solutions_list = []
run_id = 0
num_dim = None
dim_index_list = []
def callback_function(es):
global gen_id
global eval_id
global num_dim
gen_id += 1
indiv_dict = {
"gen": gen_id,
"run": run_id,
"num_dim": num_dim,
#"best_x": es.best.x,
"best_f": es.best.f,
"best_evals": es.best.evals,
"sigma": es.sigma,
}
solutions_list.append(indiv_dict)
for ndim in DIMS:
for run in range(1, NUM_RUNS):
run_id = run
num_dim = ndim
gen_id = 0
print("{}D run {}".format(ndim, run))
x0 = np.random.uniform(low=init_lower_bound, high=init_higher_bound, size=num_dim) # initial solution
sigma0 = np.random.uniform(0., 1.) # initial standard deviation
x_optimal, es = cma.fmin2(fitness, x0, sigma0,
callback=callback_function,
options={'verbose': -9, 'ftarget': F_TARGET, 'maxfevals': 8000}) # See last example of http://cma.gforge.inria.fr/apidocs-pycma/cma.evolution_strategy.html#fmin
df = pd.DataFrame(solutions_list)
In [ ]:
ALPHA = 0.2
ax = sns.lineplot(x="gen", y="best_f",
estimator=None, units="run", alpha=ALPHA,
data=df.loc[df.num_dim == DIMS[0]])
for dim in DIMS[1:]:
sns.lineplot(x="gen", y="best_f",
estimator=None, units="run", alpha=ALPHA,
data=df.loc[df.num_dim == dim],
ax=ax)
ax.set_yscale("log")
plt.grid()
plt.title("Best fitness ({} runs)".format(NUM_RUNS))
plt.ylabel("Best fitness")
plt.xlabel("Number of generations")
legend_lines = []
legend_str = []
for dim in DIMS:
legend_lines.append(ax.get_lines()[(dim-1) * (NUM_RUNS-1) - 1])
legend_str.append("{} {}D".format(fitness_name, dim))
plt.legend(legend_lines, legend_str)
plt.savefig(fitness_name.lower() + ".png");
In [ ]:
ax = sns.lineplot(x="gen", y="best_f",
#estimator=None, units="run", alpha=0.5,
data=df.loc[df.num_dim == DIMS[0]],
label="{} {}D".format(fitness_name, DIMS[0]))
for dim in DIMS[1:]:
sns.lineplot(x="gen", y="best_f",
#estimator=None, units="run", alpha=0.5,
data=df.loc[df.num_dim == dim],
label="{} {}D".format(fitness_name, dim))
ax.set_yscale("log")
plt.grid()
plt.title("Mean of best fitness")
plt.ylabel("Mean of best fitness")
plt.xlabel("Number of generations")
plt.savefig(fitness_name.lower() + "_avg.png");
In [ ]:
ax = sns.lineplot(x="gen", y="best_f",
estimator=np.median,
data=df.loc[df.num_dim == DIMS[0]],
label="{} {}D".format(fitness_name, DIMS[0]))
for dim in DIMS[1:]:
sns.lineplot(x="gen", y="best_f",
estimator=np.median,
data=df.loc[df.num_dim == dim],
label= "{} {}D".format(fitness_name, dim))
ax.set_yscale("log")
plt.grid()
plt.title("Median of best fitness")
plt.ylabel("Median of best fitness")
plt.xlabel("Number of generations")
plt.savefig(fitness_name.lower() + "_med.png");
In [ ]:
df.to_csv(fitness_name.lower() + ".csv")