"""学習後の評価の IoU(`training/iou.py`)のテスト.
期待値は SPEC_02「学習後の評価」と原本(`legacy/source/main.py` の `model.eval()` 以降)を
基準にする.原本は import できないため,同じフォルダの `original_evaluation.py` に書き写した
参照実装(scikit-learn の `confusion_matrix` は NumPy の数え上げに置き換え)とも比べる.
"""
from __future__ import annotations
import json
import math
import numpy as np
import pytest
import torch
from original_evaluation import original_iou
from tongue_seg_model.training.iou import (
binary_iou,
evaluate_iou,
otsu_binarize,
summarize_ious,
tongue_output_to_uint8,
)
SEED = 0
def _logit(p: float) -> float:
return math.log(p / (1.0 - p))
def _output_from_tongue_logits(tongue_logits: torch.Tensor) -> torch.Tensor:
"""舌のチャンネル 0 の値から `(2, H, W)` の出力を作る(チャンネル 1 は 0 の反対の値)."""
return torch.stack([tongue_logits, -tongue_logits], dim=0)
def _target_from_tongue(tongue: torch.Tensor) -> torch.Tensor:
tongue = tongue.float()
return torch.stack([tongue, 1.0 - tongue], dim=0)
# ---------------------------------------------------------------------------
# tongue_output_to_uint8(シグモイド → ×255 → 切り捨て)
# ---------------------------------------------------------------------------
def test_output_to_uint8_shape_and_dtype() -> None:
output = torch.zeros(2, 4, 6)
image = tongue_output_to_uint8(output)
assert isinstance(image, np.ndarray)
assert image.shape == (4, 6)
assert image.dtype == np.uint8
def test_output_to_uint8_truncates() -> None:
# 0 → sigmoid 0.5 → 127.5 → 127(四捨五入なら 128)
# 10 → sigmoid 0.99995… → 254.98… → 254(四捨五入なら 255).大きな負の値 → 0
# 20 → float32 のシグモイドが 1.0 ちょうどに丸まる → 255(原本も float32 で同じ)
# 100.9 / 255 になる値 → 100(四捨五入なら 101).100.1 / 255 になる値 → 100
values = torch.tensor(
[[0.0, 10.0, -20.0, _logit(100.9 / 255.0), _logit(100.1 / 255.0), 20.0]],
dtype=torch.float32,
)
output = _output_from_tongue_logits(values)
image = tongue_output_to_uint8(output)
assert image.tolist() == [[127, 254, 0, 100, 100, 255]]
def test_output_to_uint8_uses_tongue_channel0_only() -> None:
output = torch.zeros(2, 1, 2)
output[0] = torch.tensor([[10.0, -20.0]])
output[1] = torch.tensor([[-20.0, 10.0]]) # チャンネル 1 は無視される
assert tongue_output_to_uint8(output).tolist() == [[254, 0]]
def test_output_to_uint8_accepts_tensor_requiring_grad() -> None:
output = torch.zeros(2, 2, 2, requires_grad=True)
assert tongue_output_to_uint8(output).tolist() == [[127, 127], [127, 127]]
# ---------------------------------------------------------------------------
# otsu_binarize
# ---------------------------------------------------------------------------
def test_otsu_binarize_separates_two_levels() -> None:
image = np.array([[10, 10, 200], [200, 10, 200]], dtype=np.uint8)
binary = otsu_binarize(image)
assert binary.dtype == np.uint8
assert binary.shape == image.shape
assert binary.tolist() == [[0, 0, 255], [255, 0, 255]]
def test_otsu_binarize_values_are_0_or_255() -> None:
image = np.random.default_rng(SEED).integers(0, 256, size=(16, 16), dtype=np.uint8)
binary = otsu_binarize(image)
assert set(np.unique(binary).tolist()) <= {0, 255}
def test_otsu_binarize_bimodal_with_noise() -> None:
# 低い山(20〜40)と高い山(200〜230).しきい値は 2 つの山の間に来る.
rng = np.random.default_rng(SEED)
low = rng.integers(20, 41, size=(8, 8), dtype=np.uint8)
high = rng.integers(200, 231, size=(8, 8), dtype=np.uint8)
image = np.concatenate([low, high], axis=1)
binary = otsu_binarize(image)
assert (binary[:, :8] == 0).all()
assert (binary[:, 8:] == 255).all()
# ---------------------------------------------------------------------------
# binary_iou
# ---------------------------------------------------------------------------
def test_binary_iou_hand_computed() -> None:
# 予測(0 / 255): 前景 4 画素.正解(0 / 1): 前景 3 画素.重なり 2,和集合 5 → 0.4
pred = np.array([[255, 255, 0], [255, 255, 0]], dtype=np.uint8)
target = np.array([[1, 0, 1], [1, 0, 0]], dtype=np.float32)
iou = binary_iou(pred, target)
assert iou == pytest.approx(0.4)
assert type(iou) is float
def test_binary_iou_accepts_0_1_prediction() -> None:
pred = np.array([[1, 1, 0, 0]], dtype=np.uint8)
target = np.array([[1, 0, 0, 0]], dtype=np.float32)
assert binary_iou(pred, target) == pytest.approx(0.5)
def test_binary_iou_disjoint_is_zero() -> None:
pred = np.array([[255, 0]], dtype=np.uint8)
target = np.array([[0, 1]], dtype=np.float32)
assert binary_iou(pred, target) == 0.0
def test_binary_iou_all_tongue_is_one() -> None:
pred = np.full((4, 4), 255, dtype=np.uint8)
target = np.ones((4, 4), dtype=np.float32)
assert binary_iou(pred, target) == 1.0
def test_binary_iou_empty_union_raises() -> None:
pred = np.zeros((4, 4), dtype=np.uint8)
target = np.zeros((4, 4), dtype=np.float32)
with pytest.raises(ValueError):
binary_iou(pred, target)
def test_binary_iou_empty_prediction_with_tongue_is_zero() -> None:
pred = np.zeros((2, 2), dtype=np.uint8)
target = np.array([[1, 0], [0, 0]], dtype=np.float32)
assert binary_iou(pred, target) == 0.0
def test_binary_iou_shape_mismatch_raises() -> None:
pred = np.zeros((4, 4), dtype=np.uint8)
target = np.ones((4, 5), dtype=np.float32)
with pytest.raises(ValueError):
binary_iou(pred, target)
# ---------------------------------------------------------------------------
# evaluate_iou(シグモイド → ×255 → 大津 → IoU)
# ---------------------------------------------------------------------------
def test_evaluate_iou_known_prediction() -> None:
# 予測の舌(大きな正の値): 左 2 列 × 4 行 = 8 画素.それ以外は大きな負の値.
# 正解の舌: 左 3 列 × 2 行 + 左 1 列 × 下 2 行 = 8 画素
# 重なり: 上 2 行の左 2 列 = 4,下 2 行の左 1 列 = 2 → 6.和集合: 8 + 8 − 6 = 10 → 0.6
logits = torch.full((4, 4), -20.0)
logits[:, :2] = 20.0
tongue = torch.zeros(4, 4)
tongue[:2, :3] = 1.0
tongue[2:, :1] = 1.0
iou = evaluate_iou(_output_from_tongue_logits(logits), _target_from_tongue(tongue))
assert iou == pytest.approx(0.6)
assert type(iou) is float
def test_evaluate_iou_uses_otsu_not_fixed_half_threshold() -> None:
# 出力が全体に低い(シグモイドで 0.5 未満)が,2 つの山に分かれる場合.
# 0.5 の固定しきい値なら全画素が舌以外になるが,大津の方法では高い方の山が舌になる.
logits = torch.full((4, 4), _logit(30.5 / 255.0)) # → 30
logits[:, :2] = _logit(100.5 / 255.0) # → 100(< 127.5)
tongue = torch.zeros(4, 4)
tongue[:, :2] = 1.0
iou = evaluate_iou(_output_from_tongue_logits(logits), _target_from_tongue(tongue))
assert iou == pytest.approx(1.0)
def test_evaluate_iou_uses_target_channel0() -> None:
logits = torch.full((2, 2), -20.0)
logits[0, :] = 20.0
tongue = torch.tensor([[1.0, 1.0], [0.0, 0.0]])
target = _target_from_tongue(tongue)
assert evaluate_iou(_output_from_tongue_logits(logits), target) == pytest.approx(1.0)
# チャンネルを入れ替えた正解(チャンネル 0 が予測の反対)では 0
swapped = target.flip(0)
assert evaluate_iou(_output_from_tongue_logits(logits), swapped) == pytest.approx(0.0)
def test_evaluate_iou_shape_mismatch_raises() -> None:
logits = torch.full((4, 4), -20.0)
logits[:2] = 20.0
with pytest.raises(ValueError):
evaluate_iou(_output_from_tongue_logits(logits), torch.ones(2, 4, 5))
def test_evaluate_iou_empty_prediction_and_target_raises() -> None:
# 出力が一様だと大津の 2 値化ですべて 0 になる.正解も空 → 和集合 0
output = torch.full((2, 4, 4), -20.0)
target = _target_from_tongue(torch.zeros(4, 4))
with pytest.raises(ValueError):
evaluate_iou(output, target)
def _random_case(seed: int, size: int = 32) -> tuple[torch.Tensor, torch.Tensor]:
gen = torch.Generator().manual_seed(seed)
output = torch.randn(1, 2, size, size, generator=gen) * 3.0
tongue = (torch.rand(size, size, generator=gen) > 0.5).float()
target = _target_from_tongue(tongue).unsqueeze(0)
return output, target
@pytest.mark.parametrize("seed", range(5))
def test_evaluate_iou_matches_original(seed: int) -> None:
output, target = _random_case(seed)
iou = evaluate_iou(output[0], target[0])
expected = original_iou(output, target)
assert iou == pytest.approx(float(expected), abs=1e-12)
def test_evaluate_iou_matches_original_known_shapes() -> None:
# 予測が正解に近い(正解に雑音を足した出力)場合も原本と一致する.
gen = torch.Generator().manual_seed(SEED)
tongue = torch.zeros(32, 32)
tongue[8:24, 6:26] = 1.0
logits = (tongue * 2 - 1) * 4 + torch.randn(32, 32, generator=gen) * 2
output = _output_from_tongue_logits(logits).unsqueeze(0)
target = _target_from_tongue(tongue).unsqueeze(0)
iou = evaluate_iou(output[0], target[0])
assert 0.5 < iou < 1.0
assert iou == pytest.approx(float(original_iou(output, target)), abs=1e-12)
# ---------------------------------------------------------------------------
# summarize_ious
# ---------------------------------------------------------------------------
def test_summarize_ious_hand_computed_odd() -> None:
# [0.2, 0.4, 0.9]: 平均 0.5,中央値 0.4,最小 0.2,最大 0.9
# 母標準偏差: sqrt((0.09 + 0.01 + 0.16) / 3)
summary = summarize_ious([0.2, 0.4, 0.9])
assert set(summary) == {"count", "mean", "median", "min", "max", "std"}
assert summary["count"] == 3
assert summary["mean"] == pytest.approx(0.5)
assert summary["median"] == pytest.approx(0.4)
assert summary["min"] == pytest.approx(0.2)
assert summary["max"] == pytest.approx(0.9)
assert summary["std"] == pytest.approx(math.sqrt(0.26 / 3))
def test_summarize_ious_hand_computed_even_median() -> None:
# [0.8, 0.2, 0.6, 0.4]: 中央値は真ん中 2 つの平均 (0.4 + 0.6) / 2 = 0.5
# 母標準偏差: 平均 0.5 → sqrt((0.09 + 0.09 + 0.01 + 0.01) / 4) = sqrt(0.05)
summary = summarize_ious([0.8, 0.2, 0.6, 0.4])
assert summary["count"] == 4
assert summary["median"] == pytest.approx(0.5)
assert summary["std"] == pytest.approx(math.sqrt(0.05))
def test_summarize_ious_single_value() -> None:
summary = summarize_ious([0.75])
assert summary == pytest.approx(
{"count": 1, "mean": 0.75, "median": 0.75, "min": 0.75, "max": 0.75, "std": 0.0}
)
def test_summarize_ious_empty_raises() -> None:
with pytest.raises(ValueError):
summarize_ious([])
def test_summarize_ious_values_are_json_native_types() -> None:
summary = summarize_ious(np.array([0.1, 0.5, 0.7], dtype=np.float64))
assert type(summary["count"]) is int
for key in ["mean", "median", "min", "max", "std"]:
assert type(summary[key]) is float, key
assert json.loads(json.dumps(summary)) == summary