RuntimeWarning: overflow encountered in exp

本文详细解析了在实现逻辑斯蒂回归时遇到的栈溢出错误,并提供了解决方案。通过优化sigmoid函数,避免了极大数值导致的溢出,同时解决了数组元素的真值判断问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用逻辑斯蒂回归时,报了栈溢出错误。

def logistic(x):
    return 1.0 / (1 + np.exp(-x))

RuntimeWarning: overflow encountered in exp return 1.0 / (1 + np.exp(-x))

参照网上的做法,对x做判断,

def logistic(x):
    if x>=0: #对sigmoid函数优化,避免出现极大的数据溢出
        return 1.0 / (1 + np.exp(-x))
    else:
        return np.exp(x)/(1+np.exp(x))

此时又报了另一个错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

x的值不止一个,需要对所有的x都进行判断,按照报错后给的提示修改即可。

def logistic(x):
    if np.all(x>=0): #对sigmoid函数优化,避免出现极大的数据溢出
        return 1.0 / (1 + np.exp(-x))
    else:
        return np.exp(x)/(1+np.exp(x))

all,any用法

>>> help(all)
all(...)
    all(iterable) -> bool
    Return True if bool(x) is True for all values x in the iterable.

>>> help(any)
any(...)
    any(iterable) -> bool
    Return True if bool(x) is True for any x in the iterable.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值