File size: 2,119 Bytes
10979b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from __future__ import annotations

import numpy as np
import torch

from gmnet.evaluation.corruptions import apply_corruption
from gmnet.evaluation.metrics import (
    classification_metrics,
    expected_calibration_error,
    paired_hierarchical_bootstrap,
)


def test_noise_is_deterministic_per_sample() -> None:
    image = torch.full((3, 32, 32), 0.5)
    first = apply_corruption(image, "gaussian_noise", 17)
    second = apply_corruption(image, "gaussian_noise", 17)
    different = apply_corruption(image, "gaussian_noise", 18)
    assert torch.equal(first, second)
    assert not torch.equal(first, different)


def test_shift_has_fixed_zero_filled_geometry() -> None:
    image = torch.zeros(3, 32, 32)
    image[:, 1, 1] = 1.0
    shifted = apply_corruption(image, "shift_2px", 0)
    assert torch.equal(shifted[:, 3, 3], torch.ones(3))
    assert shifted.sum().item() == 3.0


def test_classification_metrics_and_ece() -> None:
    metrics = classification_metrics(
        np.array([1, 0, 1, 0]),
        np.array([1, 1, 1, 0]),
        np.array([0.1, 1.0, 0.2, 2.0]),
        np.array([0.9, 0.8, 0.7, 0.2]),
        ece_bins=2,
    )
    assert metrics["top1"] == 50.0
    assert metrics["top5"] == 75.0
    assert metrics["nll"] == 0.825
    assert expected_calibration_error(np.array([1.0]), np.array([1])) == 0.0


def test_paired_bootstrap_preserves_exact_constant_difference() -> None:
    reference = np.zeros((3, 6, 20), dtype=np.float64)
    candidate = np.ones_like(reference)
    rows = paired_hierarchical_bootstrap(
        candidate,
        reference,
        statistics={
            "clean_top1": "clean_top1",
            "mean": "mean_corruption_top1",
            "raw": "clean_raw_mean",
        },
        samples=100,
        seed=3,
    )
    scaled = [row for row in rows if row["metric"] != "raw"]
    raw = next(row for row in rows if row["metric"] == "raw")
    assert all(row["difference"] == 100.0 for row in scaled)
    assert all(row["ci_low"] == 100.0 and row["ci_high"] == 100.0 for row in scaled)
    assert raw["difference"] == raw["ci_low"] == raw["ci_high"] == 1.0