2014-09-04 130 views
0

从这里随访: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 < 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循环都要经过每个值是固定的...但有什么办法将其纳入更快的代码?我的数组有成千上万的元素。

回答

2

该表达

​​3210

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

np.maximum(a - a_max, threshold) 

,以取代表达式(npnumpy。)

+0

现在我得到这个错误: 'OUT =日志(总和(EXP(np.minimum(一 - a_max, ) TypeError:sum()不带关键字参数' – user961627 2014-09-04 09:43:57

+0

您必须使用numpy函数:'np.log','np.sum'和'np.exp'。 – 2014-09-04 09:50:03