问题描述
我正在评估一个 pytorch 模型。它以下列方式给出结果
results = model(batch)
# results is a list of dictionaries with 'Boxes','labels' and 'scores' keys and torch tensor values
然后我尝试打印一些值来检查发生了什么
print(
(
f"{results[0]['Boxes'].shape[0]}\n" # Returns how many Boxes there is
f"{results[0]['scores'].mean()}" # Mean credibility score of the Boxes
)
)
这会导致错误
Exception has occurred: RuntimeError: operation does not have identity
为了让事情变得更加混乱,print
只是在某些时候失败。为什么会失败?
解决方法
我在我的代码中遇到了同样的问题。事实证明,当尝试访问空张量的属性(例如形状、均值等)时,结果是没有身份异常。
重现代码:
import torch
a = torch.arange(12)
mask = a > 100
b = a[mask] # tensor([],dtype=torch.int64) -- empty tensor
b.min() # yields "RuntimeError: operation does not have an identity."
弄清楚为什么你的代码返回空张量,这将解决问题。