问题
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