-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStyleLoss.py
49 lines (34 loc) · 1.09 KB
/
StyleLoss.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 30 22:50:22 2018
@author: megamind
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
class StyleLoss(nn.Module):
def __init__(self, target):
super(StyleLoss, self).__init__()
self.target = self.get_gram_matrix(target.detach())
def get_gram_matrix(self, inp):
#bs: Batch Size
#ch: input channels. 3 for RGB image
#h: image height
#w= image width
bs, ch, h, w = inp.data.size()
feats = inp.view(bs*ch,h*w)
G = torch.mm(feats,feats.t())
#return normalized Gram matrix
return G.div(bs*ch*h*w)
def forward(self, inp):
#forward pass for our StyleLoss Module
inp_gm = self.get_gram_matrix(inp)
self.loss = F.mse_loss(inp_gm, self.target)
return inp