python - 在 numpy 中使用 exp 和最小正 float128 避免下溢

标签 python numpy numerical-methods numerical-analysis underflow

我正在尝试计算以下比率: w(i)/(sum(w(j)) 其中 w 使用指数递减函数更新,即 w(i) = w(i) * exp(-k)k为正参数,所有数字均为非负数。 然后将该比率用于公式(乘以一个常数并添加另一个常数)。不出所料,我很快就遇到了下溢问题。

我想这种情况经常发生,但有人可以给我一些关于如何处理这种情况的引用吗?我没有找到合适的转换,所以我尝试做的一件事是将一些最小正数设置为安全阈值,但我没有找到哪个是最小正 float (我在 numpy.float128< 中表示数字)。我怎样才能在我的机器上得到最小的这样的数字? 代码如下所示:

w = np.ones(n, dtype='float128')
lt = np.ones(n)
for t in range(T):
    p = (1-k) * w / w.sum() + (k/n)
    # Process a subset of the n elements, call it set I, j is some range()
    for i in I: 
        s = p[list(j[i])].sum()
        lt /= s
        w[s] *= np.exp(-k * lt)

其中 k 是 (0,1) 中的某个常数,n 是数组的长度

最佳答案

当处理指数级的小数字时,通常最好在对数空间中工作。例如,log(w*exp(-k)) = log(w) - k ,除非 k 本身呈指数级大或 w 为零,否则不会有任何上溢/下溢问题。而且,如果w为零,numpy 将正确返回 -inf .然后,在求和时,您可以分解出最大项:

log_w = np.log(w) - k
max_log_w = np.max(log_w)
# Individual terms in the following may underflow, but then they wouldn't
# contribute to the sum anyways.
log_sum_w = max_log_w + np.log(np.sum(np.exp(log_w - max_log_w)))
log_ratio = log_w - log_sum_w

这可能不是您想要的,因为您可以分解出 k完全(假设它是一个常量而不是一个数组),但它应该让你上路。

Scikit-learnextmath.logsumexp 实现类似的事情, 但与上述基本相同。

关于python - 在 numpy 中使用 exp 和最小正 float128 避免下溢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33434032/

相关文章:

python:几何布朗运动模拟

python - 拆分字符串而不删除 python 中的定界符

python - 从数据集*编辑*中标准化普朗克定律的 curve_fit 中的值

python - 我不明白第二个支架是如何工作的

python - 如何在 python 中权衡具有高斯分布的 2 个变量的函数?

c - 数值微分方程求解器算法意外出现段错误

python - 不同数量的 map task (1、2、4 ..)之间没有性能差异

python - 如何通过 myplayer 将视频嵌入到 QWidget 框架中?

pandas - 如何从频率表创建箱线图

matlab - MATLAB 中的高斯-赛德尔法