guofei9987 / scikit-opt

Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Optimization Algorithm,Immune Algorithm, Artificial Fish Swarm Algorithm, Differential Evolution and TSP(Traveling salesman)
https://scikit-opt.github.io/scikit-opt/#/en/
MIT License
5.3k stars 989 forks source link

BUG: array shape mismatch between Y and pbest_y in PSO, error raised in update_pbest #222

Closed mmfarrugia closed 1 year ago

mmfarrugia commented 1 year ago

I think I have figured out the problem, just needs fixed.

Error message raised:

def update_pbest(self):

self.need_update = self.pbest_y > self.Y
for idx, x in enumerate(self.X):

      if self.need_update[idx]:
E ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

../../../.local/lib/python3.11/site-packages/sko/PSO.py:151: ValueError

First iteration works properly, self.need_update is size (pop_size, 1) array, but in the second iteration it is (pop_size, pop_size) arrray of booleans.

Looks like it is because self.pbest_y is a 2-dimensional array with shape (pop_size, 1) but self.Y is a 1-dimensional array of length pop_size, so effectively shape (1, pop_size) I think. It's a quick fix in the definition of self.Y to make it a 2-dimensional array.

I am, however, really messing around a bit by making a hybrid optimizer though so this could be a result of my meddling, but I don't think so because it happens in my basic usage of PSO as well.

I haven't cloned the code to debug and fix it yet. If maintainers would appreciate a fix and pull request on this then I am happy to help out with a fix and pull request but please note this would be my first time pushing to an open-source project so I may need a little guidance with the pull request process.

Also happy to provide more information for reproducibility.

Thank you for such a well-written, intuitive, and useful package!

Mikaela

mmfarrugia commented 1 year ago

Apologies, I found the issue: I was trying to hybridize PSO with a class where Y is 1 dimensional (DE). Was able to fix it within my code by flattening and reshaping. Closing the issue.

Thanks!