值错误:真值模糊
接着之前的内容:Python中的条件计算
我正在编辑这一行:
out = log(sum(exp(a - a_max), axis=0))
来自第85行:https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18
改成这样:
out = log(sum(exp(threshold if a - a_max < threshold else a - a_max), axis = 0))
但是我遇到了以下错误:
out = log(sum(exp(threshold if a - a_max < threshold else a - a_max), axis=0)) ValueError: 数组中有多个元素时的真值是模糊的。请使用 a.any() 或 a.all()
我从这个回答中看到,可以通过使用for循环来逐个处理每个值来修复这个错误……但是有没有办法把它整合进更快的代码里?我的数组有成千上万个元素。
1 个回答
2
这个表达式
threshold if a - a_max < threshold else a - a_max
和 max(a - a_max, threshold)
是一样的。如果 a
是一个 numpy 数组,那么表达式 a - a_max < threshold
也是一个 numpy 数组。你不能直接把 numpy 数组用作 Python 中 if-else
三元运算符的条件表达式,但你可以用 np.maximum
来逐个计算最大值。所以你可以用下面的表达式来替代它:
np.maximum(a - a_max, threshold)
(np
是 numpy
的缩写.)