File size: 9,312 Bytes
455ba60 |
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
#!/usr/bin/env python3
"""
Simple Metrics Evaluation for Frequency-Aware Super-Denoiser
============================================================
Calculates PSNR, SSIM, and MSE metrics using existing sampling methods
"""
import torch
import torch.nn.functional as F
import numpy as np
from PIL import Image
import os
from skimage.metrics import structural_similarity as ssim
import matplotlib.pyplot as plt
# Import model components
from model import SmoothDiffusionUNet
from noise_scheduler import FrequencyAwareNoise
from config import Config
from dataloader import get_dataloaders
from sample import frequency_aware_sample
def calculate_psnr(img1, img2, max_val=2.0):
"""Calculate PSNR between two images"""
mse = F.mse_loss(img1, img2)
if mse == 0:
return float('inf')
return 20 * torch.log10(torch.tensor(max_val) / torch.sqrt(mse))
def calculate_ssim(img1, img2):
"""Calculate SSIM between two images"""
# Convert to numpy and ensure proper format
img1_np = img1.detach().cpu().numpy().transpose(1, 2, 0)
img2_np = img2.detach().cpu().numpy().transpose(1, 2, 0)
# Normalize to [0,1]
img1_np = (img1_np + 1) / 2
img2_np = (img2_np + 1) / 2
img1_np = np.clip(img1_np, 0, 1)
img2_np = np.clip(img2_np, 0, 1)
return ssim(img1_np, img2_np, multichannel=True, channel_axis=2, data_range=1.0)
def add_noise(image, noise_level=0.2):
"""Add Gaussian noise to images"""
noise = torch.randn_like(image) * noise_level
return torch.clamp(image + noise, -1, 1)
def evaluate_model():
"""Simplified model evaluation using existing sampling methods"""
print("π FREQUENCY-AWARE SUPER-DENOISER METRICS EVALUATION")
print("=" * 60)
# Setup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config = Config()
# Load model
model = SmoothDiffusionUNet(config).to(device)
if os.path.exists('model_final.pth'):
checkpoint = torch.load('model_final.pth', map_location=device, weights_only=False)
model.load_state_dict(checkpoint)
print("β
Model loaded successfully")
else:
print("β No trained model found! Please run training first.")
return
model.eval()
scheduler = FrequencyAwareNoise(config)
# Get test data
try:
_, test_loader = get_dataloaders(config)
print(f"β
Test data loaded: {len(test_loader)} batches")
except:
print("β Could not load test data")
return
# Evaluation metrics storage
metrics = {
'reconstruction_mse': [],
'reconstruction_psnr': [],
'reconstruction_ssim': [],
'enhancement_mse': [],
'enhancement_psnr': [],
'enhancement_ssim': []
}
print("\nπ Evaluating reconstruction quality...")
with torch.no_grad():
for i, (images, _) in enumerate(test_loader):
if i >= 20: # Evaluate on 20 batches for speed
break
images = images.to(device)
batch_size = min(4, images.shape[0]) # Process 4 images at a time
images = images[:batch_size]
print(f" Processing batch {i+1}/20...")
# Test 1: Reconstruction from low noise
# Add light noise and see how well we can reconstruct
lightly_noisy = add_noise(images, noise_level=0.1)
# Apply noise using the scheduler
t_light = torch.full((batch_size,), 50, device=device, dtype=torch.long) # Light noise
noisy_imgs, noise_spatial = scheduler.apply_noise(images, t_light)
# Reconstruct by predicting the noise
predicted_noise = model(noisy_imgs, t_light)
# Simple reconstruction
alpha_bar = scheduler.alpha_bars[50].item()
reconstructed = (noisy_imgs - np.sqrt(1 - alpha_bar) * predicted_noise) / np.sqrt(alpha_bar)
# Calculate reconstruction metrics
for j in range(batch_size):
original = images[j]
recon = reconstructed[j]
# MSE
mse_val = F.mse_loss(original, recon).item()
metrics['reconstruction_mse'].append(mse_val)
# PSNR
psnr_val = calculate_psnr(original, recon, max_val=2.0).item()
metrics['reconstruction_psnr'].append(psnr_val)
# SSIM
ssim_val = calculate_ssim(original, recon)
metrics['reconstruction_ssim'].append(ssim_val)
# Test 2: Enhancement from noisy images
# Add more significant noise and test enhancement
noisy_enhanced = add_noise(images, noise_level=0.3)
# Apply heavier noise with scheduler
t_heavy = torch.full((batch_size,), 150, device=device, dtype=torch.long)
heavy_noisy, _ = scheduler.apply_noise(images, t_heavy)
# Multi-step denoising simulation
enhanced = heavy_noisy.clone()
timesteps = [150, 100, 50, 25, 10, 5, 1]
for t_val in timesteps:
t_tensor = torch.full((batch_size,), max(t_val, 0), device=device, dtype=torch.long)
pred_noise = model(enhanced, t_tensor)
# Simple denoising step
if t_val > 0:
alpha_bar = scheduler.alpha_bars[t_val].item()
enhanced = (enhanced - 0.1 * pred_noise)
enhanced = torch.clamp(enhanced, -1, 1)
# Calculate enhancement metrics
for j in range(batch_size):
original = images[j]
enhanced_img = enhanced[j]
mse_val = F.mse_loss(original, enhanced_img).item()
metrics['enhancement_mse'].append(mse_val)
psnr_val = calculate_psnr(original, enhanced_img, max_val=2.0).item()
metrics['enhancement_psnr'].append(psnr_val)
ssim_val = calculate_ssim(original, enhanced_img)
metrics['enhancement_ssim'].append(ssim_val)
# Calculate final statistics
print("\nπ FINAL METRICS RESULTS:")
print("=" * 60)
print("π― RECONSTRUCTION PERFORMANCE (Light Noise β Original):")
recon_mse = np.mean(metrics['reconstruction_mse'])
recon_psnr = np.mean(metrics['reconstruction_psnr'])
recon_ssim = np.mean(metrics['reconstruction_ssim'])
print(f" MSE: {recon_mse:.6f} Β± {np.std(metrics['reconstruction_mse']):.6f}")
print(f" PSNR: {recon_psnr:.2f} Β± {np.std(metrics['reconstruction_psnr']):.2f} dB")
print(f" SSIM: {recon_ssim:.4f} Β± {np.std(metrics['reconstruction_ssim']):.4f}")
print("\nπ§Ή ENHANCEMENT PERFORMANCE (Heavy Noise β Original):")
enh_mse = np.mean(metrics['enhancement_mse'])
enh_psnr = np.mean(metrics['enhancement_psnr'])
enh_ssim = np.mean(metrics['enhancement_ssim'])
print(f" MSE: {enh_mse:.6f} Β± {np.std(metrics['enhancement_mse']):.6f}")
print(f" PSNR: {enh_psnr:.2f} Β± {np.std(metrics['enhancement_psnr']):.2f} dB")
print(f" SSIM: {enh_ssim:.4f} Β± {np.std(metrics['enhancement_ssim']):.4f}")
# Generate performance grades
def grade_metric(value, thresholds, metric_name):
if metric_name == 'MSE':
if value < thresholds[0]: return "Excellent β
"
elif value < thresholds[1]: return "Very Good π’"
elif value < thresholds[2]: return "Good π΅"
else: return "Fair π‘"
else: # PSNR, SSIM
if value > thresholds[0]: return "Excellent β
"
elif value > thresholds[1]: return "Very Good π’"
elif value > thresholds[2]: return "Good π΅"
else: return "Fair π‘"
print("\nπ RECONSTRUCTION GRADES:")
print(f" MSE: {grade_metric(recon_mse, [0.01, 0.05, 0.1], 'MSE')}")
print(f" PSNR: {grade_metric(recon_psnr, [35, 30, 25], 'PSNR')}")
print(f" SSIM: {grade_metric(recon_ssim, [0.9, 0.8, 0.7], 'SSIM')}")
print("\nπ ENHANCEMENT GRADES:")
print(f" MSE: {grade_metric(enh_mse, [0.05, 0.1, 0.2], 'MSE')}")
print(f" PSNR: {grade_metric(enh_psnr, [30, 25, 20], 'PSNR')}")
print(f" SSIM: {grade_metric(enh_ssim, [0.85, 0.75, 0.65], 'SSIM')}")
# Create summary for README
print("\nπ SUMMARY FOR README:")
print("=" * 60)
print("Reconstruction Performance:")
print(f"- MSE: {recon_mse:.6f}")
print(f"- PSNR: {recon_psnr:.1f} dB")
print(f"- SSIM: {recon_ssim:.4f}")
print("\nEnhancement Performance:")
print(f"- MSE: {enh_mse:.6f}")
print(f"- PSNR: {enh_psnr:.1f} dB")
print(f"- SSIM: {enh_ssim:.4f}")
print("\nπ Metrics evaluation completed!")
return {
'recon_mse': recon_mse,
'recon_psnr': recon_psnr,
'recon_ssim': recon_ssim,
'enh_mse': enh_mse,
'enh_psnr': enh_psnr,
'enh_ssim': enh_ssim
}
if __name__ == "__main__":
evaluate_model()
|