Spaces:
Runtime error
Runtime error
File size: 13,203 Bytes
6bd8735 |
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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
import torch
import torch.nn as nn
import numpy as np
from torchvision import transforms
import torch.nn.functional as F
from efficientnet_pytorch import EfficientNet
from efficientnet_pytorch.utils import (
round_filters,
round_repeats,
drop_connect,
get_same_padding_conv2d,
get_model_params,
efficientnet_params,
load_pretrained_weights,
Swish,
MemoryEfficientSwish,
)
from efficientnet_pytorch.model import MBConvBlock
from torchvision.models import resnet
from pytorchcv.model_provider import get_model
class Head(nn.Module):
def __init__(self, in_f, out_f):
super(Head, self).__init__()
self.f = nn.Flatten()
self.l = nn.Linear(in_f, 512)
self.d = nn.Dropout(0.5)
self.o = nn.Linear(512, out_f)
self.b1 = nn.BatchNorm1d(in_f)
self.b2 = nn.BatchNorm1d(512)
self.r = nn.ReLU()
def forward(self, x):
x = self.f(x)
x = self.b1(x)
x = self.d(x)
x = self.l(x)
x = self.r(x)
x = self.b2(x)
x = self.d(x)
out = self.o(x)
return out
class FCN(nn.Module):
def __init__(self, base, in_f, out_f):
super(FCN, self).__init__()
self.base = base
self.h1 = Head(in_f, out_f)
def forward(self, x):
x = self.base(x)
return self.h1(x)
class BaseFCN(nn.Module):
def __init__(self, n_classes: int):
super(BaseFCN, self).__init__()
self.f = nn.Flatten()
self.l = nn.Linear(625, 256)
self.d = nn.Dropout(0.5)
self.o = nn.Linear(256, n_classes)
def forward(self, x):
x = self.f(x)
x = self.l(x)
x = self.d(x)
out = self.o(x)
return out
def get_trainable_parameters_cooccur(self):
return self.parameters()
class BaseFCNHigh(nn.Module):
def __init__(self, n_classes: int):
super(BaseFCNHigh, self).__init__()
self.f = nn.Flatten()
self.l = nn.Linear(625, 512)
self.d = nn.Dropout(0.5)
self.o = nn.Linear(512, n_classes)
def forward(self, x):
x = self.f(x)
x = self.l(x)
x = self.d(x)
out = self.o(x)
return out
def get_trainable_parameters_cooccur(self):
return self.parameters()
class BaseFCN4(nn.Module):
def __init__(self, n_classes: int):
super(BaseFCN4, self).__init__()
self.f = nn.Flatten()
self.l1 = nn.Linear(625, 512)
self.l2 = nn.Linear(512, 384)
self.l3 = nn.Linear(384, 256)
self.d = nn.Dropout(0.5)
self.o = nn.Linear(256, n_classes)
def forward(self, x):
x = self.f(x)
x = self.l1(x)
x = self.d(x)
x = self.l2(x)
x = self.d(x)
x = self.l3(x)
x = self.d(x)
out = self.o(x)
return out
def get_trainable_parameters_cooccur(self):
return self.parameters()
class BaseFCNBnR(nn.Module):
def __init__(self, n_classes: int):
super(BaseFCNBnR, self).__init__()
self.f = nn.Flatten()
self.b1 = nn.BatchNorm1d(625)
self.b2 = nn.BatchNorm1d(256)
self.l = nn.Linear(625, 256)
self.d = nn.Dropout(0.5)
self.o = nn.Linear(256, n_classes)
self.r = nn.ReLU()
def forward(self, x):
x = self.f(x)
x = self.b1(x)
x = self.d(x)
x = self.l(x)
x = self.r(x)
x = self.b2(x)
x = self.d(x)
out = self.o(x)
return out
def get_trainable_parameters_cooccur(self):
return self.parameters()
def forward_resnet_conv(net, x, upto: int = 4):
"""
Forward ResNet only in its convolutional part
:param net:
:param x:
:param upto:
:return:
"""
x = net.conv1(x) # N / 2
x = net.bn1(x)
x = net.relu(x)
x = net.maxpool(x) # N / 4
if upto >= 1:
x = net.layer1(x) # N / 4
if upto >= 2:
x = net.layer2(x) # N / 8
if upto >= 3:
x = net.layer3(x) # N / 16
if upto >= 4:
x = net.layer4(x) # N / 32
return x
class FeatureExtractor(nn.Module):
"""
Abstract class to be extended when supporting features extraction.
It also provides standard normalized and parameters
"""
def features(self, x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
def get_trainable_parameters(self):
return self.parameters()
@staticmethod
def get_normalizer():
return transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
class FeatureExtractorGray(nn.Module):
"""
Abstract class to be extended when supporting features extraction.
It also provides standard normalized and parameters
"""
def features(self, x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
def get_trainable_parameters(self):
return self.parameters()
@staticmethod
def get_normalizer():
return transforms.Normalize(mean=[0.479], std=[0.226])
class EfficientNetGen(FeatureExtractor):
def __init__(self, model: str, n_classes: int, pretrained: bool):
super(EfficientNetGen, self).__init__()
if pretrained:
self.efficientnet = EfficientNet.from_pretrained(model)
else:
self.efficientnet = EfficientNet.from_name(model)
self.classifier = nn.Linear(self.efficientnet._conv_head.out_channels, n_classes)
del self.efficientnet._fc
def features(self, x: torch.Tensor) -> torch.Tensor:
x = self.efficientnet.extract_features(x)
x = self.efficientnet._avg_pooling(x)
x = x.flatten(start_dim=1)
return x
def forward(self, x):
x = self.features(x)
x = self.efficientnet._dropout(x)
x = self.classifier(x)
# x = F.softmax(x, dim=-1)
return x
class EfficientNetB0(EfficientNetGen):
def __init__(self, n_classes: int, pretrained: bool):
super(EfficientNetB0, self).__init__(model='efficientnet-b0', n_classes=n_classes, pretrained=pretrained)
class EfficientNetB4(EfficientNetGen):
def __init__(self, n_classes: int, pretrained: bool):
super(EfficientNetB4, self).__init__(model='efficientnet-b4', n_classes=n_classes, pretrained=pretrained)
class EfficientNetGenPostStem(FeatureExtractor):
def __init__(self, model: str, n_classes: int, pretrained: bool, n_ir_blocks: int):
super(EfficientNetGenPostStem, self).__init__()
if pretrained:
self.efficientnet = EfficientNet.from_pretrained(model)
else:
self.efficientnet = EfficientNet.from_name(model)
self.n_ir_blocks = n_ir_blocks
self.classifier = nn.Linear(self.efficientnet._conv_head.out_channels, n_classes)
# modify STEM
in_channels = 3 # rgb
out_channels = round_filters(32, self.efficientnet._global_params)
Conv2d = get_same_padding_conv2d(image_size=self.efficientnet._global_params.image_size)
self.efficientnet._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=1, bias=False)
self.init_blocks_args = self.efficientnet._blocks_args[0]
self.init_blocks_args = self.init_blocks_args._replace(output_filters=32)
self.init_block = MBConvBlock(self.init_blocks_args, self.efficientnet._global_params)
self.last_block_args = self.efficientnet._blocks_args[0]
self.last_block_args = self.last_block_args._replace(output_filters=32, stride=2)
self.last_block = MBConvBlock(self.last_block_args, self.efficientnet._global_params)
del self.efficientnet._fc
def features(self, x: torch.Tensor) -> torch.Tensor:
x = self.efficientnet._swish(self.efficientnet._bn0(self.efficientnet._conv_stem(x)))
# init blocks
for b in range(self.n_ir_blocks - 1):
x = self.init_block(x, drop_connect_rate=0)
# last block
x = self.last_block(x, drop_connect_rate=0)
# standard blocks efficientNet:
for idx, block in enumerate(self.efficientnet._blocks):
drop_connect_rate = self.efficientnet._global_params.drop_connect_rate
if drop_connect_rate:
drop_connect_rate *= float(idx) / len(self.efficientnet._blocks)
x = block(x, drop_connect_rate=drop_connect_rate)
x = self.efficientnet._swish(self.efficientnet._bn1(self.efficientnet._conv_head(x)))
x = self.efficientnet._avg_pooling(x)
x = x.flatten(start_dim=1)
return x
def forward(self, x):
x = self.features(x)
x = self.efficientnet._dropout(x)
x = self.classifier(x)
# x = F.softmax(x, dim=-1)
return x
class EfficientNetB0PostStemIR(EfficientNetGenPostStem):
def __init__(self, n_classes: int, pretrained: bool, n_ir_blocks: int):
super(EfficientNetB0PostStemIR, self).__init__(model='efficientnet-b0', n_classes=n_classes,
pretrained=pretrained, n_ir_blocks=n_ir_blocks)
class EfficientNetGenPreStem(FeatureExtractor):
def __init__(self, model: str, n_classes: int, pretrained: bool, n_ir_blocks: int):
super(EfficientNetGenPreStem, self).__init__()
if pretrained:
self.efficientnet = EfficientNet.from_pretrained(model)
else:
self.efficientnet = EfficientNet.from_name(model)
self.n_ir_blocks = n_ir_blocks
self.classifier = nn.Linear(self.efficientnet._conv_head.out_channels, n_classes)
self.init_block_args = self.efficientnet._blocks_args[0]
self.init_block_args = self.init_block_args._replace(input_filters=3, output_filters=32)
self.init_block = MBConvBlock(self.init_block_args, self.efficientnet._global_params)
self.last_blocks_args = self.efficientnet._blocks_args[0]
self.last_blocks_args = self.last_blocks_args._replace(output_filters=32)
self.last_block = MBConvBlock(self.last_blocks_args, self.efficientnet._global_params)
# modify STEM
in_channels = 32
out_channels = round_filters(32, self.efficientnet._global_params)
Conv2d = get_same_padding_conv2d(image_size=self.efficientnet._global_params.image_size)
self.efficientnet._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)
del self.efficientnet._fc
def features(self, x: torch.Tensor) -> torch.Tensor:
# init block
x = self.init_block(x, drop_connect_rate=0)
# other blocks
for b in range(self.n_ir_blocks - 1):
x = self.last_block(x, drop_connect_rate=0)
# standard stem efficientNet:
x = self.efficientnet._swish(self.efficientnet._bn0(self.efficientnet._conv_stem(x)))
# standard blocks efficientNet:
for idx, block in enumerate(self.efficientnet._blocks):
drop_connect_rate = self.efficientnet._global_params.drop_connect_rate
if drop_connect_rate:
drop_connect_rate *= float(idx) / len(self.efficientnet._blocks)
x = block(x, drop_connect_rate=drop_connect_rate)
x = self.efficientnet._swish(self.efficientnet._bn1(self.efficientnet._conv_head(x)))
x = self.efficientnet._avg_pooling(x)
x = x.flatten(start_dim=1)
return x
def forward(self, x):
x = self.features(x)
x = self.efficientnet._dropout(x)
x = self.classifier(x)
# x = F.softmax(x, dim=-1)
return x
class EfficientNetB0PreStemIR(EfficientNetGenPreStem):
def __init__(self, n_classes: int, pretrained: bool, n_ir_blocks: int):
super(EfficientNetB0PreStemIR, self).__init__(model='efficientnet-b0', n_classes=n_classes,
pretrained=pretrained, n_ir_blocks=n_ir_blocks)
class ResNet50(FeatureExtractor):
def __init__(self, n_classes: int, pretrained: bool):
super(ResNet50, self).__init__()
self.resnet = resnet.resnet50(pretrained=pretrained)
self.fc = nn.Linear(in_features=self.resnet.fc.in_features, out_features=n_classes)
del self.resnet.fc
def features(self, x):
x = forward_resnet_conv(self.resnet, x)
x = self.resnet.avgpool(x).flatten(start_dim=1)
return x
def forward(self, x):
x = self.features(x)
x = self.fc(x)
return x
"""
Xception from Kaggle
"""
class XceptionWeiHao(FeatureExtractor):
def __init__(self, n_classes: int, pretrained: bool):
super(XceptionWeiHao, self).__init__()
self.model = get_model("xception", pretrained=pretrained)
self.model = nn.Sequential(*list(self.model.children())[:-1]) # Remove original output layer
self.model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)))
self.model = FCN(self.model, 2048, n_classes)
def features(self, x: torch.Tensor) -> torch.Tensor:
return self.model.base(x)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.features(x)
return self.model.h1(x)
|