【问题标题】:Value error: truth value ambiguous值错误:真值不明确
【发布时间】:2014-10-28 23:50:10
【问题描述】:

从这里跟进:Conditional calculation in 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 &lt; threshold else a - a_max), axis=0)) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我可以从this 的回答中看到,可以使用 for 循环遍历每个值来修复错误...但是有没有办法将它合并到更快的代码中?我的数组有数以万计的元素。

【问题讨论】:

    标签: python numpy conditional


    【解决方案1】:

    这个表达式

    threshold if a - a_max < threshold else a - a_max
    

    max(a - a_max, threshold) 相同。如果a 是一个numpy 数组,那么表达式a - a_max &lt; threshold 也是如此。您不能使用 numpy 数组作为 Python if-else 三元运算符中的条件表达式,但您可以使用 np.maximum 按元素计算最大值。所以你应该能够用

    替换那个表达式
    np.maximum(a - a_max, threshold)
    

    npnumpy。)

    【讨论】:

    • 现在我得到这个错误:out = log(sum(exp( np.minimum(a - a_max, threshold)), axis=0)) TypeError: sum() takes no keyword arguments
    • 您必须使用 numpy 函数:np.lognp.sumnp.exp
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 2018-01-11
    • 2016-01-23
    • 2018-07-06
    • 2021-08-13
    • 2019-08-21
    • 2019-07-08
    • 2016-07-11
    相关资源
    最近更新 更多