-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadain_model.py
227 lines (182 loc) · 7.49 KB
/
adain_model.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
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
from io import open
import unicodedata
import string
import re
import random
import time
import math
import torch
import torch.nn as nn
from torch import optim
import torchvision
import torch.nn.functional as F
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import numpy as np
from os import system
from torchsummary import summary
'''
in this file, the output of decoder and adain layer are list!
'''
#the 'f' in paper(encoder)
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.net = torchvision.models.vgg19(pretrained=True)
self.net = self.net.features[:21]
self.net = nn.ModuleList([*self.net])#用list才能插入
self.net = nn.Sequential(*self.net)
for p in self.net.parameters():
p.requires_grad = False
self.layer_name_mapping = [1, 6, 11, 20]
def forward(self, x, only_last):
outs = []
for name, module in self.net._modules.items():
#here name is the number in sequential, so in fact name is a number
x = module(x)
if int(name) in self.layer_name_mapping:
outs.append(x)
if only_last:
return [outs[-1]]#return a list of[(bs, c, h, w)]
else:
return outs#return a list of[(bs, c, h, w), ..., (bs, c, h, w)]
#middle layer(adain)
class adain_layer(nn.Module):
def __init__(self):
super(adain_layer, self).__init__()
def IN(self, x):#input is a (bs, c, h, w) matrix
bs, c, h, w = x.size()
x = x.view(bs, c, -1)
mu_x = x.mean(dim=2).view(bs, c, 1, 1)#(bs, c, 1, 1)
std_x = x.std(dim=2).view(bs, c, 1, 1)#(bs, c, 1 ,1)
return mu_x, std_x
def adain(self, content, style, eps = 1e-8):#c:a fetaure map of content shape(bs, c, h, w)
bs, c, h, w = content.size()
size = [bs, c, h, w]
mu_c, std_c = self.IN(content)#(bs, c, 1, 1)
mu_s, std_s = self.IN(style)#(bs, c, 1, 1)
ada = std_s * ((content - mu_c) / (std_c + eps)) + mu_s
return ada#(bs, c, h, w)
def forward(self, feat_maps_c, feat_maps_s):
'''
input:
feat_maps_c(s): a list with len=4(4 layers), and
each element with shape(bs, c, h, w)
return:
outs:a list with len=4(4 layers), and
each element with shape(h, w)
[(bs, h, w), (bs, h, w), (bs, h, w), (bs, h, w)]
'''
#input[bs, c, h, w], please squeeze matrix before use
outs = []
for feat_map_c, feat_map_s in zip(feat_maps_c, feat_maps_s):
#calculate the outcome layer by layer
out = self.adain(feat_map_c, feat_map_s)
outs.append(out)
return outs# a list
#outs [(bs, c, h, w), (bs, c, h, w), (bs, c, h, w), (bs, c, h, w)] for 4 layers
#the 'g' in decoder
class Decoder(nn.Module):
def __init__(self):
super(Decoder, self).__init__()
self.layer1 = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(512, 256, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True)
)
self.layer2 = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(256, 128, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
)
self.layer3 = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
)
self.layer4 = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=0),
nn.ReLU(inplace=True),
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(64, 3, kernel_size=(3, 3), stride=(1, 1), padding=0),
# nn.ReLU(inplace=True),
)
def forward(self, x):
x = self.layer1(x)
x = F.interpolate(x, scale_factor=2)
x = self.layer2(x)
x = F.interpolate(x, scale_factor=2)
x = self.layer3(x)
x = F.interpolate(x, scale_factor=2)
out = self.layer4(x)
return out
class StyleTranserNetwork(nn.Module):
'''
this model combine encoder, adain, decoder in the model
'''
def __init__(self):
super(StyleTranserNetwork, self).__init__()
self.encoder = Encoder()
self.adain_layer = adain_layer()
self.decoder = Decoder()
def content_loss(self, out_features, t):
'''
out-features=f(g(t))=>decode t and then encode t
, thus we have f(g(t))
The content loss is the Euclidean distance
between the target features and the
features of the output image.
'''
return F.mse_loss(out_features, t)
def style_loss(self, content_feats, style_feats):
'''
input:
content_feats is a list with feat extraction from 4 layers
style_feats is also a list with feat extraction from 4 layers
every feats of 4 layers
let mean c close to mean s, and the same is std
'''
loss = 0
for c, s in zip(content_feats, style_feats):
mu_c, std_c = self.adain_layer.IN(c)
mu_s, std_s = self.adain_layer.IN(s)
loss_mix = F.mse_loss(mu_c, mu_s) + F.mse_loss(std_c, std_s)
loss += loss_mix
return loss
def forward(self, c_imgs, s_imgs, alpha=1, lam=10):
clist, slist = self.encoder(c_imgs, only_last=True), self.encoder(s_imgs, only_last=True)
#return two list with len = 1 both, because the para only_last=true
outlist = self.adain_layer(clist, slist)
ada = outlist[0]
t =(1 - alpha) * clist[0] + alpha * ada
out = self.decoder(t)
fgt = self.encoder(out, only_last=True) # a list
c_loss = self.content_loss(fgt[0], t)#fgt[0] is just because it is a list
c_middle, s_middle = self.encoder(out, only_last = False), self.encoder(s_imgs, only_last = False)
# c_middle, s_middle = self.encoder(c_imgs, only_last = False), self.encoder(s_imgs, only_last = False)
#return two list with len = 4 both, because the para only_last=false
s_loss = self.style_loss(c_middle, s_middle)
loss = c_loss + lam * s_loss
return loss, c_loss, s_loss
def generate(self, c_imgs, s_imgs, alpha=1):
clist, slist = self.encoder(c_imgs, only_last=True), self.encoder(s_imgs, only_last=True)
#return two list with len = 1 both, because the para only_last=true
outlist = self.adain_layer(clist, slist)
t = outlist[0]
t =(1 - alpha) * clist[0] + alpha * t
out = self.decoder(t)
# print(out)
return out