为日志定义boudned ufunc

2024-05-14 12:55:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试定义一个函数log_bounded,它与numpy的log对于正输入是一样的,但是对于非正输入它会给出一个很大的负数。我需要它是一个可以接受数组作为输入的ufunc。你知道吗

到目前为止,我已经:

def log_bounded(x,verysmall=np.exp(-100)):
    return np.log(np.maximum(x,verysmall))

这是可行的,负输入返回-100:

>>> log_bounded(2.72)
1.000631880307906
>>> log_bounded(-5)
-100.0

但我希望它返回一个更低的值,比如-10**10。我认为最理想的方法是检查x的值并直接返回低值,而不是记录接近零的值,例如

def log_bounded_if(x, verylow=-10**10):
    if x > 0:
        return np.log(x)
    else:
        return verylow

但是,这个函数不会对数组进行元素操作,因为if试图对整个数组运行一次。你知道吗

Scipy可以用scipy.maximum(scipy.log(x),verylow)完成这项工作,因为scipy.log在非正输入上的计算结果为负无穷大。但是,我需要使用numpy,因为它将与numba的autojit一起运行,而scipy似乎消除了速度优势。你知道吗


Tags: 函数numpylogreturnif定义defnp
1条回答
网友
1楼 · 发布于 2024-05-14 12:55:33

你可以通过logical indexing来完成。你知道吗

最小解:

import numpy as np

def log_bounded(x, verylow=-10**10):
    y = np.log(x)
    y[x <= 0] = verylow
    return y

print log_bounded(np.arange(-2, 3))

输出:[ -1.00000000e+10 -1.00000000e+10 -1.00000000e+10 0 6.93147181e-01]


更高级的选择:(同时处理标量;节省不必要的log计算)

import numpy as np

def log_bounded(x, verylow=-10**10):
    if np.isscalar(x):               # handle scalars as well
        if x > 0:
            y = np.log(x)
        else:
            y = verylow
    else:
        y = np.empty_like(x)
        y[x > 0] = np.log(x[x > 0])  # compute log only where needed
        y[x <= 0] = verylow
    return y

print log_bounded(-3), log_bounded(np.arange(-2, 3)), log_bounded(3)

输出:-10000000000 [-10000000000 -10000000000 -10000000000 0 0] 1.09861228867

相关问题 更多 >

    热门问题