Update CD-DCU-Net(Incorporate CD-module)/CD-DCU-Net.py
Browse files
CD-DCU-Net(Incorporate CD-module)/CD-DCU-Net.py
CHANGED
|
@@ -1,268 +1,268 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import torch.nn.functional as F
|
| 4 |
-
from torchsummary import summary
|
| 5 |
-
import numpy as np
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
class ConcreteDropout(nn.Module):
|
| 9 |
-
def __init__(self, weight_regularizer=1e-7, dropout_regularizer=1e-6, init_min=0.1, init_max=0.4):
|
| 10 |
-
super().__init__()
|
| 11 |
-
|
| 12 |
-
self.weight_regularizer = weight_regularizer
|
| 13 |
-
self.dropout_regularizer = dropout_regularizer
|
| 14 |
-
|
| 15 |
-
init_min = np.log(init_min) - np.log(1. - init_min)
|
| 16 |
-
init_max = np.log(init_max) - np.log(1. - init_max)
|
| 17 |
-
self.p_logit = nn.Parameter(torch.empty(1).uniform_(init_min, init_max))
|
| 18 |
-
self.regularization_loss = 0.0
|
| 19 |
-
|
| 20 |
-
def forward(self, x, layer):
|
| 21 |
-
p = torch.sigmoid(self.p_logit)
|
| 22 |
-
p = torch.clamp(p, max=0.4)
|
| 23 |
-
|
| 24 |
-
if self.training:
|
| 25 |
-
# Training mode: use Concrete Dropout.
|
| 26 |
-
out = layer(self._concrete_dropout(x, p))
|
| 27 |
-
|
| 28 |
-
# Calculate the regularization loss.
|
| 29 |
-
sum_of_square = 0
|
| 30 |
-
for param in layer.parameters():
|
| 31 |
-
sum_of_square += torch.sum(torch.pow(param, 2))
|
| 32 |
-
weights_regularizer = self.weight_regularizer * sum_of_square / (1 - p)
|
| 33 |
-
|
| 34 |
-
dropout_regularizer = p * torch.log(p)
|
| 35 |
-
dropout_regularizer += (1. - p) * torch.log(1. - p)
|
| 36 |
-
|
| 37 |
-
input_dim = x[0].numel()
|
| 38 |
-
#input_dim=x.size(1)
|
| 39 |
-
|
| 40 |
-
dropout_regularizer *= self.dropout_regularizer * input_dim
|
| 41 |
-
|
| 42 |
-
self.regularization_loss = (weights_regularizer + dropout_regularizer)
|
| 43 |
-
else:
|
| 44 |
-
# Evaluation mode: pass directly through the layer.
|
| 45 |
-
out = layer(x)
|
| 46 |
-
|
| 47 |
-
return out
|
| 48 |
-
|
| 49 |
-
def _concrete_dropout(self, x, p):
|
| 50 |
-
eps = 1e-7
|
| 51 |
-
temp = 0.
|
| 52 |
-
|
| 53 |
-
unif_noise = torch.rand_like(x, device=x.device)
|
| 54 |
-
drop_prob = (torch.log(p + eps)
|
| 55 |
-
- torch.log(1 - p + eps)
|
| 56 |
-
+ torch.log(unif_noise + eps)
|
| 57 |
-
- torch.log(1 - unif_noise + eps))
|
| 58 |
-
|
| 59 |
-
drop_prob = torch.sigmoid(drop_prob / temp)
|
| 60 |
-
random_tensor = 1 - drop_prob
|
| 61 |
-
retain_prob = 1 - p
|
| 62 |
-
|
| 63 |
-
x = torch.mul(x, random_tensor)
|
| 64 |
-
x /= retain_prob
|
| 65 |
-
|
| 66 |
-
return x
|
| 67 |
-
|
| 68 |
-
def get_dropout_rate(self):
|
| 69 |
-
"""Return the current dropout rate."""
|
| 70 |
-
return torch.sigmoid(self.p_logit).item()
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
class DoubleConv(nn.Module):
|
| 74 |
-
def __init__(self, in_channels, out_channels, mid_channels=None):
|
| 75 |
-
super().__init__()
|
| 76 |
-
if not mid_channels:
|
| 77 |
-
mid_channels = out_channels
|
| 78 |
-
self.double_conv = nn.Sequential(
|
| 79 |
-
nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
|
| 80 |
-
nn.BatchNorm2d(mid_channels),
|
| 81 |
-
nn.ReLU(inplace=True),
|
| 82 |
-
|
| 83 |
-
nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
|
| 84 |
-
nn.BatchNorm2d(out_channels),
|
| 85 |
-
nn.ReLU(inplace=True),
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
)
|
| 89 |
-
|
| 90 |
-
def forward(self, x):
|
| 91 |
-
return self.double_conv(x)
|
| 92 |
-
# Downsample with max pooling.
|
| 93 |
-
class Down(nn.Module):
|
| 94 |
-
def __init__(self, in_channels, out_channels):
|
| 95 |
-
super().__init__()
|
| 96 |
-
self.maxpool_conv = nn.Sequential(
|
| 97 |
-
nn.MaxPool2d(2),
|
| 98 |
-
DoubleConv(in_channels, out_channels,)
|
| 99 |
-
)
|
| 100 |
-
|
| 101 |
-
def forward(self, x):
|
| 102 |
-
return self.maxpool_conv(x)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
class Up(nn.Module):
|
| 106 |
-
def __init__(self, in_channels, out_channels, bilinear=False):
|
| 107 |
-
super().__init__()
|
| 108 |
-
if bilinear:
|
| 109 |
-
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
|
| 110 |
-
self.conv = DoubleConv(in_channels + in_channels // 2, out_channels)
|
| 111 |
-
else:
|
| 112 |
-
self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
|
| 113 |
-
self.conv = DoubleConv(in_channels // 2 + out_channels, out_channels)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def forward(self, x1, x2):
|
| 117 |
-
x1 = self.up(x1)
|
| 118 |
-
|
| 119 |
-
diffY = x2.size()[2] - x1.size()[2]
|
| 120 |
-
diffX = x2.size()[3] - x1.size()[3]
|
| 121 |
-
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
|
| 122 |
-
diffY // 2, diffY - diffY // 2])
|
| 123 |
-
x = torch.cat([x2, x1], dim=1)
|
| 124 |
-
return self.conv(x)
|
| 125 |
-
|
| 126 |
-
class OutConv(nn.Module):
|
| 127 |
-
def __init__(self, in_channels, out_channels=4):
|
| 128 |
-
super(OutConv, self).__init__()
|
| 129 |
-
self.conv = nn.Sequential(
|
| 130 |
-
nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, bias=True),
|
| 131 |
-
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=True)
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
def forward(self, x):
|
| 135 |
-
return self.conv(x)
|
| 136 |
-
|
| 137 |
-
class UNet(nn.Module):
|
| 138 |
-
def __init__(self, n_channels=3, bilinear=False):
|
| 139 |
-
super(UNet, self).__init__()
|
| 140 |
-
self.n_channels = n_channels
|
| 141 |
-
self.bilinear = bilinear
|
| 142 |
-
|
| 143 |
-
# Encoder.
|
| 144 |
-
self.inc = DoubleConv(n_channels, 64)
|
| 145 |
-
self.down1 = Down(64, 128)
|
| 146 |
-
self.down2 = Down(128, 256)
|
| 147 |
-
self.down3 = Down(256, 512)
|
| 148 |
-
self.down4 = Down(512, 1024)
|
| 149 |
-
|
| 150 |
-
# Encoder Concrete Dropout layers: apply one at every level.
|
| 151 |
-
self.cd_enc1 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 152 |
-
self.cd_enc2 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 153 |
-
self.cd_enc3 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 154 |
-
self.cd_enc4 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 155 |
-
self.cd_enc5 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 156 |
-
|
| 157 |
-
# Convolution layers paired with encoder Concrete Dropout.
|
| 158 |
-
self.cd_enc_conv1 = nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False)
|
| 159 |
-
self.cd_enc_conv2 = nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False)
|
| 160 |
-
self.cd_enc_conv3 = nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False)
|
| 161 |
-
self.cd_enc_conv4 = nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False)
|
| 162 |
-
self.cd_enc_conv5 = nn.Conv2d(1024, 1024, kernel_size=3, padding=1, bias=False)
|
| 163 |
-
|
| 164 |
-
# Decoder.
|
| 165 |
-
self.up1 = Up(1024, 512, bilinear)
|
| 166 |
-
self.up2 = Up(512, 256, bilinear)
|
| 167 |
-
self.up3 = Up(256, 128, bilinear)
|
| 168 |
-
self.up4 = Up(128, 64, bilinear)
|
| 169 |
-
|
| 170 |
-
# Decoder Concrete Dropout layers.
|
| 171 |
-
self.cd_dec1 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 172 |
-
self.cd_dec2 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 173 |
-
self.cd_dec3 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 174 |
-
self.cd_dec4 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 175 |
-
|
| 176 |
-
# Convolution layers paired with decoder Concrete Dropout.
|
| 177 |
-
self.cd_dec_conv1 = nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False)
|
| 178 |
-
self.cd_dec_conv2 = nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False)
|
| 179 |
-
self.cd_dec_conv3 = nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False)
|
| 180 |
-
self.cd_dec_conv4 = nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False)
|
| 181 |
-
|
| 182 |
-
self.outc = OutConv(64, 4)
|
| 183 |
-
|
| 184 |
-
def forward(self, x):
|
| 185 |
-
# Encoder path.
|
| 186 |
-
x1 = self.inc(x)
|
| 187 |
-
x1 = self.cd_enc1(x1, self.cd_enc_conv1) # Apply Concrete Dropout at level 1.
|
| 188 |
-
|
| 189 |
-
x2 = self.down1(x1)
|
| 190 |
-
x2 = self.cd_enc2(x2, self.cd_enc_conv2) # Apply Concrete Dropout at level 2.
|
| 191 |
-
|
| 192 |
-
x3 = self.down2(x2)
|
| 193 |
-
x3 = self.cd_enc3(x3, self.cd_enc_conv3) # Apply Concrete Dropout at level 3.
|
| 194 |
-
|
| 195 |
-
x4 = self.down3(x3)
|
| 196 |
-
x4 = self.cd_enc4(x4, self.cd_enc_conv4) # Apply Concrete Dropout at level 4.
|
| 197 |
-
|
| 198 |
-
x5 = self.down4(x4)
|
| 199 |
-
|
| 200 |
-
x5 = self.cd_enc5(x5, self.cd_enc_conv5) # Apply Concrete Dropout at the bottleneck.
|
| 201 |
-
|
| 202 |
-
# Decoder path.
|
| 203 |
-
x = self.up1(x5, x4)
|
| 204 |
-
x = self.cd_dec1(x, self.cd_dec_conv1) # Apply Concrete Dropout at decoder level 1.
|
| 205 |
-
|
| 206 |
-
x = self.up2(x, x3)
|
| 207 |
-
x = self.cd_dec2(x, self.cd_dec_conv2) # Apply Concrete Dropout at decoder level 2.
|
| 208 |
-
|
| 209 |
-
x = self.up3(x, x2)
|
| 210 |
-
x = self.cd_dec3(x, self.cd_dec_conv3) # Apply Concrete Dropout at decoder level 3.
|
| 211 |
-
|
| 212 |
-
x = self.up4(x, x1)
|
| 213 |
-
x = self.cd_dec4(x, self.cd_dec_conv4) # Apply Concrete Dropout at decoder level 4.
|
| 214 |
-
|
| 215 |
-
# Predict means and variances.
|
| 216 |
-
outputs = self.outc(x)
|
| 217 |
-
M_mean = outputs[:, 0:1] # M mean.
|
| 218 |
-
M_var = 0.001 + F.softplus(outputs[:, 2:3]) # M variance; softplus keeps it positive.
|
| 219 |
-
# M_var = F.softplus(outputs[:, 2:3]) # M variance; softplus keeps it positive.
|
| 220 |
-
D_mean = outputs[:, 1:2] # D mean.
|
| 221 |
-
D_var = 0.001 + F.softplus(outputs[:, 3:4]) # D variance; softplus keeps it positive.
|
| 222 |
-
# D_var = F.softplus(outputs[:, 3:4])
|
| 223 |
-
|
| 224 |
-
return {'M_mean': M_mean, 'M_var': M_var, 'D_mean': D_mean, 'D_var': D_var}
|
| 225 |
-
|
| 226 |
-
def get_regularization_loss(self):
|
| 227 |
-
"""Return the regularization loss from all Concrete Dropout layers."""
|
| 228 |
-
return (self.cd_enc1.regularization_loss +
|
| 229 |
-
self.cd_enc2.regularization_loss +
|
| 230 |
-
self.cd_enc3.regularization_loss +
|
| 231 |
-
self.cd_enc4.regularization_loss +
|
| 232 |
-
self.cd_enc5.regularization_loss +
|
| 233 |
-
self.cd_dec1.regularization_loss +
|
| 234 |
-
self.cd_dec2.regularization_loss +
|
| 235 |
-
self.cd_dec3.regularization_loss +
|
| 236 |
-
self.cd_dec4.regularization_loss)
|
| 237 |
-
|
| 238 |
-
def get_dropout_rates(self):
|
| 239 |
-
"""Return the dropout rate for every layer."""
|
| 240 |
-
return {
|
| 241 |
-
'enc1': self.cd_enc1.get_dropout_rate(),
|
| 242 |
-
'enc2': self.cd_enc2.get_dropout_rate(),
|
| 243 |
-
'enc3': self.cd_enc3.get_dropout_rate(),
|
| 244 |
-
'enc4': self.cd_enc4.get_dropout_rate(),
|
| 245 |
-
'enc5': self.cd_enc5.get_dropout_rate(),
|
| 246 |
-
'dec1': self.cd_dec1.get_dropout_rate(),
|
| 247 |
-
'dec2': self.cd_dec2.get_dropout_rate(),
|
| 248 |
-
'dec3': self.cd_dec3.get_dropout_rate(),
|
| 249 |
-
'dec4': self.cd_dec4.get_dropout_rate()
|
| 250 |
-
}
|
| 251 |
-
|
| 252 |
-
if __name__ == "__main__":
|
| 253 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 254 |
-
model = UNet(3, bilinear=False).to(device)
|
| 255 |
-
print(summary(model, (3, 432, 352)))
|
| 256 |
-
|
| 257 |
-
# Example input.
|
| 258 |
-
x = torch.randn(1, 3, 800, 800).to(device)
|
| 259 |
-
output = model(x)
|
| 260 |
print("Output mean M:", output['M_mean'].shape)
|
| 261 |
print("Output variance M:", output['M_var'].shape)
|
| 262 |
print("Output mean D:", output['D_mean'].shape)
|
| 263 |
print("Output variance D:", output['D_var'].shape)
|
| 264 |
-
|
| 265 |
-
# Print the dropout rate for every layer.
|
| 266 |
-
dropout_rates = model.get_dropout_rates()
|
| 267 |
-
for layer, rate in dropout_rates.items():
|
| 268 |
-
print(f"{layer} dropout rate: {rate:.4f}")
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torchsummary import summary
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ConcreteDropout(nn.Module):
|
| 9 |
+
def __init__(self, weight_regularizer=1e-7, dropout_regularizer=1e-6, init_min=0.1, init_max=0.4):
|
| 10 |
+
super().__init__()
|
| 11 |
+
|
| 12 |
+
self.weight_regularizer = weight_regularizer
|
| 13 |
+
self.dropout_regularizer = dropout_regularizer
|
| 14 |
+
|
| 15 |
+
init_min = np.log(init_min) - np.log(1. - init_min)
|
| 16 |
+
init_max = np.log(init_max) - np.log(1. - init_max)
|
| 17 |
+
self.p_logit = nn.Parameter(torch.empty(1).uniform_(init_min, init_max))
|
| 18 |
+
self.regularization_loss = 0.0
|
| 19 |
+
|
| 20 |
+
def forward(self, x, layer):
|
| 21 |
+
p = torch.sigmoid(self.p_logit)
|
| 22 |
+
p = torch.clamp(p, max=0.4)
|
| 23 |
+
|
| 24 |
+
if self.training:
|
| 25 |
+
# Training mode: use Concrete Dropout.
|
| 26 |
+
out = layer(self._concrete_dropout(x, p))
|
| 27 |
+
|
| 28 |
+
# Calculate the regularization loss.
|
| 29 |
+
sum_of_square = 0
|
| 30 |
+
for param in layer.parameters():
|
| 31 |
+
sum_of_square += torch.sum(torch.pow(param, 2))
|
| 32 |
+
weights_regularizer = self.weight_regularizer * sum_of_square / (1 - p)
|
| 33 |
+
|
| 34 |
+
dropout_regularizer = p * torch.log(p)
|
| 35 |
+
dropout_regularizer += (1. - p) * torch.log(1. - p)
|
| 36 |
+
|
| 37 |
+
input_dim = x[0].numel()
|
| 38 |
+
#input_dim=x.size(1)
|
| 39 |
+
|
| 40 |
+
dropout_regularizer *= self.dropout_regularizer * input_dim
|
| 41 |
+
|
| 42 |
+
self.regularization_loss = (weights_regularizer + dropout_regularizer)
|
| 43 |
+
else:
|
| 44 |
+
# Evaluation mode: pass directly through the layer.
|
| 45 |
+
out = layer(x)
|
| 46 |
+
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
def _concrete_dropout(self, x, p):
|
| 50 |
+
eps = 1e-7
|
| 51 |
+
temp = 0.5
|
| 52 |
+
|
| 53 |
+
unif_noise = torch.rand_like(x, device=x.device)
|
| 54 |
+
drop_prob = (torch.log(p + eps)
|
| 55 |
+
- torch.log(1 - p + eps)
|
| 56 |
+
+ torch.log(unif_noise + eps)
|
| 57 |
+
- torch.log(1 - unif_noise + eps))
|
| 58 |
+
|
| 59 |
+
drop_prob = torch.sigmoid(drop_prob / temp)
|
| 60 |
+
random_tensor = 1 - drop_prob
|
| 61 |
+
retain_prob = 1 - p
|
| 62 |
+
|
| 63 |
+
x = torch.mul(x, random_tensor)
|
| 64 |
+
x /= retain_prob
|
| 65 |
+
|
| 66 |
+
return x
|
| 67 |
+
|
| 68 |
+
def get_dropout_rate(self):
|
| 69 |
+
"""Return the current dropout rate."""
|
| 70 |
+
return torch.sigmoid(self.p_logit).item()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DoubleConv(nn.Module):
|
| 74 |
+
def __init__(self, in_channels, out_channels, mid_channels=None):
|
| 75 |
+
super().__init__()
|
| 76 |
+
if not mid_channels:
|
| 77 |
+
mid_channels = out_channels
|
| 78 |
+
self.double_conv = nn.Sequential(
|
| 79 |
+
nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
|
| 80 |
+
nn.BatchNorm2d(mid_channels),
|
| 81 |
+
nn.ReLU(inplace=True),
|
| 82 |
+
|
| 83 |
+
nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
|
| 84 |
+
nn.BatchNorm2d(out_channels),
|
| 85 |
+
nn.ReLU(inplace=True),
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
return self.double_conv(x)
|
| 92 |
+
# Downsample with max pooling.
|
| 93 |
+
class Down(nn.Module):
|
| 94 |
+
def __init__(self, in_channels, out_channels):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.maxpool_conv = nn.Sequential(
|
| 97 |
+
nn.MaxPool2d(2),
|
| 98 |
+
DoubleConv(in_channels, out_channels,)
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def forward(self, x):
|
| 102 |
+
return self.maxpool_conv(x)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class Up(nn.Module):
|
| 106 |
+
def __init__(self, in_channels, out_channels, bilinear=False):
|
| 107 |
+
super().__init__()
|
| 108 |
+
if bilinear:
|
| 109 |
+
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
|
| 110 |
+
self.conv = DoubleConv(in_channels + in_channels // 2, out_channels)
|
| 111 |
+
else:
|
| 112 |
+
self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
|
| 113 |
+
self.conv = DoubleConv(in_channels // 2 + out_channels, out_channels)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def forward(self, x1, x2):
|
| 117 |
+
x1 = self.up(x1)
|
| 118 |
+
|
| 119 |
+
diffY = x2.size()[2] - x1.size()[2]
|
| 120 |
+
diffX = x2.size()[3] - x1.size()[3]
|
| 121 |
+
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
|
| 122 |
+
diffY // 2, diffY - diffY // 2])
|
| 123 |
+
x = torch.cat([x2, x1], dim=1)
|
| 124 |
+
return self.conv(x)
|
| 125 |
+
|
| 126 |
+
class OutConv(nn.Module):
|
| 127 |
+
def __init__(self, in_channels, out_channels=4):
|
| 128 |
+
super(OutConv, self).__init__()
|
| 129 |
+
self.conv = nn.Sequential(
|
| 130 |
+
nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, bias=True),
|
| 131 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=True)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
return self.conv(x)
|
| 136 |
+
|
| 137 |
+
class UNet(nn.Module):
|
| 138 |
+
def __init__(self, n_channels=3, bilinear=False):
|
| 139 |
+
super(UNet, self).__init__()
|
| 140 |
+
self.n_channels = n_channels
|
| 141 |
+
self.bilinear = bilinear
|
| 142 |
+
|
| 143 |
+
# Encoder.
|
| 144 |
+
self.inc = DoubleConv(n_channels, 64)
|
| 145 |
+
self.down1 = Down(64, 128)
|
| 146 |
+
self.down2 = Down(128, 256)
|
| 147 |
+
self.down3 = Down(256, 512)
|
| 148 |
+
self.down4 = Down(512, 1024)
|
| 149 |
+
|
| 150 |
+
# Encoder Concrete Dropout layers: apply one at every level.
|
| 151 |
+
self.cd_enc1 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 152 |
+
self.cd_enc2 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 153 |
+
self.cd_enc3 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 154 |
+
self.cd_enc4 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 155 |
+
self.cd_enc5 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 156 |
+
|
| 157 |
+
# Convolution layers paired with encoder Concrete Dropout.
|
| 158 |
+
self.cd_enc_conv1 = nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False)
|
| 159 |
+
self.cd_enc_conv2 = nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False)
|
| 160 |
+
self.cd_enc_conv3 = nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False)
|
| 161 |
+
self.cd_enc_conv4 = nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False)
|
| 162 |
+
self.cd_enc_conv5 = nn.Conv2d(1024, 1024, kernel_size=3, padding=1, bias=False)
|
| 163 |
+
|
| 164 |
+
# Decoder.
|
| 165 |
+
self.up1 = Up(1024, 512, bilinear)
|
| 166 |
+
self.up2 = Up(512, 256, bilinear)
|
| 167 |
+
self.up3 = Up(256, 128, bilinear)
|
| 168 |
+
self.up4 = Up(128, 64, bilinear)
|
| 169 |
+
|
| 170 |
+
# Decoder Concrete Dropout layers.
|
| 171 |
+
self.cd_dec1 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 172 |
+
self.cd_dec2 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 173 |
+
self.cd_dec3 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 174 |
+
self.cd_dec4 = ConcreteDropout(weight_regularizer=1e-6, dropout_regularizer=1e-5)
|
| 175 |
+
|
| 176 |
+
# Convolution layers paired with decoder Concrete Dropout.
|
| 177 |
+
self.cd_dec_conv1 = nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False)
|
| 178 |
+
self.cd_dec_conv2 = nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False)
|
| 179 |
+
self.cd_dec_conv3 = nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False)
|
| 180 |
+
self.cd_dec_conv4 = nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False)
|
| 181 |
+
|
| 182 |
+
self.outc = OutConv(64, 4)
|
| 183 |
+
|
| 184 |
+
def forward(self, x):
|
| 185 |
+
# Encoder path.
|
| 186 |
+
x1 = self.inc(x)
|
| 187 |
+
x1 = self.cd_enc1(x1, self.cd_enc_conv1) # Apply Concrete Dropout at level 1.
|
| 188 |
+
|
| 189 |
+
x2 = self.down1(x1)
|
| 190 |
+
x2 = self.cd_enc2(x2, self.cd_enc_conv2) # Apply Concrete Dropout at level 2.
|
| 191 |
+
|
| 192 |
+
x3 = self.down2(x2)
|
| 193 |
+
x3 = self.cd_enc3(x3, self.cd_enc_conv3) # Apply Concrete Dropout at level 3.
|
| 194 |
+
|
| 195 |
+
x4 = self.down3(x3)
|
| 196 |
+
x4 = self.cd_enc4(x4, self.cd_enc_conv4) # Apply Concrete Dropout at level 4.
|
| 197 |
+
|
| 198 |
+
x5 = self.down4(x4)
|
| 199 |
+
|
| 200 |
+
x5 = self.cd_enc5(x5, self.cd_enc_conv5) # Apply Concrete Dropout at the bottleneck.
|
| 201 |
+
|
| 202 |
+
# Decoder path.
|
| 203 |
+
x = self.up1(x5, x4)
|
| 204 |
+
x = self.cd_dec1(x, self.cd_dec_conv1) # Apply Concrete Dropout at decoder level 1.
|
| 205 |
+
|
| 206 |
+
x = self.up2(x, x3)
|
| 207 |
+
x = self.cd_dec2(x, self.cd_dec_conv2) # Apply Concrete Dropout at decoder level 2.
|
| 208 |
+
|
| 209 |
+
x = self.up3(x, x2)
|
| 210 |
+
x = self.cd_dec3(x, self.cd_dec_conv3) # Apply Concrete Dropout at decoder level 3.
|
| 211 |
+
|
| 212 |
+
x = self.up4(x, x1)
|
| 213 |
+
x = self.cd_dec4(x, self.cd_dec_conv4) # Apply Concrete Dropout at decoder level 4.
|
| 214 |
+
|
| 215 |
+
# Predict means and variances.
|
| 216 |
+
outputs = self.outc(x)
|
| 217 |
+
M_mean = outputs[:, 0:1] # M mean.
|
| 218 |
+
M_var = 0.001 + F.softplus(outputs[:, 2:3]) # M variance; softplus keeps it positive.
|
| 219 |
+
# M_var = F.softplus(outputs[:, 2:3]) # M variance; softplus keeps it positive.
|
| 220 |
+
D_mean = outputs[:, 1:2] # D mean.
|
| 221 |
+
D_var = 0.001 + F.softplus(outputs[:, 3:4]) # D variance; softplus keeps it positive.
|
| 222 |
+
# D_var = F.softplus(outputs[:, 3:4])
|
| 223 |
+
|
| 224 |
+
return {'M_mean': M_mean, 'M_var': M_var, 'D_mean': D_mean, 'D_var': D_var}
|
| 225 |
+
|
| 226 |
+
def get_regularization_loss(self):
|
| 227 |
+
"""Return the regularization loss from all Concrete Dropout layers."""
|
| 228 |
+
return (self.cd_enc1.regularization_loss +
|
| 229 |
+
self.cd_enc2.regularization_loss +
|
| 230 |
+
self.cd_enc3.regularization_loss +
|
| 231 |
+
self.cd_enc4.regularization_loss +
|
| 232 |
+
self.cd_enc5.regularization_loss +
|
| 233 |
+
self.cd_dec1.regularization_loss +
|
| 234 |
+
self.cd_dec2.regularization_loss +
|
| 235 |
+
self.cd_dec3.regularization_loss +
|
| 236 |
+
self.cd_dec4.regularization_loss)
|
| 237 |
+
|
| 238 |
+
def get_dropout_rates(self):
|
| 239 |
+
"""Return the dropout rate for every layer."""
|
| 240 |
+
return {
|
| 241 |
+
'enc1': self.cd_enc1.get_dropout_rate(),
|
| 242 |
+
'enc2': self.cd_enc2.get_dropout_rate(),
|
| 243 |
+
'enc3': self.cd_enc3.get_dropout_rate(),
|
| 244 |
+
'enc4': self.cd_enc4.get_dropout_rate(),
|
| 245 |
+
'enc5': self.cd_enc5.get_dropout_rate(),
|
| 246 |
+
'dec1': self.cd_dec1.get_dropout_rate(),
|
| 247 |
+
'dec2': self.cd_dec2.get_dropout_rate(),
|
| 248 |
+
'dec3': self.cd_dec3.get_dropout_rate(),
|
| 249 |
+
'dec4': self.cd_dec4.get_dropout_rate()
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 254 |
+
model = UNet(3, bilinear=False).to(device)
|
| 255 |
+
print(summary(model, (3, 432, 352)))
|
| 256 |
+
|
| 257 |
+
# Example input.
|
| 258 |
+
x = torch.randn(1, 3, 800, 800).to(device)
|
| 259 |
+
output = model(x)
|
| 260 |
print("Output mean M:", output['M_mean'].shape)
|
| 261 |
print("Output variance M:", output['M_var'].shape)
|
| 262 |
print("Output mean D:", output['D_mean'].shape)
|
| 263 |
print("Output variance D:", output['D_var'].shape)
|
| 264 |
+
|
| 265 |
+
# Print the dropout rate for every layer.
|
| 266 |
+
dropout_rates = model.get_dropout_rates()
|
| 267 |
+
for layer, rate in dropout_rates.items():
|
| 268 |
+
print(f"{layer} dropout rate: {rate:.4f}")
|