File size: 1,402 Bytes
04ae9bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | """Decision-theoretic point prediction for SMAPE+1."""
from __future__ import annotations
import torch
def smape_loss_matrix(n_classes: int, device=None, dtype=torch.float32) -> torch.Tensor:
"""Loss[y, c] = |y-c| / ((|y|+|c|)/2 + 1)."""
y = torch.arange(int(n_classes), device=device, dtype=dtype)
c = y.view(1, -1)
y = y.view(-1, 1)
return (y - c).abs() / ((y.abs() + c.abs()) / 2.0 + 1.0)
def smape_optimal_point(probs: torch.Tensor) -> torch.Tensor:
"""Return argmin_c E[SMAPE+1(c)] for probs (..., C)."""
if probs.dim() < 2:
raise ValueError("probs must have at least 2 dimensions")
C = probs.shape[-1]
L = smape_loss_matrix(C, device=probs.device, dtype=probs.dtype)
expected = torch.matmul(probs, L)
return expected.argmin(dim=-1).to(probs.dtype)
def expected_smape(probs: torch.Tensor) -> torch.Tensor:
C = probs.shape[-1]
L = smape_loss_matrix(C, device=probs.device, dtype=probs.dtype)
expected = torch.matmul(probs, L)
return expected.min(dim=-1).values
def point_from_output(output: torch.Tensor, output_type: str = "regression", n_classes: int = 87) -> torch.Tensor:
if output_type == "regression":
return output
if output_type == "distribution":
probs = torch.softmax(output, dim=-1)
return smape_optimal_point(probs)
raise ValueError(f"Unknown output_type: {output_type}")
|