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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_robustness.py
|
| 3 |
+
Robustness evaluation for student models (Phase 2, Steps 2 & 3).
|
| 4 |
+
|
| 5 |
+
Tests trained models under various input corruptions and reports
|
| 6 |
+
localization error in meters (median, P90, P99).
|
| 7 |
+
|
| 8 |
+
Step 2 — AP Dropout:
|
| 9 |
+
- Remove each AP individually (zero out 1 of 4 channels)
|
| 10 |
+
- Random 1-AP dropout (random channel zeroed per sample)
|
| 11 |
+
- Random 2-AP dropout (2 random channels zeroed per sample)
|
| 12 |
+
|
| 13 |
+
Step 3 — Data Augmentation Robustness (optional):
|
| 14 |
+
- Gaussian noise (sigma=0.1, 0.2)
|
| 15 |
+
- AP attenuation (scale channel by 0.5)
|
| 16 |
+
- Phase perturbation (random rotation in complex-like space)
|
| 17 |
+
- Heatmap blur (Gaussian blur on input)
|
| 18 |
+
|
| 19 |
+
Usage:
|
| 20 |
+
python test_robustness.py
|
| 21 |
+
Edit CONFIG below to select model and weights path.
|
| 22 |
+
"""
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as torchF
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
from utils import localization_error
|
| 31 |
+
from data_loader import load_data
|
| 32 |
+
|
| 33 |
+
# ============================================================
|
| 34 |
+
# CONFIG
|
| 35 |
+
# ============================================================
|
| 36 |
+
MODEL_TYPE = 'mobilenet' # 'mobilenet', 'tinycnn', 'unet'
|
| 37 |
+
WEIGHTS_PATH = './weights/mobilenet_standalone_best.pth'
|
| 38 |
+
BATCH_SIZE = 32
|
| 39 |
+
|
| 40 |
+
# Data paths (Fig 10b — Jacobs Hall)
|
| 41 |
+
testpath = [
|
| 42 |
+
'./data/dataset_fov_test_jacobs_July28_2.mat',
|
| 43 |
+
'./data/dataset_non_fov_test_jacobs_July28_2.mat',
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
# ============================================================
|
| 47 |
+
# CORRUPTION FUNCTIONS
|
| 48 |
+
# ============================================================
|
| 49 |
+
def no_corruption(inputs):
|
| 50 |
+
"""Baseline: no corruption."""
|
| 51 |
+
return inputs
|
| 52 |
+
|
| 53 |
+
def drop_ap(inputs, ap_index):
|
| 54 |
+
"""Zero out a specific AP channel."""
|
| 55 |
+
corrupted = inputs.clone()
|
| 56 |
+
corrupted[:, ap_index, :, :] = 0.0
|
| 57 |
+
return corrupted
|
| 58 |
+
|
| 59 |
+
def random_drop_1ap(inputs):
|
| 60 |
+
"""Randomly zero 1 AP per sample."""
|
| 61 |
+
corrupted = inputs.clone()
|
| 62 |
+
for i in range(corrupted.shape[0]):
|
| 63 |
+
ap = torch.randint(0, 4, (1,)).item()
|
| 64 |
+
corrupted[i, ap, :, :] = 0.0
|
| 65 |
+
return corrupted
|
| 66 |
+
|
| 67 |
+
def random_drop_2ap(inputs):
|
| 68 |
+
"""Randomly zero 2 APs per sample."""
|
| 69 |
+
corrupted = inputs.clone()
|
| 70 |
+
for i in range(corrupted.shape[0]):
|
| 71 |
+
aps = torch.randperm(4)[:2]
|
| 72 |
+
for ap in aps:
|
| 73 |
+
corrupted[i, ap, :, :] = 0.0
|
| 74 |
+
return corrupted
|
| 75 |
+
|
| 76 |
+
def gaussian_noise(inputs, sigma=0.1):
|
| 77 |
+
"""Add Gaussian noise."""
|
| 78 |
+
return inputs + torch.randn_like(inputs) * sigma
|
| 79 |
+
|
| 80 |
+
def ap_attenuation(inputs, scale=0.5):
|
| 81 |
+
"""Scale all channels by a factor (simulates weaker signal)."""
|
| 82 |
+
return inputs * scale
|
| 83 |
+
|
| 84 |
+
def single_ap_attenuation(inputs, ap_index, scale=0.3):
|
| 85 |
+
"""Attenuate a single AP channel."""
|
| 86 |
+
corrupted = inputs.clone()
|
| 87 |
+
corrupted[:, ap_index, :, :] *= scale
|
| 88 |
+
return corrupted
|
| 89 |
+
|
| 90 |
+
def gaussian_blur(inputs, kernel_size=5, sigma=1.0):
|
| 91 |
+
"""Apply Gaussian blur to each channel."""
|
| 92 |
+
# Create 1D Gaussian kernel
|
| 93 |
+
x = torch.arange(kernel_size, dtype=torch.float32, device=inputs.device) - kernel_size // 2
|
| 94 |
+
kernel_1d = torch.exp(-0.5 * (x / sigma) ** 2)
|
| 95 |
+
kernel_1d = kernel_1d / kernel_1d.sum()
|
| 96 |
+
# Make 2D kernel
|
| 97 |
+
kernel_2d = kernel_1d[:, None] * kernel_1d[None, :]
|
| 98 |
+
kernel_2d = kernel_2d.expand(inputs.shape[1], 1, kernel_size, kernel_size)
|
| 99 |
+
pad = kernel_size // 2
|
| 100 |
+
return torchF.conv2d(inputs, kernel_2d, padding=pad, groups=inputs.shape[1])
|
| 101 |
+
|
| 102 |
+
# ============================================================
|
| 103 |
+
# MAIN
|
| 104 |
+
# ============================================================
|
| 105 |
+
def load_model(model_type, weights_path, device):
|
| 106 |
+
if model_type == 'mobilenet':
|
| 107 |
+
from student_mobilenet import MobileNetStudent
|
| 108 |
+
model = MobileNetStudent(input_nc=4)
|
| 109 |
+
elif model_type == 'tinycnn':
|
| 110 |
+
from student_tinycnn import TinyCNNStudent
|
| 111 |
+
model = TinyCNNStudent(input_nc=4)
|
| 112 |
+
elif model_type == 'unet':
|
| 113 |
+
from student_unet import MobileNetUNetStudent
|
| 114 |
+
model = MobileNetUNetStudent(input_nc=4)
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError(f'Unknown model type: {model_type}')
|
| 117 |
+
|
| 118 |
+
model.load_state_dict(torch.load(weights_path, map_location=device, weights_only=True))
|
| 119 |
+
model.to(device)
|
| 120 |
+
model.eval()
|
| 121 |
+
return model
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def evaluate_condition(model, test_loader, corrupt_fn, device):
|
| 125 |
+
"""Run model on corrupted inputs, return error stats in meters."""
|
| 126 |
+
all_errors = []
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
for data in test_loader:
|
| 129 |
+
inputs = data[0].to(device)
|
| 130 |
+
labels = data[1].to(device)
|
| 131 |
+
|
| 132 |
+
corrupted = corrupt_fn(inputs)
|
| 133 |
+
output = model(corrupted)
|
| 134 |
+
|
| 135 |
+
errors = localization_error(
|
| 136 |
+
output.cpu().numpy(),
|
| 137 |
+
labels.cpu().numpy(),
|
| 138 |
+
scale=0.1,
|
| 139 |
+
)
|
| 140 |
+
all_errors.extend(errors)
|
| 141 |
+
|
| 142 |
+
all_errors = np.array(all_errors)
|
| 143 |
+
return {
|
| 144 |
+
'median': np.median(all_errors),
|
| 145 |
+
'p90': np.percentile(all_errors, 90),
|
| 146 |
+
'p99': np.percentile(all_errors, 99),
|
| 147 |
+
'mean': np.mean(all_errors),
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 153 |
+
print(f'Device: {device}')
|
| 154 |
+
print(f'Model: {MODEL_TYPE}, Weights: {WEIGHTS_PATH}')
|
| 155 |
+
|
| 156 |
+
# Load model
|
| 157 |
+
model = load_model(MODEL_TYPE, WEIGHTS_PATH, device)
|
| 158 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 159 |
+
print(f'Parameters: {n_params:,}')
|
| 160 |
+
|
| 161 |
+
# Load test data
|
| 162 |
+
print('Loading test data...')
|
| 163 |
+
test_w_list, test_lbl_list = [], []
|
| 164 |
+
for fp in testpath:
|
| 165 |
+
_, w, lbl = load_data(fp)
|
| 166 |
+
if lbl.dim() == 3:
|
| 167 |
+
lbl = lbl.unsqueeze(1)
|
| 168 |
+
test_w_list.append(w)
|
| 169 |
+
test_lbl_list.append(lbl)
|
| 170 |
+
test_w = torch.cat(test_w_list, dim=0)
|
| 171 |
+
test_lbl = torch.cat(test_lbl_list, dim=0)
|
| 172 |
+
print(f'Test samples: {test_w.shape[0]}')
|
| 173 |
+
|
| 174 |
+
test_data = torch.utils.data.TensorDataset(test_w, test_lbl)
|
| 175 |
+
test_loader = torch.utils.data.DataLoader(
|
| 176 |
+
test_data, batch_size=BATCH_SIZE, shuffle=False,
|
| 177 |
+
num_workers=4, pin_memory=True,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Define all test conditions
|
| 181 |
+
conditions = {
|
| 182 |
+
# Step 2: AP Dropout
|
| 183 |
+
'Normal (no corruption)': no_corruption,
|
| 184 |
+
'Drop AP 0': lambda x: drop_ap(x, 0),
|
| 185 |
+
'Drop AP 1': lambda x: drop_ap(x, 1),
|
| 186 |
+
'Drop AP 2': lambda x: drop_ap(x, 2),
|
| 187 |
+
'Drop AP 3': lambda x: drop_ap(x, 3),
|
| 188 |
+
'Random drop 1 AP': random_drop_1ap,
|
| 189 |
+
'Random drop 2 APs': random_drop_2ap,
|
| 190 |
+
# Step 3: Augmentation robustness
|
| 191 |
+
'Gaussian noise (sigma=0.1)': lambda x: gaussian_noise(x, sigma=0.1),
|
| 192 |
+
'Gaussian noise (sigma=0.2)': lambda x: gaussian_noise(x, sigma=0.2),
|
| 193 |
+
'Attenuation (0.5x all)': lambda x: ap_attenuation(x, scale=0.5),
|
| 194 |
+
'Attenuate AP 0 (0.3x)': lambda x: single_ap_attenuation(x, 0, 0.3),
|
| 195 |
+
'Gaussian blur (k=5, s=1)': lambda x: gaussian_blur(x, kernel_size=5, sigma=1.0),
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
# Run all conditions
|
| 199 |
+
print(f'\n{"="*75}')
|
| 200 |
+
print(f' ROBUSTNESS EVALUATION — {MODEL_TYPE.upper()}')
|
| 201 |
+
print(f'{"="*75}')
|
| 202 |
+
print(f'{"Condition":<30} {"Median":>8} {"P90":>8} {"P99":>8} {"Mean":>8}')
|
| 203 |
+
print(f'{"-"*75}')
|
| 204 |
+
|
| 205 |
+
results = {}
|
| 206 |
+
for name, corrupt_fn in conditions.items():
|
| 207 |
+
stats = evaluate_condition(model, test_loader, corrupt_fn, device)
|
| 208 |
+
results[name] = stats
|
| 209 |
+
print(f'{name:<30} {stats["median"]:>7.3f}m {stats["p90"]:>7.3f}m {stats["p99"]:>7.3f}m {stats["mean"]:>7.3f}m')
|
| 210 |
+
|
| 211 |
+
print(f'{"="*75}')
|
| 212 |
+
|
| 213 |
+
# Save results
|
| 214 |
+
save_path = f'robustness_{MODEL_TYPE}.txt'
|
| 215 |
+
with open(save_path, 'w') as f:
|
| 216 |
+
f.write(f'Model: {MODEL_TYPE}\n')
|
| 217 |
+
f.write(f'Weights: {WEIGHTS_PATH}\n')
|
| 218 |
+
f.write(f'Test samples: {test_w.shape[0]}\n\n')
|
| 219 |
+
f.write(f'{"Condition":<30} {"Median":>8} {"P90":>8} {"P99":>8} {"Mean":>8}\n')
|
| 220 |
+
f.write(f'{"-"*62}\n')
|
| 221 |
+
for name, stats in results.items():
|
| 222 |
+
f.write(f'{name:<30} {stats["median"]:>7.3f}m {stats["p90"]:>7.3f}m {stats["p99"]:>7.3f}m {stats["mean"]:>7.3f}m\n')
|
| 223 |
+
print(f'\nResults saved to {save_path}')
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == '__main__':
|
| 227 |
+
main()
|