我手动计算 R^2,并将结果与没有多输出的 torcheval.metrics.regression.r2_score 进行比较,但我没有绑定总和平方计算,因此手动 R^2 与 torcheval 不同:
手动方法:
#Manual approach code
ss_total = torch.sum((var1 - torch.mean(var1)) ** 2)
ss_residual = torch.sum((var1 - var2) ** 2)
r2 = 1 - (ss_residual / ss_total)
print("R^2 manual",r2, "my ss_total", ss_total, "ss_residual", ss_residual)
#R^2 manual tensor(-1.4128, device='cuda:0') my ss_total tensor(3.7081, device='cuda:0') ss_residual tensor(8.9471, device='cuda:0')
Torcheval.metrics 方法tss 公式文档无需多输出:
sum_squared_obs = torch.sum((actual - torch.mean(actual)) ** 2)
tss sum squared calculation = sum_squared_obs - torch.square(sum_obs) / num_obs
r_squared = 1 - (rss / tss)
#torcheval.metrics.regression.r2_score tested in script
metric = R2Score(device=device)
update = metric.update(var1, var2)
print("sum_squared_residual",update.sum_squared_residual)
print("sum_obs",update.sum_obs)
print("torch.square(sum_obs)",torch.square(update.sum_obs))
print("num_obs",len(var1))
print("sum_squared_obs",update.sum_squared_obs)
r2_py = metric.compute()
print("R^2 pytorch",r2_py)
#sum_squared_residual tensor(8.9471, device='cuda:0')
#sum_obs tensor(-29.9617, device='cuda:0')
#torch.square(sum_obs) tensor(897.7044, device='cuda:0')
#num_obs 64
#sum_squared_obs tensor(22.2245, device='cuda:0')
#R^2 pytorch tensor(-0.0914, device='cuda:0')
#R^2 var_weight pytorch tensor(-0.0914, device='cuda:0')
我无法解开 tss。
有人能解释一下这两种方法有什么区别吗?
我已经在 Excel 中保存了实际值和预测值,并使用这两种方法计算 R^2。