Skip to content

Commit 7781834

Browse files
authored
feat(torch): add more errors and fix imports (#16)
1 parent ab0edbf commit 7781834

File tree

5 files changed

+94
-2
lines changed

5 files changed

+94
-2
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ pip install sklearn-utilities
4242

4343
## API
4444

45+
See [Docs](https://sklearn-utilities.readthedocs.io/en/latest/sklearn_utilities.html) for more information.
46+
4547
- `EstimatorWrapperBase`: base class for wrappers. Redirects all attributes which are not in the wrapper to the wrapped estimator.
4648
- `DataFrameWrapper`: tries to convert every estimator output to a pandas DataFrame or Series.
4749
- `FeatureUnionPandas`: a `FeatureUnion` that works with pandas DataFrames.
@@ -56,9 +58,10 @@ pip install sklearn-utilities
5658
- `RecursiveFitSubtractRegressor`: a regressor that recursively fits a regressor and subtracts the prediction from the target.
5759
- `SmartMultioutputEstimator`: a `MultiOutputEstimator` that supports tuple of arrays in `predict()` and supports pandas `Series` and `DataFrame`.
5860
- `until_event()`, `since_event()`: calculates the time since or until events (`Series[bool]`)
59-
- `ComposeVarEstimator`: compose mean and std/var estimators.
61+
- `ComposeVarEstimator`: composes mean and std/var estimators.
6062
- `DummyRegressorVar`: `DummyRegressor` that returns 1.0 for std/var.
6163
- `TransformedTargetRegressorVar`: `TransformedTargetRegressor` with std/var support.
64+
- `StandardScalerVar`: `StandardScaler` with std/var support.
6265

6366
### `sklearn_utilities.dataset`
6467

@@ -70,7 +73,8 @@ pip install sklearn-utilities
7073

7174
#### `sklearn_utilities.torch.skorch`
7275

73-
- `SkorchReshaper`, `SkorchCNNReshaper`: reshape X and y for `nn.Linear` and `nn.Conv1d/2d` respectively. (For `nn.Conv2d`, uses `np.sliding_window_view()`.)
76+
- `SkorchReshaper`, `SkorchCNNReshaper`: reshapes X and y for `nn.Linear` and `nn.Conv1d/2d` respectively. (For `nn.Conv2d`, uses `np.sliding_window_view()`.)
77+
- `AllowNaN`: wraps a loss module and assign 0 to y and y_hat for indices where y contains NaN in `forward()`..
7478

7579
## See also
7680

src/sklearn_utilities/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
ComposeVarEstimator,
2020
DummyRegressorVar,
2121
PipelineVar,
22+
StandardScalerVar,
2223
TransformedTargetEstimatorVar,
2324
)
2425
from .recursive_fit_subtract_regressor import RecursiveFitSubtractRegressor
@@ -45,4 +46,5 @@
4546
"DummyRegressorVar",
4647
"TransformedTargetEstimatorVar",
4748
"PipelineVar",
49+
"StandardScalerVar",
4850
]
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from .compose_var import ComposeVarEstimator
22
from .dummy_regressor import DummyRegressorVar
33
from .pipeline_var import PipelineVar
4+
from .standard_scaler_var import StandardScalerVar
45
from .transformed_target_estimator import TransformedTargetEstimatorVar
56

67
__all__ = [
78
"ComposeVarEstimator",
89
"DummyRegressorVar",
910
"PipelineVar",
1011
"TransformedTargetEstimatorVar",
12+
"StandardScalerVar",
1113
]

src/sklearn_utilities/torch/skorch/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
from .proba import (
2+
AlgebraicErrors,
3+
AllowNan,
24
AsymmetricLoss,
35
AsymmetricLosses,
46
LNErrors,
7+
LogCoshErrors,
58
SkorchCNNReshaperProba,
69
SkorchReshaperProba,
10+
XSigmoidErrors,
11+
XTanhErrors,
712
)
813
from .reshaper import SkorchCNNReshaper, SkorchReshaper
914

@@ -13,6 +18,11 @@
1318
"SkorchReshaperProba",
1419
"SkorchCNNReshaperProba",
1520
"LNErrors",
21+
"LogCoshErrors",
22+
"XSigmoidErrors",
23+
"XTanhErrors",
24+
"AlgebraicErrors",
25+
"AllowNan",
1626
"AsymmetricLoss",
1727
"AsymmetricLosses",
1828
"SkorchReshaperProba",

src/sklearn_utilities/torch/skorch/proba.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
from __future__ import annotations
22

3+
import math
34
from typing import Any, Generic, Literal, Sequence
45

56
import numpy as np
67
import torch
78
import torch.nn as nn
9+
import torch.nn.functional as F
810

911
from ...types import TX, TY, TEstimator
1012
from .reshaper import SkorchCNNReshaper, SkorchReshaper
@@ -64,6 +66,78 @@ def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
6466
return torch.abs(y_true - y_pred).pow(self.n)
6567

6668

69+
class LogCoshErrors(nn.Module):
70+
"""Log cosh errors.
71+
Loss = log(cosh(errors + eps))
72+
73+
See also
74+
--------
75+
https://datascience.stackexchange.com/questions/96271/logcoshloss-on-pytorch
76+
"""
77+
78+
def __init__(self, *, softplus: bool = True, eps: float | None = None) -> None:
79+
"""Returns log(cosh(errors)).
80+
81+
Parameters
82+
----------
83+
softplus : bool, optional
84+
If True, uses softplus to get stable results, by default True"""
85+
super().__init__()
86+
self.softplus = softplus
87+
self.eps = eps
88+
89+
def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
90+
x = y_pred - y_true
91+
if self.softplus:
92+
return x + F.softplus(-2.0 * x) - math.log(2.0)
93+
else:
94+
eps = self.eps or torch.finfo(x.dtype).eps
95+
return torch.log(torch.cosh(x + eps))
96+
97+
98+
class XTanhErrors(nn.Module):
99+
"""XTanh errors.
100+
Loss = x * tanh(x)
101+
102+
See also
103+
--------
104+
https://github.com/tuantle/regression-losses-pytorch
105+
"""
106+
107+
def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
108+
x = y_pred - y_true
109+
return x * torch.tanh(x)
110+
111+
112+
class XSigmoidErrors(nn.Module):
113+
"""XSigmoid errors.
114+
Loss = x * (2 * sigmoid(x) - 1)
115+
116+
See also
117+
--------
118+
https://github.com/tuantle/regression-losses-pytorch
119+
"""
120+
121+
def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
122+
x = y_pred - y_true
123+
return x * (2 * torch.sigmoid(x) - 1)
124+
125+
126+
class AlgebraicErrors(nn.Module):
127+
"""Algebraic errors.
128+
Loss = x^2 / sqrt(1 + x^2)
129+
130+
See also
131+
--------
132+
https://github.com/tuantle/regression-losses-pytorch
133+
"""
134+
135+
def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
136+
x = y_pred - y_true
137+
x2 = torch.pow(x, 2)
138+
return x2 / torch.sqrt(1 + x2)
139+
140+
67141
class AsymmetricLoss(nn.Module):
68142
def __init__(
69143
self,

0 commit comments

Comments
 (0)