Newer
Older
TIASJudgeModel / tests / evaluation / test_metrics_top_k.py
"""top-k の正解率のテスト(SPEC_02「評価の出し方」).

- `top_k` はスコアの上位 1 個・2 個に正解が入っている割合(全体とクラス別)
- top-1 は accuracy と,クラス別の top-1 はクラス別 recall と一致する
- スコアは順位だけを使う(確率でなくてよい)
- クラス別は正解に現れるクラスだけを出す

期待値は手計算した既知の入力から求める.
"""

from __future__ import annotations

import numpy as np
import pytest

from tias_judge_model.data.classes import CLASS_SLUGS, NUM_CLASSES
from tias_judge_model.evaluation.metrics import (
    aggregate_folds,
    classification_metrics,
    subset_metrics,
    top_k_metrics,
)

PALE, LIGHT_RED, RED, DARK_RED, PURPLE = range(5)

# 各行の順位(手で確かめられるように並べた)
Y_TRUE = np.array([PALE, PALE, LIGHT_RED, RED, RED, PURPLE])
SCORES = np.array(
    [
        [0.9, 0.05, 0.03, 0.01, 0.01],  # 正解 pale は 1 位
        [0.3, 0.4, 0.2, 0.05, 0.05],  # 正解 pale は 2 位
        [0.5, 0.1, 0.3, 0.05, 0.05],  # 正解 light_red は 3 位
        [0.1, 0.2, 0.6, 0.05, 0.05],  # 正解 red は 1 位
        [0.2, 0.5, 0.25, 0.03, 0.02],  # 正解 red は 2 位
        [0.1, 0.4, 0.3, 0.15, 0.05],  # 正解 purple は 5 位
    ]
)


def test_top_k_overall_matches_hand_calculation() -> None:
    result = top_k_metrics(Y_TRUE, SCORES)
    assert result["top1"] == pytest.approx(2 / 6)
    assert result["top2"] == pytest.approx(4 / 6)


def test_top_k_per_class_matches_hand_calculation() -> None:
    per_class = top_k_metrics(Y_TRUE, SCORES)["per_class"]
    assert per_class["pale"] == {"top1": 0.5, "top2": 1.0, "support": 2}
    assert per_class["light_red"] == {"top1": 0.0, "top2": 0.0, "support": 1}
    assert per_class["red"] == {"top1": 0.5, "top2": 1.0, "support": 2}
    assert per_class["purple"] == {"top1": 0.0, "top2": 0.0, "support": 1}


def test_top_k_per_class_has_only_classes_in_truth() -> None:
    per_class = top_k_metrics(Y_TRUE, SCORES)["per_class"]
    assert "dark_red" not in per_class
    assert set(per_class) == {"pale", "light_red", "red", "purple"}


def test_top_k_is_monotonic_and_perfect_scores_give_one() -> None:
    y_true = np.arange(NUM_CLASSES)
    result = top_k_metrics(y_true, np.eye(NUM_CLASSES))
    assert result["top1"] == 1.0
    assert result["top2"] == 1.0


@pytest.mark.parametrize("seed", [0, 1, 2])
def test_top1_equals_accuracy_and_per_class_top1_equals_recall(seed: int) -> None:
    rng = np.random.default_rng(seed)
    y_true = rng.integers(0, NUM_CLASSES, size=200)
    scores = rng.normal(size=(200, NUM_CLASSES))
    y_pred = scores.argmax(axis=1)

    top_k = top_k_metrics(y_true, scores)
    metrics = classification_metrics(y_true, y_pred)

    assert top_k["top1"] == pytest.approx(metrics["accuracy"])
    assert top_k["top2"] >= top_k["top1"]
    for slug in CLASS_SLUGS:
        if slug in top_k["per_class"]:
            assert top_k["per_class"][slug]["top1"] == pytest.approx(
                metrics["per_class"][slug]["recall"]
            )
            assert top_k["per_class"][slug]["top2"] >= top_k["per_class"][slug]["top1"]


def test_top1_agrees_with_argmax_when_scores_tie() -> None:
    # 同点でも top-1 が accuracy(argmax の予測)と一致する(SPEC_02)
    y_true = np.array([LIGHT_RED, PALE, RED])
    scores = np.array(
        [
            [0.5, 0.5, 0.0, 0.0, 0.0],
            [0.5, 0.5, 0.0, 0.0, 0.0],
            [0.25, 0.25, 0.25, 0.25, 0.0],
        ]
    )
    y_pred = scores.argmax(axis=1)
    result = top_k_metrics(y_true, scores)
    assert result["top1"] == pytest.approx(classification_metrics(y_true, y_pred)["accuracy"])
    # 3 行目の red は同点の 3 番手なので top-2 にも入らない
    assert result["top2"] == pytest.approx(2 / 3)


def test_scores_need_not_be_probabilities() -> None:
    # decision_function(負の値を含む)でも,スケールを変えても順位だけで決まる
    baseline = top_k_metrics(Y_TRUE, SCORES)
    assert top_k_metrics(Y_TRUE, SCORES * 37.0 - 11.0) == baseline


def test_subset_metrics_adds_top_k_for_each_subset() -> None:
    severities = ["strong", "mild", "normal", "strong", "mild", "strong"]
    y_pred = SCORES.argmax(axis=1)
    result = subset_metrics(Y_TRUE, y_pred, severities, SCORES)

    assert result["all"]["top_k"]["top1"] == pytest.approx(2 / 6)
    assert result["all"]["top_k"] == top_k_metrics(Y_TRUE, SCORES)
    common = np.array([s != "mild" for s in severities])
    assert result["common"]["top_k"] == top_k_metrics(Y_TRUE[common], SCORES[common])
    mild = ~common
    assert result["mild"]["top_k"] == top_k_metrics(Y_TRUE[mild], SCORES[mild])


def test_subset_metrics_without_scores_has_no_top_k() -> None:
    result = subset_metrics(Y_TRUE, SCORES.argmax(axis=1), ["strong"] * 6)
    assert "top_k" not in result["all"]


def test_aggregate_folds_averages_top_k_but_not_support() -> None:
    first = {"top_k": top_k_metrics(Y_TRUE, SCORES)}
    second = {"top_k": top_k_metrics(Y_TRUE, np.eye(NUM_CLASSES)[Y_TRUE])}
    summary = aggregate_folds([first, second])
    assert summary is not None
    assert summary["top_k"]["top1"]["mean"] == pytest.approx((2 / 6 + 1.0) / 2)
    assert summary["top_k"]["top2"]["mean"] == pytest.approx((4 / 6 + 1.0) / 2)
    assert "support" not in summary["top_k"]["per_class"]["pale"]