ljvmiranda921 / pyswarms

A research toolkit for particle swarm optimization in Python
https://pyswarms.readthedocs.io/en/latest/
MIT License
1.27k stars 333 forks source link

A toy problem example - need help to use PySwarms #510

Open twistfire opened 1 year ago

twistfire commented 1 year ago

Description

I need to optimize a function of >30 arguments using PSO technique. The function in nonconvex and has a lot of pockets inside.

I know the bounds for each parameter to optimize and the initial guess for each of them. But I don't get how to pass all this information to PySwarms to get it working.

So I need a very basic example to run and I created next "toy problem" to solve that will help me and others to understand how can I use this package for this kind of problems.

What I Did

I have created a toy-problem function, the parameters of which I need to optimize. It doesn't works (I don't know why) and that is where I need help for understanding.

Here is the code:

import numpy as np
import pyswarms as ps

# Define the objective function
def objective_function(x):
    return  ((x[0] - 1)**2 + (x[1]-2)**2 + (x[2] - 3)**2)

# Define the bounds for each element of x
bounds = ([-5]*3, [5]*3)
print('Bounds:')
print(bounds)

# Define the initial guesses for each element of x
initial_guess_1 = np.array([1.0, 2.0, 2.9])

# Define the number of elements to optimize
dimensions = initial_guess_1.size
print('Dimensions:', dimensions)

# defining the number of particles to use:
n_particles = 100

print('Objective function for initial guess:')
print(objective_function(initial_guess_1))

# reshaping to get all the particles initial guess positions? 
# I don't know if it's necessary to do this?

initial_guess = initial_guess_1.reshape((1, dimensions))
init_pos = np.tile(initial_guess, (n_particles, 1))

print('Initial guess of one particle:')
print(initial_guess_1)

print('Initial positions for all particles: ')
print(init_pos.shape)
print(init_pos)

# Define the options for the optimizer

options = {
    'c1': 0.5,  # cognitive parameter
    'c2': 0.3,  # social parameter
    'w': 0.9   # inertia weight
}

# Create a PSO optimizer
optimizer = ps.single.GlobalBestPSO(n_particles=n_particles, 
                                    dimensions=dimensions, 
                                    options=options, 
                                    bounds=bounds,
                                    init_pos=init_pos
                                    )

# Initialize the particles with the initial guesses
#optimizer.pos = init_pos

# Run the optimization
best_cost, best_position= optimizer.optimize(objective_function, iters=1000, verbose=True)

# Print the results
print("Best position:", best_position)
print("Best cost:", best_cost)

print('Func value at best pos', objective_function(best_cost))

It gives an error message:

ValueError: operands could not be broadcast together with shapes (3,) (100,)