Skip to content

Commit

Permalink
avoided overflow in exp computation during fuzzifier fit
Browse files Browse the repository at this point in the history
  • Loading branch information
dariomalchiodi committed Nov 13, 2024
1 parent d268c9f commit d2615da
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
2 changes: 1 addition & 1 deletion mulearn/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = '1.0.7'
__version__ = '1.0.8'


import copy
Expand Down
20 changes: 13 additions & 7 deletions mulearn/fuzzifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ def _safe_exp(r):
except FloatingPointError:
return 1

def exp_clip(a):
return np.exp(a) if a < 0 else 1
# idx = (a < 0)
# a[idx] = 1
# a[~idx] = np.exp(a[~idx])
# return a


class Fuzzifier:
"""Base class for fuzzifiers.
Expand Down Expand Up @@ -402,9 +409,9 @@ def fit(self, squared_R, mu, squared_radius):

if self.profile == "fixed":
def r2_to_mu(R_2, r_2_1):
return [np.clip(_safe_exp( \
-np.log(2) * (r_2 - r_2_1) / (squared_radius - r_2_1)),
0, 1) for r_2 in R_2]
return [exp_clip(-np.log(2) * \
(r_2 - r_2_1) / (squared_radius - r_2_1))
for r_2 in R_2]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
[r_2_1_opt], _ = curve_fit(r2_to_mu, squared_R, mu,
Expand All @@ -416,8 +423,7 @@ def r2_to_mu(R_2, r_2_1):

elif self.profile == "infer":
def r2_to_mu(R_2, r_2_1, s):
return [np.clip(_safe_exp(-(r_2 - r_2_1) / s), 0, 1)
for r_2 in R_2]
return [exp_clip(-(r_2 - r_2_1) / s) for r_2 in R_2]

try:
p_opt, _ = curve_fit(r2_to_mu, squared_R, mu,
Expand All @@ -438,8 +444,8 @@ def r2_to_mu(R_2, r_2_1):
inner = [r_2 - r_2_1 for r_2 in squared_R if r_2 > r_2_1]
if len(inner) > 0:
q = np.percentile(inner, 100 * alpha)
return [np.clip(_safe_exp(np.log(alpha) / q * (r_2 - r_2_1)),
0, 1) for r_2 in R_2]
return [exp_clip(np.log(alpha) / q * (r_2 - r_2_1))
for r_2 in R_2]
else:
# all points have within the sphere -> unit membership
return [1] * len(R_2)
Expand Down

0 comments on commit d2615da

Please sign in to comment.