!pip install torch-fidelity
import torch
import torch.nn as nn
from torchmetrics.image.kid import KernelInceptionDistance # Or import KernelInceptionDistance
import torch_fidelity
@torch.no_grad()
def compute_kid(model, val_loader, device, subsets=10, subset_size=512):
model.eval()
real_feats, pred_feats = ,
inception = nn.Identity() # Auto-handled by metricfor img_a, img_b, labels in tqdm(val_loader): img_a, img_b, labels = img_a.to(device), img_b.to(device), labels.to(device) # Real change maps (labels) real_feats.append(labels.cpu()) # Binary maps # Predicted pred = torch.sigmoid(model(img_a, img_b)) pred_feats.append(pred.cpu()) real_maps = torch.cat(real_feats).flatten(1) # (N, H*W) or Inception feats pred_maps = torch.cat(pred_feats).flatten(1) kid = KernelInceptionDistance(feature=2048, # or whatever you want subsets=10, subset_size=1000) return kid.item() # Lower = better [web:100]
!pip install torch-fidelity
import torch_fidelity
transform=transforms.Compose([
transforms.Resize(256),
transforms.ToTensor()])
val_dataset = ChangeDetectionDataset(“midenet/test/imageA”, “midenet/test/imageB”, “midenet/test/label”, transform)
val_loader = DataLoader(val_dataset, batch_size=16, shuffle=False)Post-epoch or final
model = load_change_model(
model_path=“/kaggle/working/best_change_detector.pth”,
device=“cuda”,
in_channels=3,
base_channels=32,
)
model.eval()
kid_score = compute_kid(model, val_loader, device=‘cuda’)
print(f"Val KID: {kid_score:.4f}")
torch.save({‘model_state_dict’: model.module.state_dict() if isinstance(model, nn.DataParallel) else model.state_dict(),
‘kid’: kid_score}, ‘best_kid_model.pth’)
I am working on a change detection model and using KID here are the code cell
these code cell throw the ModuleNotFoundError
ModuleNotFoundError Traceback (most recent call last)
/tmp/ipykernel_55/128099551.py in <cell line: 0>()
16 )
17 model.eval()
---> 18 kid_score = compute_kid(model, val_loader, device='cuda')
19 print(f"Val KID: {kid_score:.4f}")
20 torch.save({'model_state_dict': model.module.state_dict() if isinstance(model, nn.DataParallel) else model.state_dict(),
/usr/local/lib/python3.12/dist-packages/torch/utils/_contextlib.py in decorate_context(*args, **kwargs)
118 def decorate_context(*args, **kwargs):
119 with ctx_factory():
--> 120 return func(*args, **kwargs)
121
122 return decorate_context
/tmp/ipykernel_55/157051291.py in compute_kid(model, val_loader, device, subsets, subset_size)
23 pred_maps = torch.cat(pred_feats).flatten(1)
24
---> 25 kid = KernelInceptionDistance(feature=2048, # or whatever you want
26 subsets=10,
27 subset_size=1000)
/usr/local/lib/python3.12/dist-packages/torchmetrics/image/kid.py in __init__(self, feature, subsets, subset_size, degree, gamma, coef, reset_real_features, normalize, **kwargs)
199 if isinstance(feature, (str, int)):
200 if not _TORCH_FIDELITY_AVAILABLE:
--> 201 raise ModuleNotFoundError(
202 "Kernel Inception Distance metric requires that `Torch-fidelity` is installed."
203 " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
ModuleNotFoundError: Kernel Inception Distance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.
Can anyone help me