【问题标题】:Avoiding infinities in this numpy logsumexp calculation在这个 numpy logsumexp 计算中避免无穷大
【发布时间】:2014-09-04 15:57:25
【问题描述】:

Value error: truth value ambiguous 开始,我正在从这里编辑logsumexp 函数:https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18

原因是: 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

【问题讨论】:

    标签: python numpy infinity


    【解决方案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.minimum(a - a_max, threshold)), axis=0))
    

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

    maximum 是您想要的最大值。

    【讨论】:

    • 你的意思是,代替np.minimum()
    • @user961627 是的 - 我已经编辑了我的答案以包含一个可能的解决方案。
    • 我将 thresholdmaxthreshold 设置为 -sys.float_info.maxsys.float_info.max 收到此错误: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'
    • 听起来数组a 的某些元素可能是None。你能从数组中过滤掉这些元素吗?
    猜你喜欢
    • 2021-11-19
    • 2018-06-11
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多