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

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() #192

Open li54426 opened 2 years ago

li54426 commented 2 years ago

File "C:\software\anconda\lib\site-packages\sko\GA.py", line 57, in penalty_ueq = np.array([np.sum(np.abs([max(0, c_i(x)) for c_i in self.constraint_ueq])) for x in self.X]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

mmfarrugia commented 1 year ago

I am also running into this issue with the PSO class:

def update_pbest(self): ''' personal best :return: ''' 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

I am, however, really monkeying around a bit by making a hybrid optimizer though so this could be a result of my meddling.

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

Mikaela

mmfarrugia commented 1 year ago

After some investigation, I've highlighted that the issue arises after the first iteration: while I haven't cloned the code to debug it yet (If maintainers would appreciate a fix and pull request on this then I could do so), it seems that in the first iteration it works properly, self.need_update is size (pop_size, 1) array, but in the second iteration it returns (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 but I do now notice that this is a bug inherently different from the one in this thread, so I will open a new one.

Thank you!