-
Notifications
You must be signed in to change notification settings - Fork 54
Add RegressionOutput #1115
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
Merged
Merged
Add RegressionOutput #1115
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3c37ffc
Add BinaryOutput
edknv 4425d2f
Merge branch 'main' into torch/binary_output
edknv 2385020
address comments
edknv c9e26b4
Add RegressionOutput
edknv 91bf855
Add continuous tag to target
edknv cb31c89
Merge branch 'main' into torch/regression_output
edknv d7742ac
Merge branch 'main' into torch/regression_output
marcromeyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| from typing import Optional, Sequence | ||
|
|
||
| import torch | ||
| from torch import nn | ||
| from torchmetrics import Metric | ||
|
|
||
| from merlin.models.torch.block import Block | ||
| from merlin.schema import ColumnSchema, Schema | ||
|
|
||
|
|
||
| class ModelOutput(Block): | ||
| """A base class for prediction tasks. | ||
|
|
||
| Example usage:: | ||
| >>> schema = ColumnSchema( | ||
| ... "target", | ||
| ... properties={"domain": {"min": 0, "max": 1}}, | ||
| ... tags=[Tags.CATEGORICAL, Tags.TARGET] | ||
| ... ) | ||
| >>> model_output = ModelOutput( | ||
| ... nn.LazyLinear(1), | ||
| ... nn.Sigmoid(), | ||
| ... schema=schema | ||
| ... ) | ||
| >>> input = torch.randn(3, 2) | ||
| >>> output = model_output(input) | ||
| >>> print(output) | ||
| tensor([[0.5529], | ||
| [0.3562], | ||
| [0.7478]], grad_fn=<SigmoidBackward0>) | ||
|
|
||
| Parameters | ||
| ---------- | ||
| schema: Optional[ColumnSchema] | ||
| The schema defining the column properties. | ||
| loss: nn.Module | ||
| The loss function used for training. | ||
| metrics: Sequence[Metric] | ||
| The metrics used for evaluation. | ||
| name: Optional[str] | ||
| The name of the model output. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *module: nn.Module, | ||
| schema: Optional[ColumnSchema] = None, | ||
| loss: Optional[nn.Module] = None, | ||
| metrics: Sequence[Metric] = (), | ||
| name: Optional[str] = None, | ||
| ): | ||
| """Initializes a ModelOutput object.""" | ||
| super().__init__(*module, name=name) | ||
|
|
||
| self.loss = loss | ||
| self.metrics = metrics | ||
| self.output_schema: Schema = Schema() | ||
|
|
||
| if schema: | ||
| self.setup_schema(schema) | ||
| self.create_target_buffer() | ||
|
|
||
| def setup_schema(self, schema: Optional[ColumnSchema]): | ||
| """Set up the schema for the output. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| schema: ColumnSchema or None | ||
| The schema defining the column properties. | ||
| """ | ||
| self.output_schema = Schema([schema]) | ||
|
|
||
| def create_target_buffer(self): | ||
| self.register_buffer("target", torch.zeros(1, dtype=torch.float32)) | ||
|
|
||
| def eval(self): | ||
| """Sets the module in evaluation mode. | ||
|
|
||
| Returns | ||
| ------- | ||
| nn.Module | ||
| The module in evaluation mode. | ||
| """ | ||
| # Reset target | ||
| self.target = torch.zeros(1, dtype=torch.float32) | ||
|
|
||
| return self.train(False) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| from typing import Optional, Sequence | ||
|
|
||
| from torch import nn | ||
| from torchmetrics import AUROC, Accuracy, Metric, Precision, Recall | ||
|
|
||
| import merlin.dtypes as md | ||
| from merlin.models.torch.outputs.base import ModelOutput | ||
| from merlin.schema import ColumnSchema, Schema | ||
|
|
||
|
|
||
| class BinaryOutput(ModelOutput): | ||
| """A prediction block for binary classification. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| schema: Optional[ColumnSchema]) | ||
| The schema defining the column properties. Default is None. | ||
| loss: nn.Module | ||
| The loss function used for training. Default is nn.BCEWithLogitsLoss(). | ||
| metrics: Sequence[Metric] | ||
| The metrics used for evaluation. Default includes Accuracy, AUROC, Precision, and Recall. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| schema: Optional[ColumnSchema] = None, | ||
| loss: nn.Module = nn.BCEWithLogitsLoss(), | ||
| metrics: Sequence[Metric] = ( | ||
| Accuracy(task="binary"), | ||
| AUROC(task="binary"), | ||
| Precision(task="binary"), | ||
| Recall(task="binary"), | ||
| ), | ||
| ): | ||
| """Initializes a BinaryOutput object.""" | ||
| super().__init__( | ||
| nn.LazyLinear(1), | ||
| nn.Sigmoid(), | ||
| schema=schema, | ||
| loss=loss, | ||
| metrics=metrics, | ||
| ) | ||
|
|
||
| def setup_schema(self, target: Optional[ColumnSchema]): | ||
| """Set up the schema for the output. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| target: Optional[ColumnSchema] | ||
| The schema defining the column properties. | ||
| """ | ||
| _target = target.with_dtype(md.float32) | ||
| if "domain" not in target.properties: | ||
| _target = _target.with_properties( | ||
| {"domain": {"min": 0, "max": 1, "name": _target.name}}, | ||
| ) | ||
|
|
||
| self.output_schema = Schema([_target]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| from typing import Optional, Sequence | ||
|
|
||
| from torch import nn | ||
| from torchmetrics import MeanSquaredError, Metric | ||
|
|
||
| import merlin.dtypes as md | ||
| from merlin.models.torch.outputs.base import ModelOutput | ||
| from merlin.schema import ColumnSchema, Schema | ||
|
|
||
|
|
||
| class RegressionOutput(ModelOutput): | ||
| """A prediction block for regression. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| schema: Optional[ColumnSchema] | ||
| The schema defining the column properties. Default is None. | ||
| loss: torch.nn.Module | ||
| The loss function used for training. Default is nn.MSELoss(). | ||
| metrics: Sequence[Metric] | ||
| The metrics used for evaluation. Default is MeanSquaredError. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| schema: Optional[ColumnSchema] = None, | ||
| loss: nn.Module = nn.MSELoss(), | ||
| metrics: Sequence[Metric] = (MeanSquaredError(),), | ||
| ): | ||
| """Initializes a RegressionOutput object.""" | ||
| super().__init__( | ||
| nn.LazyLinear(1), | ||
| schema=schema, | ||
| loss=loss, | ||
| metrics=metrics, | ||
| ) | ||
|
|
||
| def setup_schema(self, target: Optional[ColumnSchema]): | ||
| """Set up the schema for the output. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| target: Optional[ColumnSchema] | ||
| The schema defining the column properties. | ||
| """ | ||
| _target = target.with_dtype(md.float32) | ||
|
|
||
| self.output_schema = Schema([_target]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| # | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| import numpy as np | ||
| import torch | ||
| from torch import nn | ||
| from torchmetrics import AUROC, Accuracy | ||
|
|
||
| import merlin.models.torch as mm | ||
| from merlin.models.torch.utils import module_utils | ||
| from merlin.schema import ColumnSchema, Schema, Tags | ||
|
|
||
|
|
||
| class TestModelOutput: | ||
| def test_init(self): | ||
| block = mm.Block() | ||
| loss = nn.BCEWithLogitsLoss() | ||
| model_output = mm.ModelOutput(block, loss=loss) | ||
|
|
||
| assert isinstance(model_output, mm.ModelOutput) | ||
| assert model_output.loss is loss | ||
| assert model_output.metrics == () | ||
| assert model_output.output_schema == Schema() | ||
|
|
||
| def test_identity(self): | ||
| block = mm.Block() | ||
| loss = nn.BCEWithLogitsLoss() | ||
| model_output = mm.ModelOutput(block, loss=loss) | ||
| inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) | ||
|
|
||
| outputs = module_utils.module_test(model_output, inputs) | ||
|
|
||
| assert torch.equal(inputs, outputs) | ||
|
|
||
| def test_setup_metrics(self): | ||
| block = mm.Block() | ||
| loss = nn.BCEWithLogitsLoss() | ||
| metrics = (Accuracy(task="binary"), AUROC(task="binary")) | ||
| model_output = mm.ModelOutput(block, loss=loss, metrics=metrics) | ||
|
|
||
| assert model_output.metrics == metrics | ||
|
|
||
| def test_setup_schema(self): | ||
| block = mm.Block() | ||
| loss = nn.BCEWithLogitsLoss() | ||
| schema = ColumnSchema("feature", dtype=np.int32, tags=[Tags.CONTINUOUS]) | ||
| model_output = mm.ModelOutput(block, loss=loss, schema=schema) | ||
|
|
||
| assert isinstance(model_output.output_schema, Schema) | ||
| assert model_output.output_schema.first == schema | ||
|
|
||
| def test_eval_resets_target(self): | ||
| block = mm.Block() | ||
| loss = nn.BCEWithLogitsLoss() | ||
| model_output = mm.ModelOutput(block, loss=loss) | ||
|
|
||
| assert torch.equal(model_output.target, torch.zeros(1)) | ||
| model_output.target = torch.ones(1) | ||
| assert torch.equal(model_output.target, torch.ones(1)) | ||
| model_output.eval() | ||
| assert torch.equal(model_output.target, torch.zeros(1)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.