Repository navigation
Closed
Labels
Description
Describe the bug
Using 'scipy == 1.11.1' with 'bayesian-optimization == 1.4.0' I see that I cannot log if multiple constraints are defined:
def constraint_function_2_dim(x, y):
return np.array([
- np.cos(x) * np.cos(y) + np.sin(x) * np.sin(y),
- np.cos(x) * np.cos(-y) + np.sin(x) * np.sin(-y)]).tolist()
constraint_lower = np.array([-np.inf, -np.inf]).tolist()
constraint_upper = np.array([0., 0.]).tolist()
constraint = NonlinearConstraint(constraint_function_2_dim, constraint_lower, constraint_upper)
optimizer = BayesianOptimization(
f=target_function,
constraint=constraint,
pbounds=pbounds,
verbose=0, # verbose = 1 prints only when a maximum is observed, verbose = 0 is silent
random_state=1,
)
logger = JSONLogger(path="./log_multiple_constraints") # writes logs.json
optimizer.subscribe(Events.OPTIMIZATION_STEP, logger)
optimizer.maximize(
init_points=2,
n_iter=10,
)getting the error:
Object of type ndarray is not JSON serializable
We suggest to fix this way:
modify target_space.py this way:
def res(self):
if self._constraint is None:
params = [dict(zip(self.keys, p)) for p in self.params]
return [
{"target": target, "params": param}
for target, param in zip(self.target, params)
]
else:
params = [dict(zip(self.keys, p)) for p in self.params]
return [
{
"target": target,
"constraint": constraint_value.tolist(),
"params": param,
"allowed": allowed
}
for target, constraint_value, param, allowed in zip(
self.target,
self._constraint_values,
params,
self._constraint.allowed(self._constraint_values)
)
]
(basically, adding "tolist()" to constraint_value in the returned list)
Thanks a lot!
Activity
t-muser commentedon Jun 20, 2024
Thanks for reporting this bug @valentinafarrelli. :)
I've pushed a fix. It might take some time to get it merged and a release pushed. If you need help installing from the branch with the patch let me know.
valentinafarrelli commentedon Jun 20, 2024
t-muser commentedon Jun 20, 2024
Assuming that you're using
pip, you can just runIf you're using conda, the easiest way is probably to install pip via conda and then install the package via pip.
valentinafarrelli commentedon Jun 20, 2024
t-muser commentedon Jun 25, 2024
This fix will be published with the next release :)