Skip to content

Commit

Permalink
add brainpy.math.surrogate..Surrogate (#638)
Browse files Browse the repository at this point in the history
* add `brainpy.math.Surrogate`

* fix

* Update _event_matvec.py

* Update _event_matvec.py

* Update _event_matvec.py

---------

Co-authored-by: He Sichao <[email protected]>
  • Loading branch information
chaoming0625 and Routhleck authored Mar 1, 2024
1 parent 8460a1d commit 3826c54
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
27 changes: 25 additions & 2 deletions brainpy/_src/math/surrogate/_one_input_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,30 @@ def _as_jax(x):


class Surrogate(object):
"""The base surrograte gradient function."""
"""The base surrograte gradient function.
To customize a surrogate gradient function, you can inherit this class and
implement the `surrogate_fun` and `surrogate_grad` methods.
Examples
--------
>>> import brainpy as bp
>>> import brainpy.math as bm
>>> import jax.numpy as jnp
>>> class MySurrogate(bm.Surrogate):
... def __init__(self, alpha=1.):
... super().__init__()
... self.alpha = alpha
...
... def surrogate_fun(self, x):
... return jnp.sin(x) * self.alpha
...
... def surrogate_grad(self, x):
... return jnp.cos(x) * self.alpha
"""

def __call__(self, x):
x = _as_jax(x)
Expand Down Expand Up @@ -123,7 +146,7 @@ def __init__(self, alpha: float = 4.):
self.alpha = alpha

def surrogate_fun(self, x):
return sci.special.expit(x)
return sci.special.expit(self.alpha * x)

def surrogate_grad(self, x):
sgax = sci.special.expit(x * self.alpha)
Expand Down
3 changes: 2 additions & 1 deletion brainpy/math/surrogate.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-



from brainpy._src.math.surrogate._one_input_new import (
Surrogate,

Sigmoid,
sigmoid as sigmoid,

Expand Down

0 comments on commit 3826c54

Please sign in to comment.