PyTorch native metrics library providing 400+ rigorously tested metrics across classification, regression, audio, image, text, and other ML domains
Image quality assessment metrics including structural similarity, peak signal-to-noise ratio, and perceptual quality measures for computer vision applications and image processing evaluation.
Measures signal quality and reconstruction fidelity in images.
class PeakSignalNoiseRatio(Metric):
def __init__(
self,
data_range: Optional[float] = None,
base: float = 10.0,
reduction: str = "elementwise_mean",
**kwargs
): ...
class PeakSignalNoiseRatioWithBlockedEffect(Metric):
def __init__(
self,
block_size: int = 8,
data_range: Optional[float] = None,
reduction: str = "elementwise_mean",
**kwargs
): ...Evaluates structural information preservation between images.
class StructuralSimilarityIndexMeasure(Metric):
def __init__(
self,
gaussian_kernel: bool = True,
sigma: Union[float, Tuple[float, float]] = 1.5,
kernel_size: Union[int, Tuple[int, int]] = 11,
reduction: str = "elementwise_mean",
data_range: Optional[float] = None,
k1: float = 0.01,
k2: float = 0.03,
**kwargs
): ...
class MultiScaleStructuralSimilarityIndexMeasure(Metric):
def __init__(
self,
gaussian_kernel: bool = True,
sigma: Union[float, Tuple[float, float]] = 1.5,
kernel_size: Union[int, Tuple[int, int]] = 11,
reduction: str = "elementwise_mean",
data_range: Optional[float] = None,
k1: float = 0.01,
k2: float = 0.03,
betas: Tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333),
normalize: Optional[str] = "relu",
**kwargs
): ...General-purpose image quality assessment measures.
class UniversalImageQualityIndex(Metric):
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]] = 8,
sigma: Union[float, Tuple[float, float]] = 1.5,
reduction: str = "elementwise_mean",
**kwargs
): ...
class VisualInformationFidelity(Metric):
def __init__(
self,
sigma_n_sq: float = 2.0,
**kwargs
): ...Metrics that analyze spectral properties of images.
class SpectralAngleMapper(Metric):
def __init__(
self,
reduction: str = "elementwise_mean",
**kwargs
): ...
class SpectralDistortionIndex(Metric):
def __init__(
self,
**kwargs
): ...
class SpatialDistortionIndex(Metric):
def __init__(
self,
**kwargs
): ...
class RelativeAverageSpectralError(Metric):
def __init__(
self,
**kwargs
): ...
class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
def __init__(
self,
ratio: float = 1.0,
ws: float = 1.0,
**kwargs
): ...Sophisticated metrics for comprehensive image quality assessment.
class RootMeanSquaredErrorUsingSlidingWindow(Metric):
def __init__(
self,
**kwargs
): ...
class TotalVariation(Metric):
def __init__(
self,
reduction: str = "sum",
**kwargs
): ...
class QualityWithNoReference(Metric):
def __init__(
self,
**kwargs
): ...
class SpatialCorrelationCoefficient(Metric):
def __init__(
self,
**kwargs
): ...Deep learning-based perceptual quality assessment (require optional dependencies).
class FrechetInceptionDistance(Metric):
def __init__(
self,
feature: int = 2048,
reset_real_features: bool = True,
normalize: bool = False,
**kwargs
): ...
class InceptionScore(Metric):
def __init__(
self,
feature: Union[int, str] = 2048,
splits: int = 10,
normalize: bool = False,
**kwargs
): ...
class KernelInceptionDistance(Metric):
def __init__(
self,
feature: int = 2048,
subsets: int = 100,
subset_size: int = 1000,
degree: int = 3,
gamma: Optional[float] = None,
coef0: float = 1.0,
reset_real_features: bool = True,
normalize: bool = False,
**kwargs
): ...
class LearnedPerceptualImagePatchSimilarity(Metric):
def __init__(
self,
net_type: str = "alex",
reduction: str = "mean",
normalize: bool = False,
**kwargs
): ...State-of-the-art perceptual quality assessment methods.
class DeepImageStructureAndTextureSimilarity(Metric):
def __init__(
self,
**kwargs
): ...
class MemorizationInformedFrechetInceptionDistance(Metric):
def __init__(
self,
feature: int = 2048,
**kwargs
): ...
class PerceptualPathLength(Metric):
def __init__(
self,
num_samples: int = 10000,
batch_size: int = 64,
interpolation_method: str = "lerp",
epsilon: float = 1e-4,
resize: Optional[int] = 64,
lower_discard: Optional[float] = None,
upper_discard: Optional[float] = None,
**kwargs
): ...import torch
from torchmetrics.image import (
PeakSignalNoiseRatio,
StructuralSimilarityIndexMeasure
)
# Initialize metrics
psnr = PeakSignalNoiseRatio()
ssim = StructuralSimilarityIndexMeasure()
# Sample image data (batch, channels, height, width)
preds = torch.rand(4, 3, 256, 256)
target = torch.rand(4, 3, 256, 256)
# Compute image quality metrics
psnr_score = psnr(preds, target)
ssim_score = ssim(preds, target)
print(f"PSNR: {psnr_score:.4f} dB")
print(f"SSIM: {ssim_score:.4f}")from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure
# Multi-scale SSIM
ms_ssim = MultiScaleStructuralSimilarityIndexMeasure()
# High-resolution images
preds = torch.rand(2, 3, 512, 512)
target = torch.rand(2, 3, 512, 512)
# Compute MS-SSIM
ms_ssim_score = ms_ssim(preds, target)
print(f"MS-SSIM: {ms_ssim_score:.4f}")from torchmetrics.image import FrechetInceptionDistance
# Initialize FID (requires torch-fidelity)
try:
fid = FrechetInceptionDistance(feature=2048)
# Generate synthetic images (must be 3-channel RGB)
real_images = torch.randint(0, 256, (50, 3, 299, 299), dtype=torch.uint8)
fake_images = torch.randint(0, 256, (50, 3, 299, 299), dtype=torch.uint8)
# Update with real and fake images
fid.update(real_images, real=True)
fid.update(fake_images, real=False)
# Compute FID
fid_score = fid.compute()
print(f"FID: {fid_score:.4f}")
except ImportError:
print("FID requires the 'torch-fidelity' package")from torchmetrics.image import LearnedPerceptualImagePatchSimilarity
# Initialize LPIPS (requires torchvision)
try:
lpips = LearnedPerceptualImagePatchSimilarity(net_type='alex')
# Sample images in [-1, 1] range
preds = torch.rand(4, 3, 256, 256) * 2 - 1
target = torch.rand(4, 3, 256, 256) * 2 - 1
# Compute perceptual distance
lpips_score = lpips(preds, target)
print(f"LPIPS: {lpips_score:.4f}")
except ImportError:
print("LPIPS requires 'torchvision' package")from torchmetrics.image import SpectralAngleMapper, SpectralDistortionIndex
# Spectral quality metrics (useful for hyperspectral images)
sam = SpectralAngleMapper()
sdi = SpectralDistortionIndex()
# Multi-channel spectral images
preds = torch.rand(2, 64, 128, 128) # 64 spectral bands
target = torch.rand(2, 64, 128, 128)
# Compute spectral metrics
sam_score = sam(preds, target)
sdi_score = sdi(preds, target)
print(f"SAM: {sam_score:.4f}")
print(f"SDI: {sdi_score:.4f}")from torchmetrics.image import TotalVariation
# Total variation (measures image smoothness)
tv = TotalVariation()
# Sample images
images = torch.rand(4, 3, 256, 256)
# Compute total variation
tv_score = tv(images)
print(f"Total Variation: {tv_score:.4f}")from torchmetrics.image import InceptionScore
# Inception Score (requires torch-fidelity)
try:
inception_score = InceptionScore()
# Generated images (must be uint8 RGB)
generated_images = torch.randint(0, 256, (100, 3, 299, 299), dtype=torch.uint8)
# Compute IS
is_mean, is_std = inception_score(generated_images)
print(f"Inception Score: {is_mean:.4f} ± {is_std:.4f}")
except ImportError:
print("Inception Score requires 'torch-fidelity' package")from typing import Union, Optional, Tuple
import torch
from torch import Tensor
ImageTensor = Tensor # Shape: (N, C, H, W) or (C, H, W)
ReductionType = Union["elementwise_mean", "sum", "none"]
InterpolationType = Union["lerp", "slerp"]Install with Tessl CLI
npx tessl i tessl/pypi-torchmetrics