Value error: truth value ambiguous

懵懂的女人 提交于 2019-12-25 03:49:13

问题


Following up from here: Conditional calculation in python

I'm editing this line:

 out = log(sum(exp(a - a_max), axis=0))

from line 85 here: https://github.com/scipy/scipy/blob/v0.14.0/scipy/misc/common.py#L18

to this:

out = log(sum(exp(threshold if a - a_max < threshold else a - a_max), axis = 0))

But I'm getting the following error:

out = log(sum(exp(threshold if a - a_max < 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()

I can see from this answer that the error can be fixed using a for-loop to go through each value... but is there any way to incorporate it into quicker code? My arrays have tens of thousands of elements.


回答1:


This expression

threshold if a - a_max < threshold else a - a_max

is the same as max(a - a_max, threshold). If a is a numpy array, then so is the expression a - a_max < threshold. You can't use a numpy array as the conditional expression in the Python if-else ternary operator, but you can compute element-wise the maximum using np.maximum. So you should be able to replace that expression with

np.maximum(a - a_max, threshold)

(np is numpy.)



来源:https://stackoverflow.com/questions/25661922/value-error-truth-value-ambiguous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!