Metrics and losses¶
Metrics¶
metrics
¶
Evaluation metrics for images, volumes and compressed representations.
Thin wrappers around torchmetrics that score a single sample and return a Python float.
Image metrics take (channels, H, W) images, and data_range defaults to the dtype
convention of torchvision and scikit-image: 255 for uint8 images and 1 for
floating-point images in [0, 1]. Pass it explicitly for other ranges, as
data_range=target.max() for MRI magnitudes.
psnr
¶
Return the peak signal-to-noise ratio in dB, pooling all elements.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
-
data_range(float | None, default:None) –Peak value;
Noneuses1for floating-point targets and the dtype's maximum for integer ones.
Examples:
Source code in inro/metrics.py
ssim
¶
Return the structural similarity of two (channels, H, W) images.
Uses an 11x11 Gaussian window by default.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
-
data_range(float | None, default:None) –Peak value;
Noneuses1for floating-point targets and the dtype's maximum for integer ones. -
**kwargs(Any, default:{}) –Passed to
structural_similarity_index_measureof torchmetrics.
Source code in inro/metrics.py
ms_ssim
¶
Return the multi-scale structural similarity of two (channels, H, W) images.
The five default scales require both image sides to be at least 176 pixels.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
-
data_range(float | None, default:None) –Peak value;
Noneuses1for floating-point targets and the dtype's maximum for integer ones. -
**kwargs(Any, default:{}) –Passed to
multiscale_structural_similarity_index_measureof torchmetrics.
Source code in inro/metrics.py
lpips
¶
lpips(pred: Tensor, target: Tensor, data_range: float | None = None, net: _LPIPSNet = 'vgg') -> float
Return the learned perceptual image patch similarity of two (3, H, W) images.
Lower is better. Inputs are clipped to the data range. The network, which matches
the reference lpips package, is loaded once per backbone and device.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
-
data_range(float | None, default:None) –Peak value;
Noneuses1for floating-point targets and the dtype's maximum for integer ones. -
net(_LPIPSNet, default:'vgg') –Backbone of the network.
References
Zhang et al., "The Unreasonable Effectiveness of Deep Features as a Perceptual Metric", CVPR 2018.
Source code in inro/metrics.py
nmse
¶
Return the normalized MSE ||pred - target||^2 / ||target||^2, as in fastMRI.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
Examples:
Source code in inro/metrics.py
iou
¶
Return the intersection over union of occupancies, occupied above zero.
Parameters:
-
pred(Tensor) –Reconstruction.
-
target(Tensor) –Reference signal.
Examples:
Source code in inro/metrics.py
bits_per_pixel
¶
Return the encoded size in bits per pixel of a (channels, *spatial) image.
Parameters:
-
encoded(bytes) –Encoded signal.
-
image(Tensor) –Image whose spatial size counts the pixels.
Examples:
Source code in inro/metrics.py
luma
¶
Return the BT.601 luma of a uint8 RGB image, as MATLAB's rgb2ycbcr.
Super-resolution reports PSNR and SSIM on this channel, with data_range=255.
Parameters:
-
image(Tensor) –Image
(3, H, W).
Returns:
-
Tensor–Float image
(1, H, W)in[16, 235].
Examples:
>>> white = torch.full((3, 2, 2), 255, dtype=torch.uint8)
>>> round(luma(white).max().item(), 2)
235.0
Source code in inro/metrics.py
super_resolution_metrics
¶
super_resolution_metrics(border: int = 0, device: str | device | None = None) -> dict[str, Callable[[Tensor, Tensor], float]]
Return the super-resolution protocol's metrics, as metrics arguments.
These are PSNR and SSIM of the luma channel and LPIPS of RGB.
train and evaluate call them as
fn(reconstruction, original) on uint8 (3, H, W) images.
Parameters:
-
border(int, default:0) –Pixels shaved off each side before scoring, by convention the scale factor.
-
device(str | device | None, default:None) –Device to score on;
Nonekeeps the images where they are.
Returns:
-
dict[str, Callable[[Tensor, Tensor], float]]–The functions under the keys
psnr,ssimandlpips.
Examples:
Source code in inro/metrics.py
Losses¶
losses
¶
Training losses and differentiable entropy estimates.
A loss follows loss_fn(batch, model) -> (loss, metrics): it runs the model on
batch["input"] and returns a scalar loss and logging values, kept as scalar tensors
so that train reads them only when it logs.
soft_entropy
¶
soft_entropy(x: Tensor, num_bins: int | None = None, temperature: float = 1.0, eps: float = 1e-16) -> Tensor
Estimate entropy in bits with differentiable soft bin assignments.
Bin centers span the detached input range. Each element gets a softmax assignment from its squared distance to them, and the entropy is that of the mean assignment. Gradients flow through the assignments, not the bin layout.
Parameters:
-
x(Tensor) –Input tensor; all elements are pooled.
-
num_bins(int | None, default:None) –Number of bins;
Noneuses the Freedman–Diaconis width2 * IQR(x) / N**(1/3), rounding the count up, or Sturges' rule when the IQR vanishes. -
temperature(float, default:1.0) –Assignment kernel width relative to bin width; larger is softer.
-
eps(float, default:1e-16) –Constant added inside the logarithm.
Returns:
-
Tensor–Scalar entropy, zero for a constant input.
Examples:
Source code in inro/losses.py
laplace_entropy
¶
Return the differential entropy of a zero-mean Laplace fit, in bits.
Uses the maximum-likelihood scale b = mean(abs(x)) and the entropy
log2(2 * b * e + eps).
Parameters:
-
x(Tensor) –Input tensor; all elements are pooled.
-
eps(float, default:1e-16) –Constant added inside the logarithm.
Source code in inro/losses.py
rate_distortion_loss
¶
rate_distortion_loss(batch: dict[str, Any], model: Module, alpha: float = 0.0, eps: float = 1e-16) -> tuple[Tensor, dict[str, Tensor]]
Balance reconstruction MSE with estimated parameter entropy.
The loss is MSE + alpha * entropy, the entropy being the size-weighted mean of
laplace_entropy over the trainable parameters, evaluated only when
alpha > 0.
Parameters:
-
batch(dict[str, Any]) –Batch with
inputandtarget. -
model(Module) –INR to evaluate.
-
alpha(float, default:0.0) –Weight of the rate term.
-
eps(float, default:1e-16) –Constant added inside the logarithm.
Returns:
-
tuple[Tensor, dict[str, Tensor]]–Scalar loss and the metrics
mse,psnr(for targets in[-1, 1]),loss, andentropywhenalpha > 0, as scalar tensors.
Source code in inro/losses.py
sdf_loss
¶
Return the L1 signed-distance loss and the metrics loss and l1.
Parameters:
-
batch(dict[str, Any]) –Batch with
inputandtarget. -
model(Module) –INR to evaluate.
Source code in inro/losses.py
super_resolution_loss
¶
Return the L1 loss through the degradation and the metrics l1 and psnr.
Renders each block's footprint, downsamples it with the block's kernel rows along
both axes and matches the low-resolution pixels. The PSNR is for targets in
[-1, 1].
Parameters:
-
batch(dict[str, Any]) –Batch of
SuperResolutionDatasetitems. -
model(Module) –INR to evaluate.