Skip to content

Instantly share code, notes, and snippets.

@s4nyam
Last active August 24, 2023 18:39
Show Gist options
  • Save s4nyam/f320821d10e9d99dc48a7f8cb1413684 to your computer and use it in GitHub Desktop.
Save s4nyam/f320821d10e9d99dc48a7f8cb1413684 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def ackley(x, y):
a = 20
b = 0.2
c = 2 * np.pi
term1 = -a * np.exp(-b * np.sqrt((x**2 + y**2) / 2))
term2 = -np.exp((np.cos(c * x) + np.cos(c * y)) / 2)
return term1 + term2 + a + np.exp(1)
def initialize_population(pop_size, num_params):
return np.random.rand(pop_size, num_params) * 10 - 5
def evaluate_fitness(population):
return np.array([ackley(individual[0], individual[1]) for individual in population])
def select_parents(population, fitness, num_parents):
return population[np.argsort(fitness)[:num_parents]]
def crossover(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[1] / 2)
for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring
def mutate(offspring_crossover):
mutation_rate = 0.01
for idx in range(offspring_crossover.shape[0]):
for param_idx in range(offspring_crossover.shape[1]):
if np.random.rand() < mutation_rate:
offspring_crossover[idx, param_idx] = np.random.uniform(-5, 5)
return offspring_crossover
pop_size = 50
num_params = 2
num_generations = 200
population = initialize_population(pop_size, num_params)
fitness_history = []
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = ackley(X, Y)
def animate(i):
global population
global fitness_history
ax.clear()
# Update contour plot with new data
Z_current = ackley(X, Y)
surface = ax.contourf(X, Y, Z_current, levels=50, cmap='viridis')
contours_xy = ax.contour(X, Y, Z_current, levels=20, offset=np.min(Z_current), cmap='viridis', linestyles="solid")
fitness = evaluate_fitness(population)
fitness_history.append(np.min(fitness))
best_solution = population[np.argmin(fitness)]
ax.scatter(best_solution[0], best_solution[1], ackley(best_solution[0], best_solution[1]), color='red', marker='o', s=100)
parents = select_parents(population, fitness, num_parents=2)
offspring_crossover = crossover(parents, offspring_size=(pop_size - parents.shape[0], num_params))
offspring_mutation = mutate(offspring_crossover)
# Update the population with new positions
population[:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = offspring_mutation
for ind in population:
# Color particles red if they are close to the best solution
if np.all(ind == best_solution):
ax.scatter(ind[0], ind[1], ackley(ind[0], ind[1]), color='red', marker='o', s=100)
else:
ax.scatter(ind[0], ind[1], ackley(ind[0], ind[1]), color='blue', marker='o', s=20)
# Set the view angle for rotation
ax.view_init(elev=20, azim=i)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1, x2)')
equation_text = r'Ackley Function'
ax.set_title('Generation: {} - Best Fitness: {:.4f}\n'.format(i, np.min(fitness)) + equation_text, fontsize=12)
ani = FuncAnimation(fig, animate, frames=num_generations, interval=200, repeat=False)
ani.save('ackley_convergence.mp4', writer='ffmpeg', dpi=150, fps=20)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def ackley(x, y):
a = 20
b = 0.2
c = 2 * np.pi
term1 = -a * np.exp(-b * np.sqrt((x**2 + y**2) / 2))
term2 = -np.exp((np.cos(c * x) + np.cos(c * y)) / 2)
return term1 + term2 + a + np.exp(1)
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = ackley(X, Y)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='viridis')
cbar = fig.colorbar(surface)
cbar.set_label('f(x1, x2)')
contours_xy = ax.contour(X, Y, Z, levels=20, offset=np.min(Z), cmap='viridis', linestyles="solid")
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1, x2)')
equation_text = r"$f(x, y) = -20 \exp \left(-0.2 \sqrt{\frac{x^2 + y^2}{2}}\right) - \exp \left(\frac{\cos(2\pi x) + \cos(2\pi y)}{2}\right) + 20 + e$"
ax.set_title('3D Contour Plot of Ackley Function\n' + equation_text, fontsize=10)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def himmelblau(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
def initialize_population(pop_size, num_params):
return np.random.rand(pop_size, num_params) * 10 - 5
def evaluate_fitness(population):
return np.array([himmelblau(individual[0], individual[1]) for individual in population])
def select_parents(population, fitness, num_parents):
return population[np.argsort(fitness)[:num_parents]]
def crossover(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[1] / 2)
for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring
def mutate(offspring_crossover):
mutation_rate = 0.01
for idx in range(offspring_crossover.shape[0]):
for param_idx in range(offspring_crossover.shape[1]):
if np.random.rand() < mutation_rate:
offspring_crossover[idx, param_idx] = np.random.uniform(-5, 5)
return offspring_crossover
pop_size = 50
num_params = 2
num_generations = 200
population = initialize_population(pop_size, num_params)
fitness_history = []
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = himmelblau(X, Y)
Z_log = np.log(Z)
def animate(i):
global population
global fitness_history
ax.clear()
Z_current = himmelblau(X, Y)
Z_log_current = np.log(Z_current)
surface = ax.contourf(X, Y, Z_log_current, levels=50, cmap='viridis')
contours_xy = ax.contour(X, Y, Z_log_current, levels=20, offset=np.min(Z_log_current), cmap='viridis', linestyles="solid")
fitness = evaluate_fitness(population)
fitness_history.append(np.min(fitness))
best_solution = population[np.argmin(fitness)]
ax.scatter(best_solution[0], best_solution[1], np.log(himmelblau(best_solution[0], best_solution[1])), color='red', marker='o', s=100)
parents = select_parents(population, fitness, num_parents=2)
offspring_crossover = crossover(parents, offspring_size=(pop_size - parents.shape[0], num_params))
offspring_mutation = mutate(offspring_crossover)
population[:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = offspring_mutation
for ind in population:
if np.all(ind == best_solution):
ax.scatter(ind[0], ind[1], np.log(himmelblau(ind[0], ind[1])), color='red', marker='o', s=100)
else:
ax.scatter(ind[0], ind[1], np.log(himmelblau(ind[0], ind[1])), color='blue', marker='o', s=20)
ax.view_init(elev=20, azim=i)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('log(f(x1, x2))')
equation_text = r"$f(x, y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2$"
ax.set_title('Generation: {} - Best Fitness: {:.4f}\n'.format(i, np.min(fitness)) + equation_text, fontsize=12)
ani = FuncAnimation(fig, animate, frames=num_generations, interval=200, repeat=False)
ani.save('himmelblau_convergence.mp4', writer='ffmpeg', dpi=150, fps=20)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def himmelblau(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = himmelblau(X, Y)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='viridis')
cbar = fig.colorbar(surface)
cbar.set_label('f(x1, x2)')
contours_xy = ax.contour(X, Y, Z, levels=20, offset=np.min(Z), cmap='viridis', linestyles="solid")
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1, x2)')
equation_text = r"$f(x, y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2$"
ax.set_title('3D Contour Plot of Himmelblau Function\n' + equation_text, fontsize=12)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def rastrigin(x, y):
N = 2 # Number of dimensions
return 10 * N + (x - 10 * np.cos(2 * np.pi * x)) + (y - 10 * np.cos(2 * np.pi * y))
def initialize_population(pop_size, num_params):
return np.random.rand(pop_size, num_params) * 10.24 - 5.12
def evaluate_fitness(population):
return np.array([rastrigin(individual[0], individual[1]) for individual in population])
def select_parents(population, fitness, num_parents):
return population[np.argsort(fitness)[:num_parents]]
def crossover(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[1] / 2)
for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring
def mutate(offspring_crossover):
mutation_rate = 0.01
for idx in range(offspring_crossover.shape[0]):
for param_idx in range(offspring_crossover.shape[1]):
if np.random.rand() < mutation_rate:
offspring_crossover[idx, param_idx] = np.random.uniform(-5.12, 5.12)
return offspring_crossover
pop_size = 50
num_params = 2
num_generations = 200
population = initialize_population(pop_size, num_params)
fitness_history = []
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
x_range = np.linspace(-5.12, 5.12, 400)
y_range = np.linspace(-5.12, 5.12, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = rastrigin(X, Y)
def animate(i):
global population
global fitness_history
ax.clear()
Z_current = rastrigin(X, Y)
surface = ax.contourf(X, Y, Z_current, levels=50, cmap='viridis')
contours_xy = ax.contour(X, Y, Z_current, levels=20, offset=np.min(Z_current), cmap='viridis', linestyles="solid")
fitness = evaluate_fitness(population)
fitness_history.append(np.min(fitness))
best_solution = population[np.argmin(fitness)]
ax.scatter(best_solution[0], best_solution[1], rastrigin(best_solution[0], best_solution[1]), color='red', marker='o', s=100)
parents = select_parents(population, fitness, num_parents=2)
offspring_crossover = crossover(parents, offspring_size=(pop_size - parents.shape[0], num_params))
offspring_mutation = mutate(offspring_crossover)
population[:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = offspring_mutation
for ind in population:
if np.all(ind == best_solution):
ax.scatter(ind[0], ind[1], rastrigin(ind[0], ind[1]), color='red', marker='o', s=100)
else:
ax.scatter(ind[0], ind[1], rastrigin(ind[0], ind[1]), color='blue', marker='o', s=20)
ax.view_init(elev=20, azim=i)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1, x2)')
equation_text = r"$f(x, y) = 10N + (x - 10\cos(2\pi x)) + (y - 10\cos(2\pi y))$"
ax.set_title('Generation: {} - Best Fitness: {:.4f}\n'.format(i, np.min(fitness)) + equation_text, fontsize=12)
ani = FuncAnimation(fig, animate, frames=num_generations, interval=200, repeat=False)
ani.save('rastrigin_convergence.mp4', writer='ffmpeg', dpi=150, fps=20)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def rastrigin(x, y):
N = 2 # Number of dimensions
return 10 * N + (x - 10 * np.cos(2 * np.pi * x)) + (y - 10 * np.cos(2 * np.pi * y))
x_range = np.linspace(-5.12, 5.12, 400)
y_range = np.linspace(-5.12, 5.12, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = rastrigin(X, Y)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='viridis')
cbar = fig.colorbar(surface)
cbar.set_label('f(x1, x2)')
contours_xy = ax.contour(X, Y, Z, levels=20, offset=np.min(Z), cmap='viridis', linestyles="solid")
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1, x2)')
equation_text = r"$f(x, y) = 10N + (x - 10\cos(2\pi x)) + (y - 10\cos(2\pi y))$"
ax.set_title('3D Contour Plot of Rastrigin Function\n' + equation_text, fontsize=12)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
def rosenbrock(x, y):
return (100 * (y - x**2)**2 + (1 - x)**2)
def initialize_population(pop_size, num_params):
return np.random.rand(pop_size, num_params) * 10 - 5
def evaluate_fitness(population):
return np.array([rosenbrock(individual[0], individual[1]) for individual in population])
def select_parents(population, fitness, num_parents):
return population[np.argsort(fitness)[:num_parents]]
def crossover(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[1] / 2)
for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring
def mutate(offspring_crossover):
mutation_rate = 0.01
for idx in range(offspring_crossover.shape[0]):
for param_idx in range(offspring_crossover.shape[1]):
if np.random.rand() < mutation_rate:
offspring_crossover[idx, param_idx] = np.random.uniform(-5, 5)
return offspring_crossover
pop_size = 50
num_params = 2
num_generations = 200
population = initialize_population(pop_size, num_params)
fitness_history = []
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = rosenbrock(X, Y)
Z_log = np.log(Z)
def animate(i):
global population
global fitness_history
ax.clear()
# Update contour plot with new data
Z_current = rosenbrock(X, Y)
Z_log_current = np.log(Z_current)
surface = ax.contourf(X, Y, Z_log_current, levels=50, cmap='viridis')
contours_xy = ax.contour(X, Y, Z_log_current, levels=20, offset=np.min(Z_log_current), cmap='viridis', linestyles="solid")
fitness = evaluate_fitness(population)
fitness_history.append(np.min(fitness))
best_solution = population[np.argmin(fitness)]
ax.scatter(best_solution[0], best_solution[1], np.log(rosenbrock(best_solution[0], best_solution[1])), color='red', marker='o', s=100)
parents = select_parents(population, fitness, num_parents=2)
offspring_crossover = crossover(parents, offspring_size=(pop_size - parents.shape[0], num_params))
offspring_mutation = mutate(offspring_crossover)
# Update the population with new positions
population[:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = offspring_mutation
for ind in population:
# Color particles red if they are close to the best solution
if np.all(ind == best_solution):
ax.scatter(ind[0], ind[1], np.log(rosenbrock(ind[0], ind[1])), color='red', marker='o', s=100)
else:
ax.scatter(ind[0], ind[1], np.log(rosenbrock(ind[0], ind[1])), color='blue', marker='o', s=20)
# Set the view angle for rotation
ax.view_init(elev=20, azim=i)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('log(f(x1, x2))')
equation_text = r'$f(x, y) = 100(y - x^2)^2 + (1 - x)^2$'
ax.set_title('Generation: {} - Best Fitness: {:.4f}\n'.format(i, np.min(fitness)) + equation_text, fontsize=12)
ani = FuncAnimation(fig, animate, frames=num_generations, interval=200, repeat=False)
ani.save('rosenbrock_convergence.mp4', writer='ffmpeg', dpi=150,fps=20)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def rosenbrock(x, y):
return (100 * (y - x**2)**2 + (1 - x)**2)
x_range = np.linspace(-5, 5, 400)
y_range = np.linspace(-5, 5, 400)
X, Y = np.meshgrid(x_range, y_range)
Z = rosenbrock(X, Y)
Z_log = np.log(Z)
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.contourf(X, Y, Z_log, levels=50, cmap='viridis')
cbar = fig.colorbar(surface)
cbar.set_label('log(f(x1, x2))')
contours_xy = ax.contour(X, Y, Z_log, levels=20, offset=np.min(Z_log), cmap='viridis', linestyles="solid")
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('log(f(x1, x2))')
equation_text = r'$f(x, y) = 100(y - x^2)^2 + (1 - x)^2$'
ax.set_title('3D Contour Plot of Rosenbrock Function\n' + equation_text, fontsize=12)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment