Download fid.py from slongle/3DEval: direct link, hf CLI and curl.
- Browser
- Download file 3.34 kB
-
https://huggingface.co/datasets/slongle/3DEval/resolve/main/fid.py
- Command line
-
hf download hf://datasets/slongle/3DEval/fid.py
-
curl -L -o fid.py https://huggingface.co/datasets/slongle/3DEval/resolve/main/fid.py
3.34 kB
| import os | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.utils.data import DataLoader | |
| from torchvision import datasets, transforms, models | |
| import numpy as np | |
| from scipy.linalg import sqrtm | |
| from torchvision.models import inception_v3 | |
| from torch.autograd import Variable | |
| import torch.cuda | |
| # Function to compute FID | |
| def calculate_fid(real_features, generated_features): | |
| mu1 = np.mean(real_features, axis=0) | |
| sigma1 = np.cov(real_features, rowvar=False) | |
| mu2 = np.mean(generated_features, axis=0) | |
| sigma2 = np.cov(generated_features, rowvar=False) | |
| # Calculate sum squared difference between means | |
| ssdiff = np.sum((mu1 - mu2) ** 2.0) | |
| # Calculate sqrt of product between covariances | |
| covmean = sqrtm(sigma1.dot(sigma2)) | |
| # Check for numerical issues | |
| if np.iscomplexobj(covmean): | |
| covmean = covmean.real | |
| fid = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean) | |
| return fid | |
| # Function to get Inception v3 features | |
| def get_features(dataset, model, batch_size=32, dims=2048, cuda=True): | |
| dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False) | |
| model.eval() | |
| features = np.empty((len(dataset), dims)) | |
| start_idx = 0 | |
| for i, (batch, _) in enumerate(dataloader): | |
| if cuda: | |
| batch = batch.cuda() | |
| print(batch.shape) | |
| with torch.no_grad(): | |
| print(type(model(batch))) | |
| pred = model(batch) | |
| print(pred.shape) | |
| print(pred.shape) | |
| pred = F.adaptive_avg_pool2d(pred, output_size=(1, 1)).squeeze(-1).squeeze(-1) | |
| features[start_idx : start_idx + pred.shape[0]] = pred.cpu().numpy() | |
| start_idx = start_idx + pred.shape[0] | |
| return features | |
| # Prepare the datasets | |
| transform = transforms.Compose( | |
| [ | |
| transforms.Resize((299, 299)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ] | |
| ) | |
| real_dataset = datasets.ImageFolder( | |
| "ImageNet/tmp", | |
| transform=transform, | |
| ) | |
| image_root_dir = "/ibex/user/dengj/3DEval/GPTEval3D/data/tournament-3darena/methods" | |
| methods = ["Meshy", "Unique3D", "InstantMesh"] | |
| prompt_idx = 0 | |
| method_idx = 0 | |
| # Replace these paths with your datasets | |
| generated_dataset = datasets.ImageFolder( | |
| os.path.join(image_root_dir, methods[method_idx], str(prompt_idx)), | |
| transform=transform, | |
| is_valid_file=lambda x: os.path.split(x)[-1].startswith("rgb_"), | |
| ) | |
| print(len(generated_dataset)) | |
| # Load the Inception v3 model | |
| inception = inception_v3(pretrained=True, transform_input=False) | |
| if torch.cuda.is_available(): | |
| inception = inception.cuda() | |
| # Extract features | |
| real_features = get_features(real_dataset, inception, cuda=torch.cuda.is_available()) | |
| generated_features = get_features(generated_dataset, inception, cuda=torch.cuda.is_available()) | |
| # Calculate FID | |
| fid_value = calculate_fid(real_features, generated_features) | |
| print(f"FID: {fid_value}") | |
| class WrapperInceptionV3(nn.Module): | |
| def __init__(self, fid_incv3): | |
| super().__init__() | |
| self.fid_incv3 = fid_incv3 | |
| def forward(self, x): | |
| y = self.fid_incv3(x) | |
| y = y[0] | |
| y = y[:, :, 0, 0] | |
| return y | |
| dims = 2048 | |
| block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] | |
| model = InceptionV3([block_idx]).to(device) | |