Skip to content

Instantly share code, notes, and snippets.

@adamstirtan
Last active May 31, 2023 02:45
Show Gist options
  • Save adamstirtan/dbe6154e98dff08e63bea3c928ddb62d to your computer and use it in GitHub Desktop.
Save adamstirtan/dbe6154e98dff08e63bea3c928ddb62d to your computer and use it in GitHub Desktop.
Particle Swarm Optimization in Python
import numpy as np
def basic_pso(cost_function, bounds, num_particles, num_iterations):
# Initialize the positions and velocities of the particles
positions = np.random.uniform(bounds[0], bounds[1], (num_particles, len(bounds[0])))
velocities = np.zeros((num_particles, len(bounds[0])))
# Initialize the best position and cost for each particle
best_positions = positions.copy()
best_costs = np.array([cost_function(p) for p in positions])
# Initialize the global best position and cost
global_best_position = best_positions[np.argmin(best_costs)]
global_best_cost = np.min(best_costs)
# Set the constants for the velocity update formula
c1 = 2.05
c2 = 2.05
# Run the iterations of the algorithm
for _ in range(num_iterations):
for i in range(num_particles):
# Update the velocity and position of the particle
velocities[i] = (0.7298 * velocities[i]) + (c1 * np.random.rand() * (best_positions[i] - positions[i])) + (c2 * np.random.rand() * (global_best_position - positions[i]))
positions[i] += velocities[i]
# Update the best position and cost for the particle if a better solution is found
cost = cost_function(positions[i])
if cost < best_costs[i]:
best_positions[i] = positions[i]
best_costs[i] = cost
# Update the global best position and cost if a better solution is found
if cost < global_best_cost:
global_best_position = positions[i]
global_best_cost = cost
# Return the final global best position and cost
return global_best_position, global_best_cost
def fitness(x):
return x**2
result = basic_pso(fitness, ([-10.0], [10.0]), 25, 100)
print("Global best position: " + str(result[0]))
print("Global best fitness: " + str(result[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment