Commit 8606c33
authored
⚡️ Speed up function
Here is an optimized version of your `sigmoid_stable` function. The performance bottleneck is due to repeated calls to `np.exp(x)` within the `np.where` function, causing unnecessary recomputation over potentially large arrays.
We'll precompute `exp_x = np.exp(x)` and `exp_neg_x = np.exp(-x)` **outside** of `np.where` to avoid recomputation and improve cache use. This significantly reduces redundant computation for both branches of the `np.where`.
**Explanation of Changes:**
- Precompute both `exp_neg_x` and `exp_x` out of `np.where` to avoid duplicate calculations.
- This reduces two extra expensive `np.exp` calls down to one each, regardless of input.
This will make the function significantly faster, especially on large arrays. The output is mathematically identical.sigmoid_stable by 26%1 parent 8947ec9 commit 8606c33
1 file changed
+4
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
6 | 9 | | |
7 | 10 | | |
8 | 11 | | |
| |||
0 commit comments