Skip to content

Commit 532e701

Browse files
Preserve sigmoid behavior for infinite inputs
1 parent 86c5b64 commit 532e701

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

‎maths/sigmoid.py‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
44
The sigmoid function maps real-valued inputs to the interval (0, 1).
55
Its implementation uses separate formulas for positive and negative inputs
6-
to avoid overflow when evaluating large-magnitude values.
6+
to avoid overflow warnings when evaluating large-magnitude values.
77
88
Script inspired from its corresponding Wikipedia article:
99
https://en.wikipedia.org/wiki/Sigmoid_function
@@ -24,7 +24,7 @@ def sigmoid(vector: np.ndarray) -> np.ndarray:
2424
2525
Raises:
2626
ValueError: If the input cannot be converted to a float array or
27-
contains non-finite values.
27+
contains NaN values.
2828
2929
Examples:
3030
>>> sigmoid(np.array([-1.0, 1.0, 2.0]))
@@ -37,27 +37,31 @@ def sigmoid(vector: np.ndarray) -> np.ndarray:
3737
>>> sigmoid(np.array([-1000.0, 1000.0]))
3838
array([0., 1.])
3939
40+
Infinite values are supported:
41+
>>> sigmoid(np.array([np.inf, -np.inf]))
42+
array([1., 0.])
43+
4044
Scalar arrays are supported:
4145
>>> sigmoid(np.array(0.0))
4246
array(0.5)
4347
44-
Non-numeric and non-finite inputs are rejected:
48+
Non-numeric and NaN inputs are rejected:
4549
>>> sigmoid(np.array(["invalid"]))
4650
Traceback (most recent call last):
4751
...
4852
ValueError: sigmoid input must be numeric
49-
>>> sigmoid(np.array([np.inf]))
53+
>>> sigmoid(np.array([np.nan]))
5054
Traceback (most recent call last):
5155
...
52-
ValueError: sigmoid input must contain only finite values
56+
ValueError: sigmoid input must not contain NaN values
5357
"""
5458
try:
5559
vector = np.asarray(vector, dtype=float)
5660
except (TypeError, ValueError) as exc:
5761
raise ValueError("sigmoid input must be numeric") from exc
5862

59-
if not np.all(np.isfinite(vector)):
60-
raise ValueError("sigmoid input must contain only finite values")
63+
if np.any(np.isnan(vector)):
64+
raise ValueError("sigmoid input must not contain NaN values")
6165

6266
result = np.empty_like(vector)
6367
positive_mask = vector >= 0

0 commit comments

Comments
 (0)