RuntimeError: Operation does not have identity in f-string statement

RuntimeError: Operation does not have identity in f-string statement

我正在评估一个 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."

找出你的代码 returns 空张量的原因,这将解决问题。