运行时错误:操作在 f 字符串语句中没有标识

vah*_*ero 3 python torch f-string torchvision

我正在评估 pytorch 模型。它以以下方式给出结果

results = model(batch)
# results is a list of dictionaries with 'boxes', 'labels' and 'scores' keys and torch tensor values
Run Code Online (Sandbox Code Playgroud)

然后我尝试打印一些值来检查发生了什么

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
    )
)
Run Code Online (Sandbox Code Playgroud)

这会导致错误

Exception has occurred: RuntimeError: operation does not have identity

让事情变得更加混乱的是,print有时只会失败。为什么会失败?

Shi*_*hir 6

我的代码中也有同样的问题。事实证明,当尝试访问空张量的属性(例如形状、平均值等)时,结果是无恒等异常。

重现代码:

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

Run Code Online (Sandbox Code Playgroud)

弄清楚为什么你的代码返回空张量,这将解决问题。