为什么result的结果torch.nn.functional.mse_loss(x1,x2)
与直接计算MSE不同?
我要重现的测试代码:
import torch
import numpy as np
# Think of x1 as predicted 2D coordinates and x2 of ground truth
x1 = torch.rand(10,2)
x2 = torch.rand(10,2)
mse_torch = torch.nn.functional.mse_loss(x1,x2)
print(mse_torch) # 0.1557
mse_direct = torch.nn.functional.pairwise_distance(x1,x2).square().mean()
print(mse_direct) # 0.3314
mse_manual = 0
for i in range(len(x1)) :
mse_manual += np.square(np.linalg.norm(x1[i]-x2[i])) / len(x1)
print(mse_manual) # 0.3314
正如我们所看到的,torch 的结果mse_loss
是0.1557
,与手动 MSE 计算的结果不同0.3314
。
事实上,结果mse_loss
恰好等于直接结果乘以点的维度(此处为 2)。
那是怎么回事?