forked from rrmina/fast-neural-style-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
101 lines (89 loc) · 2.6 KB
/
models.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
import torch
import torch.nn as nn
from torchsummary import summary
import torchvision.models as models
class VGGNet(nn.Module):
def __init__(self):
super(VGGNet, self).__init__()
self.select = ['3', '8', '17', '22', '26', '35']
self.vgg = models.vgg19(pretrained=True).features
for param in self.vgg.parameters():
param.requires_grad = False
def forward(self, x):
features = {}
for name, layer in self.vgg._modules.items():
x = layer(x)
if name in self.select:
features[name] = x
return features
class TransformerNet(nn.Module):
def __init__(self):
super(TransformerNet, self).__init__()
self.ConvBlock = nn.Sequential(
Conv(3, 32, kernel=9, stride=1),
nn.ReLU(),
Conv(32, 64, kernel=3, stride=2),
nn.ReLU(),
Conv(64, 128, kernel=3, stride=2),
nn.ReLU()
)
self.ResBlock = nn.Sequential(
Res(ch=128, kernel=3),
Res(ch=128, kernel=3),
Res(ch=128, kernel=3),
Res(ch=128, kernel=3),
Res(ch=128, kernel=3)
)
self.DeconvBlock = nn.Sequential(
Deconv(128, 64, kernel=3, stride=2, padding=1),
nn.ReLU(),
Deconv(64, 32, kernel=3, stride=2, padding=1),
nn.ReLU(),
Conv(32, 3, kernel=9, stride=1, norm="None")
)
def forward(self, x):
x = self.ConvBlock(x)
x = self.ResBlock(x)
out = self.DeconvBlock(x)
return out
class Conv(nn.Module):
def __init__(self, in_channel, out_channel, kernel, stride, norm="batch"):
super(Conv, self).__init__()
padding = kernel // 2
self.pad1 = nn.ReflectionPad2d(padding)
self.conv2 = nn.Conv2d(in_channel, out_channel, kernel, stride)
self.norm3 = nn.InstanceNorm2d(out_channel, affine=True)
self.norm = norm
def forward(self, x):
x = self.pad1(x)
x = self.conv2(x)
if self.norm is "batch":
out = self.norm3(x)
else:
out = x
return out
class Res(nn.Module):
def __init__(self, ch, kernel):
super(Res, self).__init__()
self.conv1 = Conv(ch, ch, kernel, stride=1)
self.conv2 = Conv(ch, ch, kernel, stride=1)
self.relu = nn.ReLU()
def forward(self, x):
tmp = x
x = self.relu(self.conv1(x))
x = self.conv2(x)
out = x + tmp
return out
class Deconv(nn.Module):
def __init__(self, in_channel, out_channel, kernel, stride, padding):
super(Deconv, self).__init__()
self.convT1 = nn.ConvTranspose2d(in_channel, out_channel, kernel, stride, kernel//2, padding)
self.norm2 = nn.InstanceNorm2d(out_channel, affine=True)
def forward(self, x):
x = self.convT1(x)
out = self.norm2(x)
return out
if __name__=="__main__":
model = TransformerNet()
print(model)
summary(model, (3, 256, 256))