Skip to content

Commit 862b685

Browse files
Handle deterministic constraint probabilities without NaNs
1 parent ec45123 commit 862b685

2 files changed

Lines changed: 59 additions & 16 deletions

File tree

‎bayes_opt/constraint.py‎

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,9 @@ def predict(self, X: NDArray[Float]) -> NDArray[Float]:
167167
with :math:`\mu(x)`, :math:`\sigma^2(x)` the mean and variance at
168168
:math:`x` as given by the GP and :math:`c^{\text{low}}`,
169169
:math:`c^{\text{up}}` the lower and upper bounds of the constraint
170-
respectively.
170+
respectively. A prediction with zero standard deviation is treated as a
171+
point mass: its probability is one exactly when its mean is within the
172+
inclusive bounds, and zero otherwise.
171173
172174
Note
173175
----
@@ -197,28 +199,22 @@ def predict(self, X: NDArray[Float]) -> NDArray[Float]:
197199
y_std: NDArray[Float]
198200
p_lower: NDArray[Float]
199201
p_upper: NDArray[Float]
200-
if len(self._model) == 1:
201-
y_mean, y_std = self._model[0].predict(X, return_std=True)
202-
203-
p_lower = (
204-
norm(loc=y_mean, scale=y_std).cdf(self._lb[0]) if self._lb[0] != -np.inf else np.array([0])
205-
)
206-
p_upper = (
207-
norm(loc=y_mean, scale=y_std).cdf(self._ub[0]) if self._ub[0] != np.inf else np.array([1])
208-
)
209-
result = p_upper - p_lower
210-
return result.reshape(X_shape[:-1])
211-
212202
result = np.ones(X.shape[0])
213203
for j, gp in enumerate(self._model):
214204
y_mean, y_std = gp.predict(X, return_std=True)
205+
deterministic = y_std == 0
206+
# A zero-variance Gaussian is a point mass; do not pass scale=0 to scipy.
207+
safe_std = np.where(deterministic, 1.0, y_std)
215208
p_lower = (
216-
norm(loc=y_mean, scale=y_std).cdf(self._lb[j]) if self._lb[j] != -np.inf else np.array([0])
209+
norm(loc=y_mean, scale=safe_std).cdf(self._lb[j]) if self._lb[j] != -np.inf else np.array([0])
217210
)
218211
p_upper = (
219-
norm(loc=y_mean, scale=y_std).cdf(self._ub[j]) if self._ub[j] != np.inf else np.array([1])
212+
norm(loc=y_mean, scale=safe_std).cdf(self._ub[j]) if self._ub[j] != np.inf else np.array([1])
213+
)
214+
probability = np.where(
215+
deterministic, (self._lb[j] <= y_mean) & (y_mean <= self._ub[j]), p_upper - p_lower
220216
)
221-
result = result * (p_upper - p_lower)
217+
result = result * probability
222218
return result.reshape(X_shape[:-1])
223219

224220
def approx(self, X: NDArray[Float]) -> NDArray[Float]:

‎tests/test_constraint.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,50 @@ def test_null_constraint_function():
197197
constraint = ConstraintModel(None, np.array([0, 0]), np.array([1, 1]))
198198
with pytest.raises(ValueError, match=re.escape("No constraint function was provided.")):
199199
constraint.eval()
200+
201+
202+
@pytest.mark.parametrize(("lb", "ub"), [(0.0, 1.0), (-np.inf, 1.0), (0.0, np.inf), (-np.inf, np.inf)])
203+
@pytest.mark.parametrize("n_constraints", [1, 2])
204+
def test_predict_zero_variance(monkeypatch, lb, ub, n_constraints):
205+
"""Deterministic predictions use closed bounds, without dividing by zero."""
206+
from scipy.stats import norm
207+
208+
lower = lb if n_constraints == 1 else [lb, -1.0]
209+
upper = ub if n_constraints == 1 else [ub, 1.0]
210+
model = ConstraintModel(None, lower, upper, random_state=0)
211+
means = np.array([-1.0, 0.0, 0.5, 1.0, 2.0])
212+
stds = np.array([0.0, 0.0, 0.5, 0.0, 0.0])
213+
for i, gp in enumerate(model.model):
214+
gp.n_features_in_ = 1
215+
if i == 0:
216+
monkeypatch.setattr(gp, "predict", lambda X, return_std: (means, stds))
217+
else:
218+
monkeypatch.setattr(gp, "predict", lambda X, return_std: (np.zeros(len(X)), np.ones(len(X))))
219+
expected = ((lb <= means) & (means <= ub)).astype(float)
220+
expected[2] = norm.cdf((ub - means[2]) / stds[2]) - norm.cdf((lb - means[2]) / stds[2])
221+
if n_constraints == 2:
222+
expected *= norm.cdf(1.0) - norm.cdf(-1.0)
223+
X = np.arange(5.0).reshape(1, 5, 1)
224+
with np.errstate(divide="raise", invalid="raise"):
225+
actual = model.predict(X)
226+
assert actual.shape == (1, 5)
227+
np.testing.assert_allclose(actual[0], expected, rtol=1e-14, atol=0)
228+
229+
230+
@pytest.mark.parametrize("n_constraints", [1, 2])
231+
def test_noiseless_constraint_training_predictions(n_constraints):
232+
"""A real noiseless GP gives finite feasibility at observed inputs."""
233+
bounds = (-0.5, 0.5) if n_constraints == 1 else ([-0.5, -0.5], [0.5, 0.5])
234+
model = ConstraintModel(None, *bounds, random_state=0)
235+
for gp in model.model:
236+
gp.set_params(alpha=0, optimizer=None)
237+
X = np.array([[0.0], [1.0], [2.0]])
238+
Y = np.array([-1.0, 0.0, 1.0])
239+
if n_constraints == 2:
240+
Y = np.column_stack([Y, Y])
241+
model.fit(X, Y)
242+
# Keep this an integration regression, not only a mocked prediction table.
243+
assert np.any(model.model[0].predict(X, return_std=True)[1] == 0)
244+
with np.errstate(divide="raise", invalid="raise"):
245+
actual = model.predict(X)
246+
np.testing.assert_allclose(actual, model.allowed(model.approx(X)).astype(float))

0 commit comments

Comments
 (0)