python-numpy-ValueError: The truth value of an array with more than one element is ambiguous.

一、问题背景

作者本人想要测试一下图片数据集的RGBA通道模式下的A通道的数值, 看是不是所有图片的不透明度都是1。

于是我用了下面的代码进行测试:其中train_dataset的第1维长度为2,分别是包括了batch_size个图片的特征和对应的labels;而图片特征对应的ndarray的shape是(16,224,224,4),分别对应batch_size,height,weight,RGBA。

第一个方法,使用!=进行测试,警报【ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()】。

这个警报为什么存在?因为生成的是一个包括真假boolean值的数组,无法通过一个数组来判别真假,只能用数组中的某一个元素来判别真假,所以编译器建议你用any()或all()来处理。

第二个方法,使用python自带的any()进行测试:又报错了,这是为啥呢?这一次的测试是我最懵逼的一次,为啥也会报错呢?不明白原因,所以我进行了本文第二部分的实验。

for i,data in enumerate(train_dataset.as_numpy_iterator()):
    if i < 2:
        # if data[0][:,:,:,3] != 1:
        #     print(data[0][:,:,:,3])
        print(any(data[0][:,:,:,3] != 1))  # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
        # print((data[0][:,:,:,3] != 1).any())
        # print(data[0][:,:,:,3])
        print(data[0].shape)
        print(dir(data))
        print(data.__len__())

第三个方法, 使用ndarray的any()方法进行测试:这次是正常的。两个batch的图片,得到的不透明度值,全部都是1,所以都返回了False。

for i,data in enumerate(train_dataset.as_numpy_iterator()):
    if i < 2:
        # if data[0][:,:,:,3] != 1:
        #     print(data[0][:,:,:,3])
        # print(any(data[0][:,:,:,3] != 1))
        print((data[0][:,:,:,3] != 1).any())
        # print(data[0][:,:,:,3])
        print(data[0].shape)
        print(dir(data))
        print(data.__len__())
        
# False
# (16, 224, 224, 4)
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
# 2
# False
# (16, 224, 224, 4)
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
# 2

二、解决方法

下面给出我做实验的代码:

import numpy as np

list1 = [[1,2],[3,4]]
list2 = [1,2,3,4]
arr1 = np.array([1,2,3,4])
arr2 = np.array([[1,2],[3,4]])

print(any(list1))
print(any(list2))  # 对于python内置的数据类型,不管是几个维度,都是允许用any()快速进行判断的
print(any(arr1))  # 一维的ndarray允许使用Python内置的any()函数进行判断,如果是多维的数组,就出出现下面的错误
print(any(arr2))  # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


# True
# True
# True

 

通过上面的实验可以看出,这个错误什么时候会发生?

第一种是用一个数组来判断真假,第二种是用Python自带的any()或all()来判断多维数组的真假。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用np.where函数时,如果传入的数组具有多个元素,会出现ValueError: The truth value of an array with more than one element is ambiguous的错误。这个错误是因为在条件判断时,出现了多个元素的真值无法确定的情况。为了解决这个问题,可以使用np.any()或np.all()方法来判断数组的真值。np.any()方法用于判断数组中是否存在至少一个True值,而np.all()方法用于判断数组中的所有值是否都为True。通过使用这些方法,可以避免出现ValueError错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python-numpy-ValueError: The truth value of an array with more than one element is ambiguous.](https://blog.csdn.net/PSpiritV/article/details/124339801)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [使用numpy遇到ValueError: The truth value of an array with more than one element is ambiguous](https://blog.csdn.net/weixin_45370422/article/details/122247903)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值