File size: 2,724 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from __future__ import annotations

from typing import Iterable

import cv2
import numpy as np
import torch

from data.degradation import DegradationPipeline
from models.concept_head import ConceptHead


def _rankdata(x: np.ndarray) -> np.ndarray:
    order = np.argsort(x)
    ranks = np.empty_like(order, dtype=np.float64)
    ranks[order] = np.arange(len(x), dtype=np.float64)
    return ranks


def _spearman(x: np.ndarray, y: np.ndarray) -> float:
    if len(x) < 2 or len(y) < 2:
        return 0.0
    rx = _rankdata(x)
    ry = _rankdata(y)
    return float(np.corrcoef(rx, ry)[0, 1])


@torch.no_grad()
def compute_crosstalk_matrix(
    model: torch.nn.Module,
    degradation_pipeline: DegradationPipeline,
    test_images: Iterable[np.ndarray],
    device: str = "cpu",
) -> list[dict[str, float | str]]:
    """Return row-wise crosstalk values as list of dicts.

    Each row corresponds to one degradation type and contains Spearman
    correlation with all concept outputs.
    """

    model.eval()
    deg_types = ["blur", "noise", "jpeg", "occlusion", "dry_skin", "wet_press"]
    rows: list[dict[str, float | str]] = []

    to_tensor = lambda img: torch.from_numpy(img.astype(np.float32) / 255.0).unsqueeze(0).unsqueeze(0)

    for deg_type in deg_types:
        severity_vals: list[float] = []
        concept_vals: list[np.ndarray] = []

        for image in test_images:
            if image.ndim == 3:
                image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            for level in DegradationPipeline.LEVELS:
                # Fix: seed np.random per level so occlusion block lands at a
                # consistent position across severity levels. Without this, each
                # level draws a random block position → Spearman ρ is computed
                # over randomly-placed blocks of increasing size, not a coherent
                # severity sweep → sign of ρ is unreliable for occlusion.
                np.random.seed(level)
                degraded = degradation_pipeline.apply(image, deg_type, level)
                x = to_tensor(degraded).to(device)
                outputs = model(x)
                concepts = outputs["concepts"].squeeze(0).detach().cpu().numpy()
                concept_vals.append(concepts)
                severity_vals.append(float(level))

        if not concept_vals:
            continue

        concept_arr = np.stack(concept_vals, axis=0)
        sev_arr = np.asarray(severity_vals, dtype=np.float64)

        row: dict[str, float | str] = {"degradation": deg_type}
        for idx, cname in enumerate(ConceptHead.CONCEPT_NAMES):
            row[cname] = _spearman(sev_arr, concept_arr[:, idx])
        rows.append(row)

    return rows