Download code/ampd/evaluation/decision.py from fryabcfry/cs4486-amp-pd-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/fryabcfry/cs4486-amp-pd-checkpoints/resolve/main/code/ampd/evaluation/decision.py
- Command line
-
hf download hf://fryabcfry/cs4486-amp-pd-checkpoints/code/ampd/evaluation/decision.py
-
curl -L -o decision.py https://huggingface.co/fryabcfry/cs4486-amp-pd-checkpoints/resolve/main/code/ampd/evaluation/decision.py
1.4 kB
| """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}") | |