Files
Stomach_Cancer_Pytorch/experiments/Models/Xception_Model_Modification.py
2025-11-07 21:03:13 +08:00

380 lines
13 KiB
Python

"""
Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch)
@author: tstandley
Adapted by cadene
Creates an Xception Model as defined in:
Francois Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/pdf/1610.02357.pdf
This weights ported from the Keras implementation. Achieves the following performance on the validation set:
Loss:0.9173 Prec@1:78.892 Prec@5:94.292
REMEMBER to set your image size to 3x299x299 for both test and validation
normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299
"""
import torch.nn as nn
import torch.nn.functional as F
from utils.Stomach_Config import Model_Config
from einops import rearrange
from timm.layers import create_classifier
class SeparableConv2d(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int = 1,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
device=None,
dtype=None,
):
dd = {'device': device, 'dtype': dtype}
super().__init__()
self.conv1 = nn.Conv2d(
in_channels,
in_channels,
kernel_size,
stride,
padding,
dilation,
groups=in_channels,
bias=False,
**dd,
)
self.pointwise = nn.Conv2d(in_channels, out_channels, 1, 1, 0, 1, 1, bias=False, **dd)
def forward(self, x):
x = self.conv1(x)
x = self.pointwise(x)
return x
class Block(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
reps: int,
strides: int = 1,
start_with_relu: bool = True,
grow_first: bool = True,
device=None,
dtype=None,
):
dd = {'device': device, 'dtype': dtype}
super().__init__()
if out_channels != in_channels or strides != 1:
self.skip = nn.Conv2d(in_channels, out_channels, 1, stride=strides, bias=False, **dd)
self.skipbn = nn.BatchNorm2d(out_channels, **dd)
else:
self.skip = None
rep = []
for i in range(reps):
if grow_first:
inc = in_channels if i == 0 else out_channels
outc = out_channels
else:
inc = in_channels
outc = in_channels if i < (reps - 1) else out_channels
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(inc, outc, 3, stride=1, padding=1, **dd))
rep.append(nn.BatchNorm2d(outc, **dd))
if not start_with_relu:
rep = rep[1:]
else:
rep[0] = nn.ReLU(inplace=False)
if strides != 1:
rep.append(nn.MaxPool2d(3, strides, 1))
self.rep = nn.Sequential(*rep)
def forward(self, inp):
x = self.rep(inp)
if self.skip is not None:
skip = self.skip(inp)
skip = self.skipbn(skip)
else:
skip = inp
x += skip
return x
class Xception(nn.Module):
"""
Xception optimized for the ImageNet dataset, as specified in
https://arxiv.org/pdf/1610.02357.pdf
"""
def __init__(
self,
num_classes: int = 1000,
in_chans: int = 3,
drop_rate: float = 0.,
global_pool: str = 'avg',
device=None,
dtype=None,
):
""" Constructor
Args:
num_classes: number of classes
"""
super().__init__()
dd = {'device': device, 'dtype': dtype}
self.drop_rate = drop_rate
self.global_pool = global_pool
self.num_classes = num_classes
self.num_features = self.head_hidden_size = 2048
self.conv1 = nn.Conv2d(in_chans, 32, 3, 2, 0, bias=False, **dd)
self.bn1 = nn.BatchNorm2d(32, **dd)
self.act1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(32, 64, 3, bias=False, **dd)
self.bn2 = nn.BatchNorm2d(64, **dd)
self.act2 = nn.ReLU(inplace=True)
self.block1 = Block(64, 128, 2, 2, start_with_relu=False, **dd)
self.block2 = Block(128, 256, 2, 2, **dd)
self.block3 = Block(256, 728, 2, 2, **dd)
self.block4 = Block(728, 728, 3, 1, **dd)
self.block5 = Block(728, 728, 3, 1, **dd)
self.block6 = Block(728, 728, 3, 1, **dd)
self.block7 = Block(728, 728, 3, 1, **dd)
self.block8 = Block(728, 728, 3, 1, **dd)
self.block9 = Block(728, 728, 3, 1, **dd)
self.block10 = Block(728, 728, 3, 1, **dd)
self.block11 = Block(728, 728, 3, 1, **dd)
self.block12 = Block(728, 1024, 2, 2, grow_first=False, **dd)
self.conv3 = SeparableConv2d(1024, 1536, 3, 1, 1, **dd)
self.bn3 = nn.BatchNorm2d(1536, **dd)
self.act3 = nn.ReLU(inplace=True)
self.conv4 = SeparableConv2d(1536, self.num_features, 3, 1, 1, **dd)
self.bn4 = nn.BatchNorm2d(self.num_features, **dd)
self.act4 = nn.ReLU(inplace=True)
self.feature_info = [
dict(num_chs=64, reduction=2, module='act2'),
dict(num_chs=128, reduction=4, module='block2.rep.0'),
dict(num_chs=256, reduction=8, module='block3.rep.0'),
dict(num_chs=728, reduction=16, module='block12.rep.0'),
dict(num_chs=2048, reduction=32, module='act4'),
]
self.global_pool, self.fc = create_classifier(self.num_features, self.num_classes, pool_type=global_pool, **dd)
self.hidden_layer = nn.Linear(2048, Model_Config["Linear Hidden Nodes"]) # 隱藏層,輸入大小取決於 Xception 的輸出大小
self.output_layer = nn.Linear(Model_Config["Linear Hidden Nodes"], Model_Config["Output Linear Nodes"]) # 輸出層,依據分類數目設定
# 激活函數與 dropout
self.relu = nn.ReLU()
self.dropout = nn.Dropout(Model_Config["Dropout Rate"])
# #------- init weights --------
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def reset_classifier(self, num_classes: int, global_pool: str = 'avg'):
self.num_classes = num_classes
self.global_pool, self.fc = create_classifier(self.num_features, self.num_classes, pool_type=global_pool)
def forward_features(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.act1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.act2(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.block6(x)
x = self.block7(x)
x = self.block8(x)
x = self.block9(x)
x = self.block10(x)
x = self.block11(x)
x = self.block12(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.act3(x)
x = self.conv4(x)
x = self.bn4(x)
x = self.act4(x)
return x
def forward_head(self, x):
x = self.global_pool(x)
return x
def forward(self, x):
x = self.forward_features(x)
x = self.forward_head(x)
x = self.dropout(x) # Dropout
x = self.hidden_layer(x)
x = self.relu(x) # 隱藏層 + ReLU
x = self.output_layer(x) # 輸出層
return x
# class Residual(nn.Module):
# def __init__(self, fn):
# super().__init__()
# self.fn = fn
# def forward(self, x, **kwargs):
# return self.fn(x, **kwargs) + x
# class PreNorm(nn.Module):
# def __init__(self, dim, fn):
# super().__init__()
# self.norm = nn.LayerNorm(dim)
# self.fn = fn
# def forward(self, x, **kwargs):
# return self.fn(self.norm(x), **kwargs)
# class FeedForward(nn.Module):
# def __init__(self, dim, hidden_dim, dropout=0.0):
# super().__init__()
# self.net = nn.Sequential(
# nn.Linear(dim, hidden_dim),
# nn.GELU(),
# nn.Dropout(dropout),
# nn.Linear(hidden_dim, dim),
# nn.Dropout(dropout)
# )
# def forward(self, x):
# return self.net(x)
# class Attention(nn.Module):
# def __init__(self, dim, heads=8, dim_head=64, dropout=0.0):
# super().__init__()
# inner_dim = dim_head * heads
# self.heads = heads
# self.scale = dim_head ** -0.5
# self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
# self.to_out = nn.Sequential(
# nn.Linear(inner_dim, dim),
# nn.Dropout(dropout)
# )
# def forward(self, x, mask=None):
# b, n, _, h = *x.shape, self.heads
# qkv = self.to_qkv(x).chunk(3, dim=-1)
# q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), qkv)
# dots = torch.einsum('bhid,bhjd->bhij', q, k) * self.scale
# if mask is not None:
# mask = F.pad(mask.flatten(1), (1, 0), value=True)
# assert mask.shape[-1] == dots.shape[-1], 'mask has incorrect dimensions'
# mask = mask[:, None, :] * mask[:, :, None]
# dots.masked_fill_(~mask, float('-inf'))
# del mask
# attn = dots.softmax(dim=-1)
# out = torch.einsum('bhij,bhjd->bhid', attn, v)
# out = rearrange(out, 'b h n d -> b n (h d)')
# out = self.to_out(out)
# return out
# class Transformer(nn.Module):
# def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout):
# super().__init__()
# self.layers = nn.ModuleList([])
# for _ in range(depth):
# self.layers.append(nn.ModuleList([
# Residual(PreNorm(dim, Attention(dim, heads=heads, dim_head=dim_head, dropout=dropout))),
# Residual(PreNorm(dim, FeedForward(dim, mlp_dim, dropout=dropout)))
# ]))
# def forward(self, x, mask=None):
# for attn, ff in self.layers:
# x = attn(x, mask=mask)
# x = ff(x)
# return x
# class ViT(nn.Module):
# def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool='cls', channels=3, dim_head=64, dropout=0., emb_dropout=0.):
# super().__init__()
# image_height, image_width = image_size if isinstance(image_size, tuple) else (image_size, image_size)
# patch_height, patch_width = patch_size if isinstance(patch_size, tuple) else (patch_size, patch_size)
# assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
# num_patches = (image_height // patch_height) * (image_width // patch_width)
# patch_dim = channels * patch_height * patch_width
# assert pool in {'cls', 'mean'}, 'pool type must be either cls (class token) or mean (mean pooling)'
# self.to_patch_embedding = nn.Sequential(
# nn.Conv2d(channels, dim, kernel_size=(patch_height, patch_width), stride=(patch_height, patch_width)),
# nn.Flatten(2),
# nn.LayerNorm(dim),
# )
# self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
# self.cls_token = nn.Parameter(torch.randn(1, 1, dim))
# self.dropout = nn.Dropout(emb_dropout)
# self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)
# self.pool = pool
# self.to_latent = nn.Identity()
# self.mlp_head = nn.Sequential(
# nn.LayerNorm(dim),
# nn.Linear(dim, num_classes)
# )
# def forward(self, img, mask=None):
# x = self.to_patch_embedding(img)
# x = x.permute(0, 2, 1)
# b, n, _ = x.shape
# cls_tokens = self.cls_token.expand(b, -1, -1)
# x = torch.cat((cls_tokens, x), dim=1)
# x += self.pos_embedding[:, :(n + 1)]
# x = self.dropout(x)
# x = self.transformer(x, mask)
# x = x.mean(dim=1) if self.pool == 'mean' else x[:, 0]
# x = self.to_latent(x)
# return self.mlp_head(x)