initial commit
This commit is contained in:
commit
c7175dd7ff
127 files changed
+13949
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
|
||||
|
||||
The FID metric calculates the distance between two distributions of images.
|
||||
Typically, we have summary statistics (mean & covariance matrix) of one
|
||||
of these distributions, while the 2nd distribution is given by a GAN.
|
||||
|
||||
When run as a stand-alone program, it compares the distribution of
|
||||
images that are stored as PNG/JPEG at a specified location with a
|
||||
distribution given by summary statistics (in pickle format).
|
||||
|
||||
The FID is calculated by assuming that X_1 and X_2 are the activations of
|
||||
the pool_3 layer of the inception net for generated samples and real world
|
||||
samples respectively.
|
||||
|
||||
See --help to see further details.
|
||||
|
||||
Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead
|
||||
of Tensorflow
|
||||
|
||||
Copyright 2018 Institute of Bioinformatics, JKU Linz
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from scipy.misc import imread
|
||||
from scipy import linalg
|
||||
from torch.autograd import Variable
|
||||
from torch.nn.functional import adaptive_avg_pool2d
|
||||
|
||||
from metrics.inception import InceptionV3
|
||||
|
||||
|
||||
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument('path', type=str, nargs=2,
|
||||
help=('Path to the generated images or '
|
||||
'to .npz statistic files'))
|
||||
parser.add_argument('--batch-size', type=int, default=64,
|
||||
help='Batch size to use')
|
||||
parser.add_argument('--dims', type=int, default=2048,
|
||||
choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),
|
||||
help=('Dimensionality of Inception features to use. '
|
||||
'By default, uses pool3 features'))
|
||||
parser.add_argument('-c', '--gpu', default='', type=str,
|
||||
help='GPU to use (leave blank for CPU only)')
|
||||
|
||||
|
||||
def get_activations(images, model, batch_size=64, dims=2048,
|
||||
cuda=False, verbose=False):
|
||||
"""Calculates the activations of the pool_3 layer for all images.
|
||||
|
||||
Params:
|
||||
-- images : Numpy array of dimension (n_images, 3, hi, wi). The values
|
||||
must lie between 0 and 1.
|
||||
-- model : Instance of inception model
|
||||
-- batch_size : the images numpy array is split into batches with
|
||||
batch size batch_size. A reasonable batch size depends
|
||||
on the hardware.
|
||||
-- dims : Dimensionality of features returned by Inception
|
||||
-- cuda : If set to True, use GPU
|
||||
-- verbose : If set to True and parameter out_step is given, the number
|
||||
of calculated batches is reported.
|
||||
Returns:
|
||||
-- A numpy array of dimension (num images, dims) that contains the
|
||||
activations of the given tensor when feeding inception with the
|
||||
query tensor.
|
||||
"""
|
||||
model.eval()
|
||||
|
||||
d0 = images.shape[0]
|
||||
if batch_size > d0:
|
||||
print(('Warning: batch size is bigger than the data size. '
|
||||
'Setting batch size to data size'))
|
||||
batch_size = d0
|
||||
|
||||
n_batches = d0 // batch_size
|
||||
n_used_imgs = n_batches * batch_size
|
||||
|
||||
pred_arr = np.empty((n_used_imgs, dims))
|
||||
for i in range(n_batches):
|
||||
if verbose:
|
||||
print('\rPropagating batch %d/%d' % (i + 1, n_batches),
|
||||
end='', flush=True)
|
||||
start = i * batch_size
|
||||
end = start + batch_size
|
||||
|
||||
batch = torch.from_numpy(images[start:end]).type(torch.FloatTensor)
|
||||
batch = Variable(batch)
|
||||
if cuda:
|
||||
batch = batch.cuda()
|
||||
|
||||
with torch.no_grad():
|
||||
pred = model(batch)[0]
|
||||
|
||||
# If model output is not scalar, apply global spatial average pooling.
|
||||
# This happens if you choose a dimensionality not equal 2048.
|
||||
if pred.shape[2] != 1 or pred.shape[3] != 1:
|
||||
pred = adaptive_avg_pool2d(pred, output_size=(1, 1))
|
||||
|
||||
pred_arr[start:end] = pred.cpu().data.numpy().reshape(batch_size, -1)
|
||||
|
||||
if verbose:
|
||||
print(' done')
|
||||
|
||||
return pred_arr
|
||||
|
||||
|
||||
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
|
||||
"""Numpy implementation of the Frechet Distance.
|
||||
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
|
||||
and X_2 ~ N(mu_2, C_2) is
|
||||
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
|
||||
|
||||
Stable version by Dougal J. Sutherland.
|
||||
|
||||
Params:
|
||||
-- mu1 : Numpy array containing the activations of a layer of the
|
||||
inception net (like returned by the function 'get_predictions')
|
||||
for generated samples.
|
||||
-- mu2 : The sample mean over activations, precalculated on an
|
||||
representative data set.
|
||||
-- sigma1: The covariance matrix over activations for generated samples.
|
||||
-- sigma2: The covariance matrix over activations, precalculated on an
|
||||
representative data set.
|
||||
|
||||
Returns:
|
||||
-- : The Frechet Distance.
|
||||
"""
|
||||
|
||||
mu1 = np.atleast_1d(mu1)
|
||||
mu2 = np.atleast_1d(mu2)
|
||||
|
||||
sigma1 = np.atleast_2d(sigma1)
|
||||
sigma2 = np.atleast_2d(sigma2)
|
||||
|
||||
assert mu1.shape == mu2.shape, \
|
||||
'Training and test mean vectors have different lengths'
|
||||
assert sigma1.shape == sigma2.shape, \
|
||||
'Training and test covariances have different dimensions'
|
||||
|
||||
diff = mu1 - mu2
|
||||
|
||||
# Product might be almost singular
|
||||
covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
|
||||
if not np.isfinite(covmean).all():
|
||||
msg = ('fid calculation produces singular product; '
|
||||
'adding %s to diagonal of cov estimates') % eps
|
||||
print(msg)
|
||||
offset = np.eye(sigma1.shape[0]) * eps
|
||||
covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
|
||||
|
||||
# Numerical error might give slight imaginary component
|
||||
if np.iscomplexobj(covmean):
|
||||
if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
|
||||
m = np.max(np.abs(covmean.imag))
|
||||
raise ValueError('Imaginary component {}'.format(m))
|
||||
covmean = covmean.real
|
||||
|
||||
tr_covmean = np.trace(covmean)
|
||||
|
||||
return (diff.dot(diff) + np.trace(sigma1) +
|
||||
np.trace(sigma2) - 2 * tr_covmean)
|
||||
|
||||
|
||||
def calculate_activation_statistics(images, model, batch_size=64,
|
||||
dims=2048, cuda=False, verbose=False):
|
||||
"""Calculation of the statistics used by the FID.
|
||||
Params:
|
||||
-- images : Numpy array of dimension (n_images, 3, hi, wi). The values
|
||||
must lie between 0 and 1.
|
||||
-- model : Instance of inception model
|
||||
-- batch_size : The images numpy array is split into batches with
|
||||
batch size batch_size. A reasonable batch size
|
||||
depends on the hardware.
|
||||
-- dims : Dimensionality of features returned by Inception
|
||||
-- cuda : If set to True, use GPU
|
||||
-- verbose : If set to True and parameter out_step is given, the
|
||||
number of calculated batches is reported.
|
||||
Returns:
|
||||
-- mu : The mean over samples of the activations of the pool_3 layer of
|
||||
the inception model.
|
||||
-- sigma : The covariance matrix of the activations of the pool_3 layer of
|
||||
the inception model.
|
||||
"""
|
||||
act = get_activations(images, model, batch_size, dims, cuda, verbose)
|
||||
mu = np.mean(act, axis=0)
|
||||
sigma = np.cov(act, rowvar=False)
|
||||
return mu, sigma
|
||||
|
||||
|
||||
def _compute_statistics_of_path(path, model, batch_size, dims, cuda):
|
||||
if path.endswith('.npz'):
|
||||
f = np.load(path)
|
||||
m, s = f['mu'][:], f['sigma'][:]
|
||||
f.close()
|
||||
else:
|
||||
path = pathlib.Path(path)
|
||||
files = list(path.glob('*.jpg')) + list(path.glob('*.png'))
|
||||
|
||||
imgs = np.array([imread(str(fn)).astype(np.float32) for fn in files])
|
||||
|
||||
# Bring images to shape (B, 3, H, W)
|
||||
imgs = imgs.transpose((0, 3, 1, 2))
|
||||
|
||||
# Rescale images to be between 0 and 1
|
||||
imgs /= 255
|
||||
|
||||
m, s = calculate_activation_statistics(imgs, model, batch_size,
|
||||
dims, cuda)
|
||||
|
||||
return m, s
|
||||
|
||||
|
||||
def calculate_fid_given_paths(paths, batch_size, cuda, dims):
|
||||
"""Calculates the FID of two paths"""
|
||||
for p in paths:
|
||||
if not os.path.exists(p):
|
||||
raise RuntimeError('Invalid path: %s' % p)
|
||||
|
||||
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
|
||||
|
||||
model = InceptionV3([block_idx])
|
||||
if cuda:
|
||||
model.cuda()
|
||||
|
||||
m1, s1 = _compute_statistics_of_path(paths[0], model, batch_size,
|
||||
dims, cuda)
|
||||
m2, s2 = _compute_statistics_of_path(paths[1], model, batch_size,
|
||||
dims, cuda)
|
||||
fid_value = calculate_frechet_distance(m1, s1, m2, s2)
|
||||
|
||||
return fid_value
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = parser.parse_args()
|
||||
# os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
|
||||
|
||||
fid_value = calculate_fid_given_paths(args.path,
|
||||
args.batch_size,
|
||||
args.gpu != '',
|
||||
args.dims)
|
||||
print('FID: ', fid_value)
|
||||
@@ -0,0 +1,139 @@
|
||||
import torch
|
||||
import numpy as np
|
||||
from sklearn.metrics import f1_score as fs
|
||||
# https://github.com/Jarvisgivemeasuit/DPANet-Pytorch/blob/master/utils/utils.py
|
||||
|
||||
class PixelAccuracy:
|
||||
def __init__(self, ignore_index=-1, eps=1e-7):
|
||||
self.num_correct = 0
|
||||
self.num_instance = 0
|
||||
self.ignore_index = ignore_index
|
||||
self.eps = eps
|
||||
|
||||
def update(self, pred, target):
|
||||
ignore_mask = target != self.ignore_index
|
||||
if pred.size(1) == 1:
|
||||
pred = torch.sigmoid(pred)
|
||||
pred = pred > 0.5
|
||||
else:
|
||||
pred = torch.argmax(pred, dim=1)
|
||||
|
||||
self.num_correct += ((pred.long() == target.long()) * ignore_mask).sum().item()
|
||||
self.num_instance += ignore_mask.sum().item()
|
||||
|
||||
def get(self):
|
||||
return self.num_correct / (self.num_instance + self.eps)
|
||||
|
||||
def reset(self):
|
||||
self.num_correct = 0
|
||||
self.num_instance = 0
|
||||
|
||||
|
||||
class MeanIoU:
|
||||
def __init__(self, num_classes, eps=1e-7):
|
||||
if num_classes == 1:
|
||||
self.num_classes = num_classes + 1
|
||||
else:
|
||||
self.num_classes = num_classes
|
||||
self.num_intersection = np.zeros(self.num_classes)
|
||||
self.num_union = np.zeros(self.num_classes)
|
||||
self.eps = eps
|
||||
|
||||
def update(self, pred, target):
|
||||
if pred.size(1) == 1:
|
||||
pred = torch.sigmoid(pred)
|
||||
pred = pred > 0.5
|
||||
else:
|
||||
pred = torch.argmax(pred, dim=1)
|
||||
|
||||
for cur_cls in range(self.num_classes):
|
||||
pred_mask = (pred == cur_cls).byte()
|
||||
target_mask = (target == cur_cls).byte()
|
||||
|
||||
intersection = (pred_mask & target_mask).float().sum()
|
||||
union = (pred_mask | target_mask).float().sum()
|
||||
|
||||
self.num_intersection[cur_cls] += intersection.item()
|
||||
self.num_union[cur_cls] += union.item()
|
||||
|
||||
def get(self, ignore_background=False):
|
||||
if ignore_background:
|
||||
iou_list = (self.num_intersection[:-1] / (self.num_union[:-1] + self.eps))
|
||||
return iou_list.mean(), iou_list.max(), np.where(iou_list == iou_list.max()), iou_list.min(), np.where(iou_list == iou_list.min())
|
||||
else:
|
||||
iou_list = (self.num_intersection / (self.num_union + self.eps))
|
||||
return iou_list.mean(), iou_list.max(), np.where(iou_list == iou_list.max()), iou_list.min(), np.where(iou_list == iou_list.min())
|
||||
|
||||
def reset(self):
|
||||
self.num_intersection = np.zeros(self.num_classes)
|
||||
self.num_union = np.zeros(self.num_classes)
|
||||
|
||||
def get_all(self):
|
||||
return (self.num_intersection / (self.num_union + self.eps))
|
||||
|
||||
class Kappa:
|
||||
def __init__(self, num_classes):
|
||||
self.pre_vec = np.zeros(num_classes)
|
||||
self.cor_vec = np.zeros(num_classes)
|
||||
self.tar_vec = np.zeros(num_classes)
|
||||
self.num = num_classes
|
||||
|
||||
def update(self, output, target):
|
||||
pre_array = torch.argmax(output, dim=1)
|
||||
|
||||
for i in range(self.num):
|
||||
pre_mask = (pre_array == i).byte()
|
||||
tar_mask = (target == i).byte()
|
||||
self.cor_vec[i] = (pre_mask & tar_mask).sum().item()
|
||||
self.pre_vec[i] = pre_mask.sum().item()
|
||||
self.tar_vec[i] = tar_mask.sum().item()
|
||||
|
||||
def get(self):
|
||||
assert len(self.pre_vec) == len(self.tar_vec) == len(self.pre_vec)
|
||||
tmp = 0.0
|
||||
for i in range(len(self.tar_vec)):
|
||||
tmp += self.pre_vec[i] * self.tar_vec[i]
|
||||
pe = tmp / (sum(self.tar_vec) ** 2 + 1e-8)
|
||||
p0 = sum(self.cor_vec) / (sum(self.tar_vec) + 1e-8)
|
||||
cohens_coefficient = (p0 - pe) / (1 - pe)
|
||||
return cohens_coefficient
|
||||
|
||||
def reset(self):
|
||||
self.pre_vec = np.zeros(self.num)
|
||||
self.cor_vec = np.zeros(self.num)
|
||||
self.tar_vec = np.zeros(self.num)
|
||||
|
||||
|
||||
class F1:
|
||||
def __init__(self):
|
||||
self.score = 0
|
||||
self.num = 0
|
||||
self.all = np.zeros(16)
|
||||
self.map = None
|
||||
self.map_tar = None
|
||||
|
||||
def update(self, output, target):
|
||||
output = torch.argmax(output, dim=1).reshape(-1).cpu()
|
||||
target = target.reshape(-1).cpu()
|
||||
# output = list(output)
|
||||
# target = list(target)
|
||||
self.score += fs(output, target, average='macro')
|
||||
self.num += 1
|
||||
if self.map == None:
|
||||
self.map = output
|
||||
else:
|
||||
self.map = torch.cat([self.map, output])
|
||||
if self.map_tar == None:
|
||||
self.map_tar = target
|
||||
else:
|
||||
self.map_tar = torch.cat([self.map_tar, target])
|
||||
|
||||
def get(self):
|
||||
return self.score / self.num
|
||||
|
||||
def reset(self):
|
||||
self.score = 0
|
||||
self.num = 0
|
||||
|
||||
def get_all(self):
|
||||
return fs(self.map, self.map_tar, average=None)
|
||||
@@ -0,0 +1,122 @@
|
||||
import numpy as np
|
||||
from sklearn.model_selection import KFold
|
||||
import math
|
||||
from scipy import interpolate
|
||||
|
||||
|
||||
def distance(embeddings1, embeddings2, distance_metric=0):
|
||||
if distance_metric == 0:
|
||||
# Euclidian distance
|
||||
diff = np.subtract(embeddings1, embeddings2)
|
||||
dist = np.sum(np.square(diff), 1)
|
||||
elif distance_metric == 1:
|
||||
# Distance based on cosine similarity
|
||||
dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1)
|
||||
norm = np.linalg.norm(embeddings1, axis=1) * np.linalg.norm(embeddings2, axis=1)
|
||||
similarity = dot / norm
|
||||
dist = np.arccos(similarity) / math.pi
|
||||
else:
|
||||
raise 'Undefined distance metric %d' % distance_metric
|
||||
return dist
|
||||
|
||||
|
||||
def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, distance_metric=0,
|
||||
subtract_mean=False):
|
||||
assert (embeddings1.shape[0] == embeddings2.shape[0])
|
||||
assert (embeddings1.shape[1] == embeddings2.shape[1])
|
||||
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
|
||||
nrof_thresholds = len(thresholds)
|
||||
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
|
||||
|
||||
tprs = np.zeros((nrof_folds, nrof_thresholds))
|
||||
fprs = np.zeros((nrof_folds, nrof_thresholds))
|
||||
accuracy = np.zeros((nrof_folds))
|
||||
|
||||
indices = np.arange(nrof_pairs)
|
||||
|
||||
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
|
||||
if subtract_mean:
|
||||
mean = np.mean(np.concatenate([embeddings1[train_set], embeddings2[train_set]]), axis=0)
|
||||
else:
|
||||
mean = 0.0
|
||||
dist = distance(embeddings1 - mean, embeddings2 - mean, distance_metric)
|
||||
|
||||
# Find the best threshold for the fold
|
||||
acc_train = np.zeros((nrof_thresholds))
|
||||
for threshold_idx, threshold in enumerate(thresholds):
|
||||
_, _, acc_train[threshold_idx] = calculate_accuracy(threshold, dist[train_set], actual_issame[train_set])
|
||||
best_threshold_index = np.argmax(acc_train)
|
||||
for threshold_idx, threshold in enumerate(thresholds):
|
||||
tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy(threshold,
|
||||
dist[test_set],
|
||||
actual_issame[
|
||||
test_set])
|
||||
best_threshold = thresholds[best_threshold_index]
|
||||
_, _, accuracy[fold_idx] = calculate_accuracy(best_threshold, dist[test_set], actual_issame[test_set])
|
||||
# print('Best threshold: {}'.format(best_threshold))
|
||||
tpr = np.mean(tprs, 0)
|
||||
fpr = np.mean(fprs, 0)
|
||||
return tpr, fpr, accuracy
|
||||
|
||||
|
||||
def calculate_accuracy(threshold, dist, actual_issame):
|
||||
predict_issame = np.less(dist, threshold)
|
||||
tp = np.sum(np.logical_and(predict_issame, actual_issame))
|
||||
fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
|
||||
tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_not(actual_issame)))
|
||||
fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))
|
||||
|
||||
tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)
|
||||
fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)
|
||||
acc = float(tp + tn) / dist.size
|
||||
return tpr, fpr, acc
|
||||
|
||||
|
||||
def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10, distance_metric=0,
|
||||
subtract_mean=False):
|
||||
assert (embeddings1.shape[0] == embeddings2.shape[0])
|
||||
assert (embeddings1.shape[1] == embeddings2.shape[1])
|
||||
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
|
||||
nrof_thresholds = len(thresholds)
|
||||
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
|
||||
|
||||
val = np.zeros(nrof_folds)
|
||||
far = np.zeros(nrof_folds)
|
||||
|
||||
indices = np.arange(nrof_pairs)
|
||||
|
||||
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
|
||||
if subtract_mean:
|
||||
mean = np.mean(np.concatenate([embeddings1[train_set], embeddings2[train_set]]), axis=0)
|
||||
else:
|
||||
mean = 0.0
|
||||
dist = distance(embeddings1 - mean, embeddings2 - mean, distance_metric)
|
||||
|
||||
# Find the threshold that gives FAR = far_target
|
||||
far_train = np.zeros(nrof_thresholds)
|
||||
for threshold_idx, threshold in enumerate(thresholds):
|
||||
_, far_train[threshold_idx] = calculate_val_far(threshold, dist[train_set], actual_issame[train_set])
|
||||
if np.max(far_train) >= far_target:
|
||||
f = interpolate.interp1d(far_train, thresholds, kind='slinear')
|
||||
threshold = f(far_target)
|
||||
else:
|
||||
threshold = 0.0
|
||||
|
||||
val[fold_idx], far[fold_idx] = calculate_val_far(threshold, dist[test_set], actual_issame[test_set])
|
||||
|
||||
val_mean = np.mean(val)
|
||||
far_mean = np.mean(far)
|
||||
val_std = np.std(val)
|
||||
|
||||
|
||||
return val_mean, val_std, far_mean
|
||||
|
||||
def calculate_val_far(threshold, dist, actual_issame):
|
||||
predict_issame = np.less(dist, threshold)
|
||||
true_accept = np.sum(np.logical_and(predict_issame, actual_issame))
|
||||
false_accept = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
|
||||
n_same = np.sum(actual_issame)
|
||||
n_diff = np.sum(np.logical_not(actual_issame))
|
||||
val = float(true_accept) / float(n_same)
|
||||
far = float(false_accept) / float(n_diff)
|
||||
return val, far
|
||||
@@ -0,0 +1,228 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from math import exp
|
||||
import numpy as np
|
||||
|
||||
|
||||
# Classes to re-use window
|
||||
class SSIM(torch.nn.Module):
|
||||
def __init__(self, window_size=11, size_average=True, val_range=None):
|
||||
super(SSIM, self).__init__()
|
||||
self.window_size = window_size
|
||||
self.size_average = size_average
|
||||
self.val_range = val_range
|
||||
|
||||
# Assume 1 channel for SSIM
|
||||
self.channel = 1
|
||||
self.window = create_window(window_size)
|
||||
self.cs_map = None
|
||||
|
||||
def forward(self, img1, img2):
|
||||
(_, channel, _, _) = img1.size()
|
||||
|
||||
if channel == self.channel and self.window.dtype == img1.dtype:
|
||||
window = self.window
|
||||
else:
|
||||
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
|
||||
self.window = window
|
||||
self.channel = channel
|
||||
|
||||
cs, self.cs_map = ssim(img1, img2, -1, window, size_average=self.size_average, full=True)
|
||||
return cs
|
||||
|
||||
|
||||
class MSSSIM(torch.nn.Module):
|
||||
def __init__(self, window_size=11, size_average=True):
|
||||
super(MSSSIM, self).__init__()
|
||||
self.window_size = window_size
|
||||
self.size_average = size_average
|
||||
self.channel = None
|
||||
self.window = None
|
||||
|
||||
def forward(self, img1, img2):
|
||||
(_, channel, _, _) = img1.size()
|
||||
|
||||
if self.window is not None and channel == self.channel and self.window.dtype == img1.dtype:
|
||||
window = self.window
|
||||
else:
|
||||
print("MSSIM: Creating window...")
|
||||
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
|
||||
self.window = window
|
||||
self.channel = channel
|
||||
# return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average, window=window)
|
||||
return msssim_simple(img1, img2, window_size=self.window_size, size_average=self.size_average, window=window)
|
||||
|
||||
|
||||
#############################################
|
||||
# Function
|
||||
|
||||
def gaussian(window_size, sigma):
|
||||
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
|
||||
return gauss/gauss.sum()
|
||||
|
||||
|
||||
def create_window(window_size, channel=1):
|
||||
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
||||
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
|
||||
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
|
||||
return window
|
||||
|
||||
|
||||
def structsim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
|
||||
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
||||
if val_range is None:
|
||||
if torch.max(img1) > 128:
|
||||
max_val = 255
|
||||
else:
|
||||
max_val = 1
|
||||
|
||||
if torch.min(img1) < -0.5:
|
||||
min_val = -1
|
||||
else:
|
||||
min_val = 0
|
||||
L = max_val - min_val
|
||||
else:
|
||||
L = val_range
|
||||
|
||||
# padd = 10
|
||||
padd = 0
|
||||
(_, channel, height, width) = img1.size()
|
||||
if window is None:
|
||||
real_size = min(window_size, height, width)
|
||||
window = create_window(real_size, channel=channel).to(img1.device)
|
||||
|
||||
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
||||
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
||||
|
||||
mu1_sq = mu1.pow(2)
|
||||
mu2_sq = mu2.pow(2)
|
||||
mu1_mu2 = mu1 * mu2
|
||||
|
||||
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
||||
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
||||
sigma1 = sigma1_sq.clamp(min=0)**0.5
|
||||
sigma2 = sigma2_sq.clamp(min=0)**0.5
|
||||
# sigma1_test = F.conv2d((img1 - mu1)**2, window, padding=padd, groups=channel)
|
||||
# sigma1_sq_test = sigma1_test.pow(2)
|
||||
|
||||
|
||||
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
||||
|
||||
C1 = (0.01 * L) ** 2
|
||||
C2 = (0.03 * L) ** 2
|
||||
|
||||
# v1 = 2.0 * sigma12 + C2
|
||||
# v2 = sigma1_sq + sigma2_sq + C2
|
||||
# cs = torch.mean(v1 / v2) # contrast sensitivity
|
||||
|
||||
l = (2 * mu1_mu2 + C1) / (mu1_sq + mu2_sq + C1)
|
||||
c = (2 * sigma1 * sigma2 + C2) / (sigma1_sq + sigma2_sq + C2)
|
||||
s = (sigma12 + (C2/2.0)) / (sigma1 * sigma2 + (C2/2.0))
|
||||
|
||||
# cs_mean = (c * s).mean()
|
||||
# cs_mean_prod = c.mean() * s.mean()
|
||||
|
||||
return l.mean(), c.mean(), s.mean()
|
||||
|
||||
|
||||
# from datasets.ds_utils import denormalized
|
||||
def ssim(img1, img2, window_size=-1, window=None, size_average=True, full=False, val_range=None):
|
||||
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
||||
# img1 = denormalized(img1).clamp(min=0)
|
||||
# img2 = denormalized(img2).clamp(min=0)
|
||||
|
||||
if val_range is None:
|
||||
if torch.max(img1) > 128:
|
||||
max_val = 255
|
||||
else:
|
||||
max_val = 1
|
||||
|
||||
if torch.min(img1) < -0.5:
|
||||
min_val = -1
|
||||
else:
|
||||
min_val = 0
|
||||
L = max_val - min_val
|
||||
else:
|
||||
L = val_range
|
||||
|
||||
padd = 0
|
||||
(_, channel, height, width) = img1.size()
|
||||
if window is None:
|
||||
if window_size > 0:
|
||||
real_size = min(window_size, height, width)
|
||||
window = create_window(real_size, channel=channel).to(img1.device)
|
||||
else:
|
||||
raise ValueError("If window not supplied, window_size must be non negative.")
|
||||
|
||||
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
||||
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
||||
|
||||
mu1_sq = mu1.pow(2)
|
||||
mu2_sq = mu2.pow(2)
|
||||
mu1_mu2 = mu1 * mu2
|
||||
|
||||
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
||||
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
||||
# sigma1_sq = sigma1_sq.clamp(min=0)**0.5
|
||||
# sigma2_sq = sigma2_sq.clamp(min=0)**0.5
|
||||
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
||||
|
||||
# C1 = (0.01 * L) ** 2
|
||||
C2 = (0.03 * L) ** 2
|
||||
|
||||
v1 = 2.0 * sigma12 + C2
|
||||
v2 = sigma1_sq + sigma2_sq + C2
|
||||
cs_map = v1 / v2 # contrast sensitivity
|
||||
cs = torch.mean(cs_map) # contrast sensitivity
|
||||
|
||||
# sigma1 = sigma1_sq.clamp(min=0)**0.5
|
||||
# sigma2 = sigma2_sq.clamp(min=0)**0.5
|
||||
# c = (2 * sigma1 * sigma2 + C2) / (sigma1_sq + sigma2_sq + C2)
|
||||
|
||||
# ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
|
||||
|
||||
if full:
|
||||
return cs, cs_map
|
||||
return cs
|
||||
|
||||
|
||||
|
||||
def msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False, window=None):
|
||||
device = img1.device
|
||||
# weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device)
|
||||
weights = torch.FloatTensor([0.0448, 0.2856, 0.3001]).to(device)
|
||||
levels = weights.size()[0]
|
||||
# mssim = []
|
||||
mcs = []
|
||||
for _ in range(levels):
|
||||
cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=False, val_range=val_range, window=window)
|
||||
# mssim.append(sim)
|
||||
mcs.append(cs)
|
||||
|
||||
img1 = F.avg_pool2d(img1, (2, 2))
|
||||
img2 = F.avg_pool2d(img2, (2, 2))
|
||||
|
||||
# mssim = torch.stack(mssim)
|
||||
mcs = torch.stack(mcs)
|
||||
|
||||
# Normalize (to avoid NaNs during training unstable models, not compliant with original definition)
|
||||
if normalize:
|
||||
# mssim = (mssim + 1) / 2
|
||||
mcs = (mcs + 1) / 2
|
||||
|
||||
# pow1 = mcs ** weights
|
||||
# pow2 = mssim ** weights
|
||||
# From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/
|
||||
# output = torch.prod(pow1[:-1]) * pow2[-1]
|
||||
output = mcs[1]
|
||||
return output
|
||||
|
||||
|
||||
def msssim_simple(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False, window=None):
|
||||
k = (2,2)
|
||||
img1 = F.avg_pool2d(img1, k)
|
||||
img2 = F.avg_pool2d(img2, k)
|
||||
cs = ssim(img1, img2, window_size=window_size, size_average=size_average, val_range=val_range, window=window)
|
||||
return cs
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
## Tripelet Loss
|
||||
## Core Idea:
|
||||
## The distance of Anchor and Positive should greater than the distance of Achore and Negative.
|
||||
## L(A, P, N) = max(||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 + a, 0)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
class AverageMeter:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
self.sum = 0
|
||||
self.avg = 0
|
||||
self.val = 0
|
||||
|
||||
def reset(self):
|
||||
self.count = 0
|
||||
self.sum = 0
|
||||
self.avg = 0
|
||||
self.val = 0
|
||||
|
||||
def update(self, val, n=1):
|
||||
self.val = val
|
||||
self.sum += val * n
|
||||
self.count += n
|
||||
self.avg = self.sum / self.count
|
||||
|
||||
|
||||
|
||||
class AverageMeterDict:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
self.sum_dict = {}
|
||||
self.avg_dict = {}
|
||||
self.val_dict = {}
|
||||
|
||||
def reset(self):
|
||||
self.count = 0
|
||||
self.sum_dict = {}
|
||||
self.avg_dict = {}
|
||||
self.val_dict = {}
|
||||
|
||||
def update(self, adict, n=1):
|
||||
|
||||
self.count += n
|
||||
|
||||
# first init
|
||||
if len(self.val_dict) == 0 :
|
||||
self.val_dict = adict.copy()
|
||||
self.sum_dict = adict.copy()
|
||||
self.avg_dict = adict.copy()
|
||||
|
||||
else:
|
||||
for key, item in adict.items():
|
||||
self.val_dict[key] = item
|
||||
self.sum_dict[key] += item * n
|
||||
self.avg_dict[key] = (self.sum_dict[key] / self.count)
|
||||
|
||||
|
||||
def print_msg(self, debug="avg", split=""):
|
||||
msg = ""
|
||||
|
||||
if debug == "sum":
|
||||
tmp_dict = self.avg_dict
|
||||
elif debug == "val":
|
||||
tmp_dict = self.val_dict
|
||||
else:
|
||||
tmp_dict = self.avg_dict
|
||||
|
||||
for (key, item) in tmp_dict.items():
|
||||
msg += f"{key}={item:0.6f} {split}"
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user