-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
58 lines (42 loc) · 1.52 KB
/
Copy pathmodel.py
File metadata and controls
58 lines (42 loc) · 1.52 KB
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
import torch
import torch.nn as nn
from torchvision.models import resnet18 , ResNet18_Weights
class ColorizationNet(nn.Module):
def __init__(self):
super().__init__()
# Convert grayscale (1 channel) to RGB (3 channels)
self.gray_to_rgb = nn.Conv2d(
in_channels=1,
out_channels=3,
kernel_size=3,
padding=1
)
# Pretrained ResNet18 Encoder
backbone = resnet18(weights=ResNet18_Weights.DEFAULT)
self.encoder = nn.Sequential(*list(backbone.children())[:-2])
# Freeze encoder weights
for param in self.encoder.parameters():
param.requires_grad = False
# Decoder
self.decoder = nn.Sequential(
nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(64, 32, kernel_size=2, stride=2),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(32, 2, kernel_size=2, stride=2),
nn.Tanh()
)
def forward(self,x):
x = self.gray_to_rgb(x)
with torch.no_grad():
x = self.encoder(x)
x= self.decoder(x)
return x