| import torch
|
| from torch import nn
|
| import torch.nn.functional as F
|
|
|
|
|
| class ContentLoss(nn.Module):
|
|
|
| def __init__(self, target,):
|
| super(ContentLoss, self).__init__()
|
|
|
|
|
|
|
|
|
| self.target = target.detach()
|
|
|
| def forward(self, input):
|
| self.loss = F.mse_loss(input, self.target)
|
| return input
|
|
|
|
|
| class StyleLoss(nn.Module):
|
| """
|
| A class represent the style loss
|
| """
|
| def __init__(self, target_feature):
|
| super(StyleLoss, self).__init__()
|
| self.target = gram_matrix(target_feature).detach()
|
|
|
| def forward(self, input):
|
| G = gram_matrix(input)
|
| self.loss = F.mse_loss(G, self.target)
|
| return input
|
|
|
|
|
| class Normalization(nn.Module):
|
| """
|
| create a module to normalize input image so we can easily put it in a
|
| nn.Sequential
|
| """
|
| def __init__(self, mean, std):
|
| super(Normalization, self).__init__()
|
|
|
|
|
|
|
| self.mean = torch.tensor(mean).view(-1, 1, 1)
|
| self.std = torch.tensor(std).view(-1, 1, 1)
|
|
|
| def forward(self, img):
|
|
|
| return (img - self.mean) / self.std
|
|
|
|
|
| def gram_matrix(mat):
|
| """
|
| Args:
|
| mat: The matrix to calculate on
|
| Returns: Calculation of the gram matrix
|
| """
|
| a, b, c, d = mat.size()
|
|
|
|
|
|
|
| features = mat.view(a * b, c * d)
|
|
|
| G = torch.mm(features, features.t())
|
|
|
|
|
|
|
| return G.div(a * b * c * d) |