0

Following up from Value error: truth value ambiguous, I'm editing the logsumexp function from here: https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18

The reason is because: 1. I want to select the maximum value myself, it's not always just the maximum of the array 2. I want to put a condition to ensure that the difference after subtracting the maximum from each element doesn't go below a certain threshold.

This is my final code. There's nothing wrong with it - except that it still returns inifinities sometimes!

def mylogsumexp(self, a, is_class, maxaj=None, axis=None, b=None):
        threshold = -sys.float_info.max         
        a = asarray(a)
        if axis is None:
            a = a.ravel()
        else:
            a = rollaxis(a, axis)

        if is_class == 1:
            a_max = a.max(axis=0)
        else:
            a_max = maxaj  
        if b is not None:
            b = asarray(b)
            if axis is None:
                b = b.ravel()
            else:
                b = rollaxis(b, axis)
            #out = log(sum(b * exp(threshold if a - a_max < threshold else a - a_max), axis=0))
            out = np.log(np.sum(b * np.exp( np.minimum(a - a_max, threshold)), axis=0))

        else:
            out = np.log(np.sum(np.exp( np.minimum(a - a_max, threshold)), axis=0))
        out += a_max
Community
  • 1
  • 1
user961627
  • 12,379
  • 42
  • 136
  • 210

1 Answers1

1

You can use np.clip to bound the maximum and minimum values of an array:

>>> arr = np.arange(10)
>>> np.clip(arr, 3, 7)
array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

In this example, values greater than 7 are capped at 7; values less than 3 are set to 3.

If I've interpreted your code correctly, you might want to replace

out = np.log(np.sum(b * np.exp( np.minimum(a - a_max, threshold)), axis=0))

with

out = np.log(np.sum(b * np.exp( np.clip(a - a_max, threshold, maximum)), axis=0))

where maximum is your desired maximum value.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • do you mean, in place of `np.minimum()`? – user961627 Sep 04 '14 at 16:06
  • @user961627 yes - I've edited my answer to include a possible solution. – Alex Riley Sep 04 '14 at 16:09
  • I set `threshold` and `maxthreshold` to `-sys.float_info.max` and `sys.float_info.max` got this error: `out = np.log(np.sum(b * np.exp( np.clip(a - a_max, threshold, maxthreshold)), axis=0)) TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'` – user961627 Sep 04 '14 at 18:16
  • Sounds like some of the elements of array `a` might be `None`. Are you able to filter these elements out of the array? – Alex Riley Sep 04 '14 at 19:13