The Xception is modified that the ViT block is appended after Xception middle flow.

This commit is contained in:
whitekirin
2025-11-10 13:12:13 +08:00
parent e6101c5898
commit ab12081149
11 changed files with 274 additions and 128 deletions

View File

@@ -0,0 +1,142 @@
# vit_branch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from typing import Tuple, Optional
class PatchEmbed(nn.Module):
"""將 feature map 切成 patches"""
def __init__(self, in_chs: int = 728, embed_dim: int = 728, patch_size: int = 4):
super().__init__()
self.proj = nn.Conv2d(in_chs, embed_dim, kernel_size=patch_size, stride=patch_size)
self.norm = nn.LayerNorm(embed_dim)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Tuple[int, int]]:
B, C, H, W = x.shape
x = self.proj(x) # (B, D, H/p, W/p)
x = x.flatten(2).transpose(1, 2) # (B, N, D)
x = self.norm(x)
return x, (H, W)
# vit_branch.py
class PatchReconstruction(nn.Module):
def __init__(self, embed_dim=728, out_chs=728, patch_size=4):
super().__init__()
self.patch_size = patch_size
self.out_chs = out_chs
self.proj = nn.Linear(embed_dim, patch_size * patch_size * out_chs)
def forward(self, x, orig_size):
B, N, _ = x.shape
H, W = orig_size
p = self.patch_size
h = H // p
w = W // p
assert h * w == N, f"N mismatch: {h*w} vs {N}"
x = self.proj(x) # (B, N, p*p*C)
x = x.view(B, h, w, p*p, self.out_chs) # (B, h, w, p*p, C)
x = rearrange(
x,
'b h w (p1 p2) c -> b c (h p1) (w p2)',
p1=p, p2=p
)
return x
class TransformerBlock(nn.Module):
def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0,
qkv_bias: bool = True, drop: float = 0., attn_drop: float = 0.):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = nn.MultiheadAttention(dim, num_heads, dropout=attn_drop,
bias=qkv_bias, batch_first=True)
self.norm2 = nn.LayerNorm(dim)
hidden_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(drop),
nn.Linear(hidden_dim, dim),
nn.Dropout(drop)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y, _ = self.attn(self.norm1(x), self.norm1(x), self.norm1(x))
x = x + y
x = x + self.mlp(self.norm2(x))
return x
class ViTBranch(nn.Module):
"""
ViT Branch: 接收 CNN feature map輸出同尺寸增強特徵
用途:與 Xception Middle Flow 融合
"""
def __init__(
self,
in_chs: int = 728,
embed_dim: int = 728,
patch_size: int = 4,
depth: int = 3,
num_heads: int = 8,
mlp_ratio: float = 4.0,
drop_rate: float = 0.0,
attn_drop_rate: float = 0.0,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
):
super().__init__()
factory_kwargs = {'device': device, 'dtype': dtype}
self.patch_embed = PatchEmbed(in_chs, embed_dim, patch_size)
self.patch_recon = PatchReconstruction(embed_dim, in_chs, patch_size)
# Learnable pos embed (will be resized dynamically)
num_patches_approx = ((299 // 16) ** 2)
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches_approx, embed_dim, **factory_kwargs))
nn.init.trunc_normal_(self.pos_embed, std=0.02)
self.blocks = nn.ModuleList([
TransformerBlock(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
drop=drop_rate,
attn_drop=attn_drop_rate
) for _ in range(depth)
])
self.norm = nn.LayerNorm(embed_dim)
def _resize_pos_embed(self, pos_embed: torch.Tensor, target_hw: Tuple[int, int]) -> torch.Tensor:
"""動態調整位置編碼尺寸"""
B = pos_embed.shape[0]
sqrt_N = int(pos_embed.shape[1] ** 0.5)
pos_embed = pos_embed.reshape(1, sqrt_N, sqrt_N, -1).permute(0, 3, 1, 2)
pos_embed = F.interpolate(pos_embed, size=target_hw, mode='bilinear', align_corners=False)
pos_embed = pos_embed.permute(0, 2, 3, 1).flatten(1, 2)
return pos_embed.expand(B, -1, -1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, C, H, W = x.shape
x, orig_size = self.patch_embed(x) # (B, N, D), orig_size=(H,W)
N = x.shape[1]
# 動態調整 pos_embed
target_grid = (H // self.patch_embed.proj.stride[0], W // self.patch_embed.proj.stride[1])
if self.pos_embed.shape[1] != N:
pos_embed = self._resize_pos_embed(self.pos_embed, target_grid)
else:
pos_embed = self.pos_embed.expand(B, -1, -1)
x = x + pos_embed
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
x = self.patch_recon(x, orig_size)
return x

View File

@@ -24,9 +24,9 @@ The resize parameter of the validation transform should be 333, and make sure to
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
from .ViT_Model import ViTBranch # 添加或替換這個導入
class SeparableConv2d(nn.Module):
@@ -248,132 +248,118 @@ class Xception(nn.Module):
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
# xception_vit.py
class XceptionWithViT(nn.Module):
"""
Xception + ViT Branch (Middle Flow 後融合)
"""
def __init__(
self,
num_classes: int = 1000,
in_chans: int = 3,
drop_rate: float = 0.0,
global_pool: str = 'avg',
vit_patch_size: int = 4,
vit_depth: int = 3,
vit_heads: int = 8,
device=None,
dtype=None,
):
super().__init__()
dd = {'device': device, 'dtype': dtype}
self.drop_rate = drop_rate
self.global_pool = global_pool
self.num_features = 2048
# class PreNorm(nn.Module):
# def __init__(self, dim, fn):
# super().__init__()
# self.norm = nn.LayerNorm(dim)
# self.fn = fn
# === Entry Flow ===
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)
# def forward(self, x, **kwargs):
# return self.fn(self.norm(x), **kwargs)
self.conv2 = nn.Conv2d(32, 64, 3, bias=False, **dd)
self.bn2 = nn.BatchNorm2d(64, **dd)
self.act2 = nn.ReLU(inplace=True)
# 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)
# )
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)
# def forward(self, x):
# return self.net(x)
# === Middle Flow ===
for i in range(4, 12):
setattr(self, f'block{i}', Block(728, 728, 3, 1, **dd))
# 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
# === ViT Branch ===
self.vit_branch = ViTBranch(
in_chs=728,
embed_dim=728,
patch_size=4,
depth=3,
num_heads=8,
mlp_ratio=4.0,
drop_rate=0.0,
attn_drop_rate=0.0,
device=device,
dtype=dtype
)
# self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
# self.to_out = nn.Sequential(
# nn.Linear(inner_dim, dim),
# nn.Dropout(dropout)
# )
# === Exit Flow ===
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)
# 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)
# === Classifier ===
self.global_pool, _ = create_classifier(self.num_features, num_classes, pool_type=global_pool, **dd)
self.hidden_layer = nn.Linear(2048, Model_Config["Linear Hidden Nodes"])
self.output_layer = nn.Linear(Model_Config["Linear Hidden Nodes"], Model_Config["Output Linear Nodes"])
self.relu = nn.ReLU()
self.dropout = nn.Dropout(Model_Config["Dropout Rate"])
# dots = torch.einsum('bhid,bhjd->bhij', q, k) * self.scale
# === Weight Init ===
self._init_weights()
# 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
def _init_weights(self):
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, nn.LayerNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
# attn = dots.softmax(dim=-1)
def forward_features(self, x):
# Entry
x = self.act1(self.bn1(self.conv1(x)))
x = self.act2(self.bn2(self.conv2(x)))
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
# 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
# Middle Flow
for i in range(4, 12):
x = getattr(self, f'block{i}')(x)
# 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)))
# ]))
# === ViT Fusion ===
vit_out = self.vit_branch(x)
x = x + vit_out # element-wise add
# def forward(self, x, mask=None):
# for attn, ff in self.layers:
# x = attn(x, mask=mask)
# x = ff(x)
# return x
# Exit Flow
x = self.block12(x)
x = self.act3(self.bn3(self.conv3(x)))
x = self.act4(self.bn4(self.conv4(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)
def forward(self, x):
x = self.forward_features(x)
x = self.global_pool(x)
x = self.dropout(x)
x = self.relu(self.hidden_layer(x))
x = self.output_layer(x)
return x

View File

@@ -14,7 +14,7 @@ from Model_Loss.Loss import Entropy_Loss
from merge_class.merge import merge
from draw_tools.Saliency_Map import SaliencyMap
from utils.Stomach_Config import Training_Config, Loading_Config, Save_Result_File_Config
from experiments.Models.Xception_Model_Modification import Xception
from experiments.Models.Xception_Model_Modification import Xception, XceptionWithViT
from experiments.Models.pytorch_Model import ModifiedXception
from Load_process.LoadData import Loding_Data_Root
from Training_Tools.PreProcess import Training_Precesses
@@ -143,9 +143,15 @@ class Xception_Identification_Block_Training_Step(Loding_Data_Root, Training_Pre
print(f"\nCross-Validation Results:")
print(f"Avg Train Loss: {avg_train_losses:.4f}, Avg Val Loss: {avg_val_losses:.4f}")
print(f"Avg Train Acc: {avg_train_accuracies:.4f}, Avg Val Acc: {avg_val_accuracies:.4f}")
print(f"Avg Train Acc: {avg_train_accuracies:.4f}, Avg Val Acc: {avg_val_accuracies:.4f}\n\n")
File.Save_TXT_File(content = f"\nCross-Validation Results:\nAvg Train Loss: {avg_train_losses:.4f}, Avg Val Loss: {avg_val_losses:.4f}\nAvg Train Acc: {avg_train_accuracies:.4f}, Avg Val Acc: {avg_val_accuracies:.4f}\n", Save_Root = Save_Result_File_Config["Identification_Average_Result"], File_Name = "Training_Average_Result")
print(f"==========平均模型訓練結果================\n{Calculate_Process.Output_Style()}\n")
print(f"==========各類別評估結果===============")
for Calculate_Every_Class in Calculate_Tool:
print(f"{Calculate_Every_Class.Output_Style()}")
File.Save_TXT_File(content = f"\n\nCross-Validation Results:\nAvg Train Loss: {avg_train_losses:.4f}, Avg Val Loss: {avg_val_losses:.4f}\nAvg Train Acc: {avg_train_accuracies:.4f}, Avg Val Acc: {avg_val_accuracies:.4f}\n", Save_Root = Save_Result_File_Config["Identification_Average_Result"], File_Name = "Training_Average_Result")
# 返回最後一個fold的模型路徑和平均指標
return Best_Model_Path
@@ -237,18 +243,18 @@ class Xception_Identification_Block_Training_Step(Loding_Data_Root, Training_Pre
def Construct_Identification_Model_CUDA(self):
# 从Model_Config中获取输出节点数量
# Model = ModifiedXception()
Model = Xception(num_classes=0)
Model = XceptionWithViT(num_classes=0)
print(summary(Model))
for name, parameters in Model.named_parameters():
print(f"Layer Name: {name}, Parameters: {parameters.size()}")
# for name, parameters in Model.named_parameters():
# print(f"Layer Name: {name}, Parameters: {parameters.size()}")
# 注释掉summary调用避免Mask参数问题
# 直接打印模型结构
print(f"Model structure: {Model}")
# # 注释掉summary调用避免Mask参数问题
# # 直接打印模型结构
# print(f"Model structure: {Model}")
# 打印模型参数和梯度状态
for name, parameters in Model.named_parameters():
print(f"Layer Name: {name}, Parameters: {parameters.size()}, requires_grad: {parameters.requires_grad}")
# # 打印模型参数和梯度状态
# for name, parameters in Model.named_parameters():
# print(f"Layer Name: {name}, Parameters: {parameters.size()}, requires_grad: {parameters.requires_grad}")
self.TargetLayer = Model.conv4.pointwise.weight
# self.TargetLayer = Model.base_model.conv4.pointwise

View File

@@ -5,6 +5,7 @@ description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
"einops>=0.8.1",
"opencv-python-headless>=4.12.0.88",
"pandas>=2.3.3",
"scikit-image>=0.25.2",

View File

@@ -36,7 +36,7 @@ Training_Config = {
"CA_Experiment_Name": f"New architecture of Xception to CA and Have Question",
"Normal_Experiment_Name": f"New architecture of Xception to Normal and Others",
"Mask_Experiment_Name" : "New architecture of GastoSegNet",
"Three_Classes_Experiment_Name" : "Xception to Three Classes",
"Three_Classes_Experiment_Name" : "Xception adds Vision Transformer Large to training three classes",
"Epoch": 10000,
"Train_Batch_Size": 64,
"Image_Size": 256,

11
uv.lock generated
View File

@@ -125,6 +125,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },
]
[[package]]
name = "einops"
version = "0.8.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" },
]
[[package]]
name = "filelock"
version = "3.20.0"
@@ -781,6 +790,7 @@ name = "pytorch"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "einops" },
{ name = "opencv-python-headless" },
{ name = "pandas" },
{ name = "scikit-image" },
@@ -795,6 +805,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "einops", specifier = ">=0.8.1" },
{ name = "opencv-python-headless", specifier = ">=4.12.0.88" },
{ name = "pandas", specifier = ">=2.3.3" },
{ name = "scikit-image", specifier = ">=0.25.2" },