2014-09-04 98 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