model.py 2.03 KB
Newer Older
BobYeah's avatar
sync    
BobYeah committed
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
import torch
import torch.nn as nn


class Net(torch.nn.Module):
    def __init__(self, num_channels, upscale_factor, d=64, s=12, m=4):
        super(Net, self).__init__()

        self.first_part = nn.Sequential(
            nn.Conv2d(in_channels=num_channels, out_channels=d,
                      kernel_size=5, stride=1, padding=2),
            nn.PReLU()
        )

        self.layers = []
        self.layers += [
            nn.Conv2d(in_channels=d, out_channels=s,
                      kernel_size=1, stride=1, padding=0),
            nn.PReLU()
        ]
        for _ in range(m):
            self.layers += [
                nn.Conv2d(in_channels=s, out_channels=s,
                          kernel_size=3, stride=1, padding=1),
                nn.PReLU()
            ]
        self.layers += [
            nn.Conv2d(in_channels=s, out_channels=d,
                      kernel_size=1, stride=1, padding=0),
            nn.PReLU()
        ]

        self.mid_part = nn.Sequential(*self.layers)

        # Deconvolution
        if upscale_factor % 2:
            self.last_part = nn.ConvTranspose2d(
                in_channels=d, out_channels=num_channels, kernel_size=9,
                stride=upscale_factor, padding=5 - (upscale_factor + 1) // 2)
        else:
            self.last_part = nn.ConvTranspose2d(
                in_channels=d, out_channels=num_channels, kernel_size=9,
                stride=upscale_factor, padding=5 - upscale_factor // 2,
                output_padding=1)

    def forward(self, x):
        out = self.first_part(x)
        out = self.mid_part(out)
        out = self.last_part(out)
        return out

    def weight_init(self, mean=0.0, std=0.02):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                m.weight.data.normal_(mean, std)
                if m.bias is not None:
                    m.bias.data.zero_()
            if isinstance(m, nn.ConvTranspose2d):
                m.weight.data.normal_(0.0, 0.0001)
                if m.bias is not None:
                    m.bias.data.zero_()