Repository navigation
Fix degenerate dataframe handling #965
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: patch/0.15.3
Are you sure you want to change the base?
Changes from all commits
6787039
4000567
4bd274c
596d160
f90f385
6937736
2d81024
a26c05a
20dc639
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,14 +13,18 @@ | |
| from joblib.hashing import hash | ||
| from typing_extensions import override | ||
|
|
||
| from baybe.exceptions import IncompatibleSurrogateError, ModelNotTrainedError | ||
| from baybe.exceptions import ( | ||
| IncompatibleSurrogateError, | ||
| IncompleteMeasurementsError, | ||
| ModelNotTrainedError, | ||
| ) | ||
| from baybe.objectives.base import Objective | ||
| from baybe.parameters.base import Parameter | ||
| from baybe.searchspace import SearchSpace | ||
| from baybe.serialization.mixin import SerialMixin | ||
| from baybe.utils.basic import classproperty | ||
| from baybe.utils.conversion import to_string | ||
| from baybe.utils.dataframe import handle_missing_values, to_tensor | ||
| from baybe.utils.dataframe import to_tensor | ||
| from baybe.utils.scaling import ColumnTransformer | ||
|
|
||
| if TYPE_CHECKING: | ||
|
|
@@ -36,6 +40,23 @@ | |
| """Type alias for requestable statistics (a float yields the corresponding quantile).""" | ||
|
|
||
|
|
||
| def _validate_training_data(df: pd.DataFrame, name: str, /) -> None: | ||
| """Ensure a modeled quantity has a non-empty set of training data. | ||
|
|
||
| Args: | ||
| df: The training data for the modeled quantity. | ||
| name: The name of the modeled quantity. | ||
|
|
||
| Raises: | ||
| IncompleteMeasurementsError: If the modeled quantity has no training data. | ||
| """ | ||
| if df.empty: | ||
| raise IncompleteMeasurementsError( | ||
| "Each modeled quantity requires at least one complete measurement. " | ||
| f"No complete measurements are available for '{name}'." | ||
| ) | ||
|
|
||
|
|
||
| class _NoTransform(Enum): | ||
| """Sentinel class.""" | ||
|
|
||
|
|
@@ -403,23 +424,20 @@ def fit( | |
| NotImplementedError: When using a continuous search space and a non-GP | ||
| model. | ||
| """ | ||
| # TODO: consider adding a validation step for `measurements` | ||
|
|
||
| # Validate multi-target compatibility | ||
| if objective.is_multi_output and not self.supports_multi_output: | ||
| if objective._is_multi_model: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't we specify in the docstring of this class that this is a
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And it is also extra weird that there still is the
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is fishy
Overall this PR makes way more incisions than I'd expect, the gut feelings ays the fix to this issue should be much simpler and not touch so many things... |
||
| raise IncompatibleSurrogateError( | ||
| f"You attempted to train a single-output surrogate in a " | ||
| f"{len(objective.targets)}-target multi-output context. Either use " | ||
| f"a proper multi-output surrogate or consider explicitly " | ||
| f"replicating the current surrogate model using its " | ||
| f"'.{self.replicate.__name__}' method." | ||
| f"You attempted to train a single-output surrogate for an objective " | ||
| f"requiring {objective._n_models} modeled quantities. Either use a " | ||
| f"CompositeSurrogate or explicitly replicate the current surrogate " | ||
| f"model using its '.{self.replicate.__name__}' method." | ||
| ) | ||
|
|
||
| # When the context is unchanged, no retraining is necessary | ||
| measurements_hash = hash(measurements) | ||
| if ( | ||
| searchspace == self._searchspace | ||
| and objective == self._objective | ||
| and hash(measurements) == self._measurements_hash | ||
| and measurements_hash == self._measurements_hash | ||
| ): | ||
| return | ||
|
|
||
|
|
@@ -431,14 +449,16 @@ def fit( | |
| f"support transfer learning." | ||
| ) | ||
|
|
||
| # Block partial measurements | ||
| handle_missing_values(measurements, [t.name for t in objective.targets]) | ||
| # Block incomplete measurements | ||
| quantity_name = objective._modeled_quantity_names[0] | ||
| training_data = objective.handle_missing_values(measurements)[quantity_name] | ||
| _validate_training_data(training_data, quantity_name) | ||
|
|
||
| # Remember the training context | ||
| self._searchspace = searchspace | ||
| self._objective = objective | ||
| self._measurements = measurements | ||
| self._measurements_hash = hash(measurements) | ||
| self._measurements_hash = measurements_hash | ||
|
|
||
| # Create context-specific transformations | ||
| self._input_scaler = self._make_input_scaler(searchspace) | ||
|
|
@@ -451,9 +471,9 @@ def fit( | |
| # values, enabling predictions with input from the pre-transformed domain | ||
| # (this allows us to control precisely on which level the model is placed) | ||
| # * The main transformation is part of the computational backpropagation graph | ||
| pre_transformed = objective._pre_transform(measurements, allow_extra=True) | ||
| pre_transformed = objective._pre_transform(training_data, allow_extra=True) | ||
| train_x_comp_rep, train_y_tensor = to_tensor( | ||
| searchspace.transform(measurements, allow_extra=True), pre_transformed | ||
| searchspace.transform(training_data, allow_extra=True), pre_transformed | ||
| ) | ||
| train_x = self._input_scaler.transform(train_x_comp_rep) | ||
| train_y = ( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,7 +8,10 @@ | |
| import pytest | ||
| from pytest import param | ||
|
|
||
| from baybe.exceptions import IncompatibleSurrogateError | ||
| from baybe.exceptions import ( | ||
| IncompatibleSurrogateError, | ||
| IncompleteMeasurementsError, | ||
| ) | ||
| from baybe.objectives.base import Objective | ||
| from baybe.objectives.desirability import DesirabilityObjective | ||
| from baybe.objectives.pareto import ParetoObjective | ||
|
|
@@ -107,6 +110,87 @@ def test_composite_surrogates(surrogate): | |
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "objective", | ||
| [ | ||
| param( | ||
| SingleTargetObjective(NumericalTarget("unmeasured_target")), | ||
| id="single", | ||
| ), | ||
| param( | ||
| DesirabilityObjective( | ||
| [ | ||
| NumericalTarget("measured_target"), | ||
| NumericalTarget("unmeasured_target"), | ||
| ], | ||
| scalarizer="MEAN", | ||
| require_normalization=False, | ||
| ), | ||
| id="desirability", | ||
| ), | ||
| param( | ||
| DesirabilityObjective( | ||
| [ | ||
| NumericalTarget("measured_target"), | ||
| NumericalTarget("unmeasured_target"), | ||
| ], | ||
| scalarizer="MEAN", | ||
| require_normalization=False, | ||
| as_pre_transformation=True, | ||
| ), | ||
| id="desirability-pre", | ||
| ), | ||
| param( | ||
| ParetoObjective( | ||
| [ | ||
| NumericalTarget("measured_target"), | ||
| NumericalTarget("unmeasured_target"), | ||
| ] | ||
| ), | ||
| id="pareto", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_surrogate_requires_observations_for_each_modeled_quantity( | ||
| objective: Objective, | ||
| ): | ||
| """Each modeled quantity must have at least one complete measurement.""" | ||
| searchspace = NumericalDiscreteParameter("p", [0, 1]).to_searchspace() | ||
| measurements = pd.DataFrame({"p": [0, 1, 0]}) | ||
| measurements["measured_target"] = [1.0, 2.0, 3.0] | ||
| measurements["unmeasured_target"] = float("nan") | ||
|
|
||
| surrogate = GaussianProcessSurrogate() | ||
| replicate = objective._n_models > 1 | ||
| model = surrogate.replicate() if replicate else surrogate | ||
| if not replicate: | ||
| measurements = measurements.iloc[:0] | ||
| with patch.object(GaussianProcessSurrogate, "_fit") as fit: | ||
| with pytest.raises( | ||
| IncompleteMeasurementsError, match="No complete measurements" | ||
| ): | ||
| model.fit(searchspace, objective, measurements) | ||
| fit.assert_not_called() | ||
|
|
||
|
|
||
| def test_surrogate_rejects_objectives_with_multiple_modeled_quantities(): | ||
| """A single-output surrogate cannot model multiple quantities on its own.""" | ||
| objective = DesirabilityObjective( | ||
| [NumericalTarget("t1"), NumericalTarget("t2")], | ||
| scalarizer="MEAN", | ||
| require_normalization=False, | ||
| ) | ||
| assert objective.is_multi_output is False | ||
| assert objective._is_multi_model is True | ||
|
|
||
| searchspace = NumericalDiscreteParameter("p", [0, 1]).to_searchspace() | ||
| measurements = pd.DataFrame({"p": [0, 1], "t1": [0.1, 0.2], "t2": [0.2, 0.3]}) | ||
| with patch.object(GaussianProcessSurrogate, "_fit") as fit: | ||
| with pytest.raises(IncompatibleSurrogateError, match="single-output"): | ||
| GaussianProcessSurrogate().fit(searchspace, objective, measurements) | ||
| fit.assert_not_called() | ||
|
Comment on lines
+188
to
+191
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This reads a bit weird as you literally call a function called |
||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "model_cls, params", | ||
| [ | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for
DesirabilityObjective(pre_transform=True)this would say "there is not compelte measurement avaialble for desirability" which imo is not optimal. The specific target names should be emtnioned