当前位置:网站首页>【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous

【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous

2022-07-05 09:06:00 aelum

Case 1

Will contain Two or more The Boolean tensor of is used in if Judging conditions :

a = torch.tensor([True, False])
if a:
    pass

One of the possible reasons for this error is to judge a Not for None, At this time, it should be changed to the following statement

if a is not None:

It should be noted that , If a Contains only one Boolean value , Then the judgment will not be wrong :

a = torch.tensor([True])
if a:
    print(1)
# 1

Case 2

When using cross entropy loss Not instantiated first

inputs = torch.randn(6, 4)
target = torch.randint(4, (6, ))
loss = nn.CrossEntropyLoss(inputs, target)

The loss should be calculated after instantiation :

criterion = nn.CrossEntropyLoss()
loss = criterion(inputs, target)

Case 3

Yes, it contains Two or more The Boolean tensor of performs orandnot This kind of operation :

a = torch.tensor([True, False])
b = torch.tensor([False, True])
"""  The following three operations will report errors  """
print(a or b)
print(a and b)
print(not a)

It should be noted that , If a and b All contain only one Boolean value , There will be no mistakes :

a = torch.tensor([True])
b = torch.tensor([False])
print(a or b)
# tensor([True])
print(a and b)
# tensor([False])
print(not a)
# False
原网站

版权声明
本文为[aelum]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050900554147.html