我有两个任意形状的张量,有几个维。
我想要计算predicted_tensor中接近目标张量值的值的数目。
对于for循环,应该是这样的:
targets = torch.flatten(target_tensor)
predicted = torch.flatten(predicted_tensor)
correct_values = 0
tolerance = 0.1
for i, prediction in enumerate(predicted):
target = targets[i]
if (target - tolerance < prediction < target + tolerance):
correct_values =+ 1
然而,对于性能来说,for循环并不是一个好主意。
我在找一个矢量化的解。我试过:
torch.sum(target - tolerance < prediction < target + tolerance)
但我得到了:
RuntimeError: Boolean value of Tensor with more than one value is ambiguous
在朱莉娅,它只是添加一个点,以精确地说,它是元素。
对于如何用一个简短的矢量化解决方案来实现PyTorch,有什么想法吗?
谢谢
发布于 2022-02-20 06:11:58
我想你是在找torch.isclose
correct_values = torch.isclose(prediction, target, atol=tolerance, rtol=0).sum()
https://stackoverflow.com/questions/71195131
复制相似问题