Spaces:
Sleeping
Sleeping
File size: 8,954 Bytes
aefacda |
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
"""
paper: https://arxiv.org/abs/2004.08790
ref: https://github.com/ZJUGiveLab/UNet-Version/blob/master/models/UNet_3Plus.py
"""
import torch
from torch import nn
from torch.functional import F
class UNetConv(nn.Module):
def __init__(
self,
in_size,
out_size,
is_batchnorm=True,
num_layers=2,
kernel_size=3,
stride=1,
padding=1,
):
super().__init__()
self.num_layers = num_layers
for i in range(num_layers):
seq = [nn.Conv1d(in_size, out_size, kernel_size, stride, padding)]
if is_batchnorm:
seq.append(nn.BatchNorm1d(out_size))
seq.append(nn.ReLU())
conv = nn.Sequential(*seq)
setattr(self, "conv%d" % i, conv)
in_size = out_size
def forward(self, inputs):
x = inputs
for i in range(self.num_layers):
conv = getattr(self, "conv%d" % i)
x = conv(x)
return x
class UNet3PlusDeepSup(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
inplanes = int(config.inplanes)
kernel_size = int(config.kernel_size)
padding = (kernel_size - 1) // 2
num_encoder_layers = int(config.num_encoder_layers)
encoder_batchnorm = bool(config.encoder_batchnorm)
self.num_depths = int(config.num_depths)
self.interpolate_mode = str(config.interpolate_mode)
dropout = float(config.dropout)
self.use_cgm = bool(config.use_cgm)
# sum_of_sup == True: ๋ชจ๋ sup ์ elementwise sum ํ์ฌ ํ๋์ dense map ์ ๋ง๋ค์ด label ๊ณผ loss ๋ฅผ ๊ตฌํจ
# sum_of_sup == False: ๊ฐ sup ๊ณผ label์ loss ๋ฅผ ๊ฐ๊ฐ ๊ตฌํ์ฌ ํ๋์ loss ์ ์ ์ฅ
self.sum_of_sup = bool(config.sum_of_sup)
# TrialSetup._init_network_params ์์ ์ค์ ๋จ
self.output_size: int = config.output_size
# Encoder
self.encoders = torch.nn.ModuleList()
for i in range(self.num_depths):
"""(MaxPool - UNetConv) ๋ฅผ ์ํํ๋ ๊ฒ์ด ํ๋์ depth ์ด๊ณ , ์์ธ์ ์ผ๋ก ์ฒซ๋ฒ์งธ depth ์ encode ๊ฒฐ๊ณผ๋ (UNetConv)๋ง ์ํํ ๊ฒ"""
_encoders = []
if i != 0:
_encoders.append(nn.MaxPool1d(2))
_encoders.append(
UNetConv(
1 if i == 0 else (inplanes * (2 ** (i - 1))),
inplanes * (2**i),
is_batchnorm=encoder_batchnorm,
num_layers=num_encoder_layers,
kernel_size=kernel_size,
stride=1,
padding=padding,
)
)
self.encoders.append(nn.Sequential(*_encoders))
# CGM: Classification-Guided Module
if self.use_cgm:
self.cls = nn.Sequential(
nn.Dropout(dropout),
nn.Conv1d(
inplanes * (2 ** (self.num_depths - 1)), 2 * self.output_size, 1
),
nn.AdaptiveMaxPool1d(1),
nn.Sigmoid(),
)
# Decoder
self.up_channels = inplanes * self.num_depths
self.decoders = torch.nn.ModuleList()
for i in reversed(range(self.num_depths - 1)):
"""
๊ฐ decoder ๋ ๊ฐ encode ๊ฒฐ๊ณผ๋ฅผ MaxPool ํ๊ฑฐ๋ ๊ทธ๋๋ก(Conv,BatchNorm,Relu ๋ง) ์ฌ์ฉํ๊ฑฐ๋ Upsample ๋ ๊ฒฐ๊ณผ๋ฅผ ์ํํ๊ณ concat ํ์ฌ (Conv,BatchNorm,Relu)๋ฅผ ์ํํ ์ ์๋๋ก ๊ตฌ์ฑ
๋ค๋ง, Upsample ์ encode ๊ฒฐ๊ณผ์ size ๋ฅผ ๋ง์ถ๊ธฐ ๊ฐํธํ๋๋ก forward ๋จ๊ณ์์ torch.functional.interpolate() ๋ก ์ํ
"""
# ๊ฐ ๋จ๊ณ๋ณ decoder ๋ ํญ์ num_depths ๋งํผ ๊ตฌ์ฑ๋๊ณ ๋ด๋ถ์ ์ผ๋ก MaxPool/๊ทธ๋๋ก/Upsample ์ํํ ์ง๊ฐ ๋ฌ๋ผ์ง
_decoders = torch.nn.ModuleList()
for j in range(self.num_depths):
_each_decoders = []
if j < i:
_each_decoders.append(nn.MaxPool1d(2 ** (i - j), ceil_mode=True))
if i < j < self.num_depths - 1:
_each_decoders.append(
nn.Conv1d(
inplanes * self.num_depths,
inplanes,
kernel_size,
padding=padding,
)
)
else:
_each_decoders.append(
nn.Conv1d(
inplanes * (2**j), inplanes, kernel_size, padding=padding
)
)
_each_decoders.append(nn.BatchNorm1d(inplanes))
_each_decoders.append(nn.ReLU())
_decoders.append(nn.Sequential(*_each_decoders))
_decoders.append(
nn.Sequential(
nn.Conv1d(
self.up_channels, self.up_channels, kernel_size, padding=padding
),
nn.BatchNorm1d(self.up_channels),
nn.ReLU(),
)
)
self.decoders.append(_decoders)
# ์ conv ๋ค์ in channel ์ด up_channels(inplanes*num_depths(์๋ณธ์์๋ 320)), ๋ง์ง๋ง conv ๋ ๋ง์ง๋ง encoder ๊ฒฐ๊ณผ์ output_channel ๊ณผ ๋ง์ถค
self.sup_conv = torch.nn.ModuleList()
for i in range(self.num_depths - 1):
self.sup_conv.append(
nn.Sequential(
nn.Conv1d(
self.up_channels, self.output_size, kernel_size, padding=padding
),
nn.BatchNorm1d(self.output_size),
nn.ReLU(),
)
)
self.sup_conv.append(
nn.Sequential(
nn.Conv1d(
inplanes * (2 ** (self.num_depths - 1)),
self.output_size,
kernel_size,
padding=padding,
),
nn.BatchNorm1d(self.output_size),
nn.ReLU(),
)
)
def forward(self, input: torch.Tensor, y=None):
# Encoder
output = input
enc_features = [] # X1Ee, X2Ee, .. , X5Ee
dec_features = [] # X5Ee, X4De, .. , X1De
for encoder in self.encoders:
output = encoder(output)
enc_features.append(output)
dec_features.append(output)
# CGM
cls_branch_max = None
if self.use_cgm:
# (B, 2*3(output_size), 1)
cls_branch: torch.Tensor = self.cls(enc_features[-1])
# (B, 3(output_size))
cls_branch_max = cls_branch.view(
input.shape[0], self.output_size, 2
).argmax(2)
# Decoder
for i in reversed(range(self.num_depths - 1)):
_each_dec_feature = []
for j in range(self.num_depths):
if j <= i:
_each_enc = enc_features[j]
else:
_each_enc = F.interpolate(
dec_features[self.num_depths - j - 1],
enc_features[i].shape[2],
mode=self.interpolate_mode,
)
_each_dec_feature.append(
self.decoders[self.num_depths - i - 2][j](_each_enc)
)
dec_features.append(
self.decoders[self.num_depths - i - 2][-1](
torch.cat(_each_dec_feature, dim=1)
)
)
sup = []
for i, (dec_feature, sup_conv) in enumerate(
zip(dec_features, reversed(self.sup_conv))
):
if i < self.num_depths - 1:
sup.append(
F.interpolate(
sup_conv(dec_feature),
input.shape[2],
mode=self.interpolate_mode,
)
)
else:
sup.append(sup_conv(dec_feature))
if self.use_cgm:
if self.sum_of_sup:
return torch.sigmoid(
sum(
[
torch.einsum("ijk,ij->ijk", [_sup, cls_branch_max])
for _sup in reversed(sup)
]
)
)
else:
return [
torch.sigmoid(
torch.einsum("ijk,ij->ijk", [_sup, cls_branch_max])
for _sup in reversed(sup)
)
]
else:
if self.sum_of_sup:
return torch.sigmoid(sum(sup))
else:
return [torch.sigmoid(_sup) for _sup in reversed(sup)]
|