值错误:真值不明确 [英] Value error: truth value ambiguous

查看:106
本文介绍了值错误:真值不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这里开始: Python中的条件计算



我正在编辑以下行:

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

从85行开始:> https://github.com/scipy/scipy/blob/v0.14.0/ scipy / misc / common.py#L18



为此:

  out = log(sum(exp(阈值,如果a-a_max <阈值,否则a-a_max),轴= 0))

但是出现以下错误:



out = log(sum(exp(threshold如果a-a_max <阈值,否则a-a_max),轴= 0))ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()



我可以从回答,可以使用for循环遍历每个值来修复错误...但是有任何方法可以合并它变成更快的代码?我的数组有成千上万的元素。

解决方案

此表达式



<$如果a-a_max< p $ p> 阈值阈值a-a_max

max(a-a_max,阈值)。如果 a 是一个numpy数组,则表达式 a-a_max<阈值。在Python if-else 三元运算符中,不能将numpy数组用作条件表达式,但是可以使用逐元素地计算最大值np.maximum 。因此,您应该可以将表达式替换为

  np.maximum(a-a_max,threshold)

np numpy 。)


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.

解决方案

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.)

这篇关于值错误:真值不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆