2014-09-04 99 views
0

Value error: truth value ambiguous跟进,我从这里编辑logsumexp功能:https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18这个numpy的logsumexp计算避免无穷

的原因是:1。 我想选择最大值自己,它并不总是只是数组的最大值 2.我想提出一个条件,以确保从每个元素中减去最大值后的差值不低于某个阈值。

这是我最终的代码。它没有什么不对 - 除了有时候它仍然会返回无限状态!

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 

回答

1

可以使用np.clip到结合的阵列的最大和最小值:

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

在这个例子中,值大于7 7被封端;值小于3设置为3

如果我理解正确的代码,您可能希望与

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

其中maximum是你想要的最大值替换

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

+0

你的意思是代替'np.minimum()'吗? – user961627 2014-09-04 16:06:41

+0

@ user961627是 - 我编辑了我的答案以包含可能的解决方案。 – 2014-09-04 16:09:55

+0

我将'threshold'和'maxthreshold'设置为'-sys.float_info.max'和'sys.float_info.max'得到这个错误: 'out = np.log(np.sum(b * np.exp(np ) TypeError:不支持的操作数类型为 - :'float'和'NoneType' – user961627 2014-09-04 18:16:37