diff --git a/Image/AlexNet/code/model.py b/Image/AlexNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2633e4f1b1942b995073fc149ee02d41aa05f6f7 --- /dev/null +++ b/Image/AlexNet/code/model.py @@ -0,0 +1,81 @@ +''' +AlexNet in Pytorch +''' + +import torch +import torch.nn as nn + +class AlexNet(nn.Module): # 训练 ALexNet + ''' + AlexNet模型 + ''' + def __init__(self,num_classes=10): + super(AlexNet,self).__init__() + # 五个卷积层 输入 32 * 32 * 3 + self.conv1 = nn.Sequential( + nn.Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=1), # (32-3+2)/1+1 = 32 + nn.ReLU(), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # (32-2)/2+1 = 16 + ) + self.conv2 = nn.Sequential( # 输入 16 * 16 * 6 + nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3, stride=1, padding=1), # (16-3+2)/1+1 = 16 + nn.ReLU(), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # (16-2)/2+1 = 8 + ) + self.conv3 = nn.Sequential( # 输入 8 * 8 * 16 + nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1), # (8-3+2)/1+1 = 8 + nn.ReLU(), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # (8-2)/2+1 = 4 + ) + self.conv4 = nn.Sequential( # 输入 4 * 4 * 64 + nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1), # (4-3+2)/1+1 = 4 + nn.ReLU(), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # (4-2)/2+1 = 2 + ) + self.conv5 = nn.Sequential( # 输入 2 * 2 * 128 + nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),# (2-3+2)/1+1 = 2 + nn.ReLU(), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # (2-2)/2+1 = 1 + ) # 最后一层卷积层,输出 1 * 1 * 128 + # 全连接层 + self.dense = nn.Sequential( + nn.Linear(128,120), + nn.ReLU(), + nn.Linear(120,84), + nn.ReLU(), + nn.Linear(84,num_classes) + ) + + # 初始化权重 + self._initialize_weights() + + def forward(self,x): + x = self.conv1(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.conv4(x) + x = self.conv5(x) + x = x.view(x.size()[0],-1) + x = self.dense(x) + return x + + def _initialize_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + 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) + +def test(): + net = AlexNet() + x = torch.randn(2,3,32,32) + y = net(x) + print(y.size()) + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net,(3,32,32)) \ No newline at end of file diff --git a/Image/AlexNet/code/train.py b/Image/AlexNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c6597f06ab33893e2d0d51ced4beccd2ce219bfa --- /dev/null +++ b/Image/AlexNet/code/train.py @@ -0,0 +1,41 @@ +import sys +import os +import argparse +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import AlexNet + +def parse_args(): + parser = argparse.ArgumentParser(description='训练AlexNet模型') + parser.add_argument('--gpu', type=int, default=0, help='GPU设备编号 (0,1,2,3)') + parser.add_argument('--batch-size', type=int, default=128, help='批次大小') + parser.add_argument('--epochs', type=int, default=200, help='训练轮数') + parser.add_argument('--lr', type=float, default=0.1, help='学习率') + return parser.parse_args() + +def main(): + # 解析命令行参数 + args = parse_args() + + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size) + + # 创建模型 + model = AlexNet() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=args.epochs, + lr=args.lr, + device=f'cuda:{args.gpu}', + save_dir='../model', + model_name='alexnet' + ) + +if __name__ == '__main__': + main() diff --git a/Graph/.gitkeep b/Image/AlexNet/dataset/.gitkeep similarity index 100% rename from Graph/.gitkeep rename to Image/AlexNet/dataset/.gitkeep diff --git a/Image/.gitkeep b/Image/AlexNet/model/.gitkeep similarity index 100% rename from Image/.gitkeep rename to Image/AlexNet/model/.gitkeep diff --git a/Image/DenseNet/code/model.py b/Image/DenseNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3308e0d3abe06d8da77e843a0be593159287297a --- /dev/null +++ b/Image/DenseNet/code/model.py @@ -0,0 +1,152 @@ +""" +DenseNet in pytorch +see the details in papaer +[1] Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger. + Densely Connected Convolutional Networks + https://arxiv.org/abs/1608.06993v5 +""" +import torch +import torch.nn as nn +import math + +class Bottleneck(nn.Module): + """ + Dense Block + 这里的growth_rate=out_channels, 就是每个Block自己输出的通道数。 + 先通过1x1卷积层,将通道数缩小为4 * growth_rate,然后再通过3x3卷积层降低到growth_rate。 + """ + # 通常1×1卷积的通道数为GrowthRate的4倍 + expansion = 4 + + def __init__(self, in_channels, growth_rate): + super(Bottleneck, self).__init__() + zip_channels = self.expansion * growth_rate + self.features = nn.Sequential( + nn.BatchNorm2d(in_channels), + nn.ReLU(True), + nn.Conv2d(in_channels, zip_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(zip_channels), + nn.ReLU(True), + nn.Conv2d(zip_channels, growth_rate, kernel_size=3, padding=1, bias=False) + ) + + def forward(self, x): + out = self.features(x) + out = torch.cat([out, x], 1) + return out + + +class Transition(nn.Module): + """ + 改变维数的Transition层 具体包括BN、ReLU、1×1卷积(Conv)、2×2平均池化操作 + 先通过1x1的卷积层减少channels,再通过2x2的平均池化层缩小feature-map + """ + # 1×1卷积的作用是降维,起到压缩模型的作用,而平均池化则是降低特征图的尺寸。 + def __init__(self, in_channels, out_channels): + super(Transition, self).__init__() + self.features = nn.Sequential( + nn.BatchNorm2d(in_channels), + nn.ReLU(True), + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), + nn.AvgPool2d(2) + ) + + def forward(self, x): + out = self.features(x) + return out + +class DenseNet(nn.Module): + """ + Dense Net + paper中growth_rate取12,维度压缩的参数θ,即reduction取0.5 + 且初始化方法为kaiming_normal() + num_blocks为每段网络中的DenseBlock数量 + DenseNet和ResNet一样也是六段式网络(一段卷积+四段Dense+平均池化层),最后FC层。 + 第一段将维数从3变到2 * growth_rate + + (3, 32, 32) -> [Conv2d] -> (24, 32, 32) -> [layer1] -> (48, 16, 16) -> [layer2] + ->(96, 8, 8) -> [layer3] -> (192, 4, 4) -> [layer4] -> (384, 4, 4) -> [AvgPool] + ->(384, 1, 1) -> [Linear] -> (10) + """ + def __init__(self, num_blocks, growth_rate=12, reduction=0.5, num_classes=10, init_weights=True): + super(DenseNet, self).__init__() + self.growth_rate = growth_rate + self.reduction = reduction + + num_channels = 2 * growth_rate + + self.features = nn.Conv2d(3, num_channels, kernel_size=3, padding=1, bias=False) + self.layer1, num_channels = self._make_dense_layer(num_channels, num_blocks[0]) + self.layer2, num_channels = self._make_dense_layer(num_channels, num_blocks[1]) + self.layer3, num_channels = self._make_dense_layer(num_channels, num_blocks[2]) + self.layer4, num_channels = self._make_dense_layer(num_channels, num_blocks[3], transition=False) + self.avg_pool = nn.Sequential( + nn.BatchNorm2d(num_channels), + nn.ReLU(True), + nn.AvgPool2d(4), + ) + self.classifier = nn.Linear(num_channels, num_classes) + + if init_weights: + self._initialize_weights() + + def _make_dense_layer(self, in_channels, nblock, transition=True): + layers = [] + for i in range(nblock): + layers += [Bottleneck(in_channels, self.growth_rate)] + in_channels += self.growth_rate + out_channels = in_channels + if transition: + out_channels = int(math.floor(in_channels * self.reduction)) + layers += [Transition(in_channels, out_channels)] + return nn.Sequential(*layers), out_channels + + def _initialize_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + 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) + nn.init.constant_(m.bias, 0) + + def forward(self, x): + out = self.features(x) + out = self.layer1(out) + out = self.layer2(out) + out = self.layer3(out) + out = self.layer4(out) + out = self.avg_pool(out) + out = out.view(out.size(0), -1) + out = self.classifier(out) + return out + +def DenseNet121(): + return DenseNet([6,12,24,16], growth_rate=32) + +def DenseNet169(): + return DenseNet([6,12,32,32], growth_rate=32) + +def DenseNet201(): + return DenseNet([6,12,48,32], growth_rate=32) + +def DenseNet161(): + return DenseNet([6,12,36,24], growth_rate=48) + +def densenet_cifar(): + return DenseNet([6,12,24,16], growth_rate=12) + + +def test(): + net = densenet_cifar() + x = torch.randn(1,3,32,32) + y = net(x) + print(y.size()) + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net,(1,3,32,32)) \ No newline at end of file diff --git a/Image/DenseNet/code/train.py b/Image/DenseNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d048b591147e26cd7ed084bf7db78f10fb2ca180 --- /dev/null +++ b/Image/DenseNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import DenseNet121 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = DenseNet121() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='densenet121' + ) + +if __name__ == '__main__': + main() diff --git a/Image/DenseNet/dataset/.gitkeep b/Image/DenseNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/DenseNet/model/.gitkeep b/Image/DenseNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/EfficientNet/code/model.py b/Image/EfficientNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b731fd4ae8b1491bf46152a4c85f73cc5a6e2cc4 --- /dev/null +++ b/Image/EfficientNet/code/model.py @@ -0,0 +1,267 @@ +''' +EfficientNet in PyTorch. + +Paper: "EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks" +Reference: https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py + +主要特点: +1. 使用MBConv作为基本模块,包含SE注意力机制 +2. 通过复合缩放方法(compound scaling)同时调整网络的宽度、深度和分辨率 +3. 使用Swish激活函数和DropConnect正则化 +''' +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + +def swish(x): + """Swish激活函数: x * sigmoid(x)""" + return x * x.sigmoid() + +def drop_connect(x, drop_ratio): + """DropConnect正则化 + + Args: + x: 输入tensor + drop_ratio: 丢弃率 + + Returns: + 经过DropConnect处理的tensor + """ + keep_ratio = 1.0 - drop_ratio + mask = torch.empty([x.shape[0], 1, 1, 1], dtype=x.dtype, device=x.device) + mask.bernoulli_(keep_ratio) + x.div_(keep_ratio) + x.mul_(mask) + return x + +class SE(nn.Module): + '''Squeeze-and-Excitation注意力模块 + + Args: + in_channels: 输入通道数 + se_channels: SE模块中间层的通道数 + ''' + def __init__(self, in_channels, se_channels): + super(SE, self).__init__() + self.se1 = nn.Conv2d(in_channels, se_channels, kernel_size=1, bias=True) + self.se2 = nn.Conv2d(se_channels, in_channels, kernel_size=1, bias=True) + + def forward(self, x): + out = F.adaptive_avg_pool2d(x, (1, 1)) # 全局平均池化 + out = swish(self.se1(out)) + out = self.se2(out).sigmoid() + return x * out # 特征重标定 + +class MBConv(nn.Module): + '''MBConv模块: Mobile Inverted Bottleneck Convolution + + Args: + in_channels: 输入通道数 + out_channels: 输出通道数 + kernel_size: 卷积核大小 + stride: 步长 + expand_ratio: 扩展比率 + se_ratio: SE模块的压缩比率 + drop_rate: DropConnect的丢弃率 + ''' + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + expand_ratio=1, + se_ratio=0.25, + drop_rate=0.): + super(MBConv, self).__init__() + self.stride = stride + self.drop_rate = drop_rate + self.expand_ratio = expand_ratio + + # Expansion phase + channels = expand_ratio * in_channels + self.conv1 = nn.Conv2d(in_channels, channels, kernel_size=1, stride=1, padding=0, bias=False) + self.bn1 = nn.BatchNorm2d(channels) + + # Depthwise conv + self.conv2 = nn.Conv2d(channels, channels, kernel_size=kernel_size, stride=stride, + padding=(1 if kernel_size == 3 else 2), groups=channels, bias=False) + self.bn2 = nn.BatchNorm2d(channels) + + # SE layers + se_channels = int(in_channels * se_ratio) + self.se = SE(channels, se_channels) + + # Output phase + self.conv3 = nn.Conv2d(channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False) + self.bn3 = nn.BatchNorm2d(out_channels) + + # Shortcut connection + self.has_skip = (stride == 1) and (in_channels == out_channels) + + def forward(self, x): + # Expansion + out = x if self.expand_ratio == 1 else swish(self.bn1(self.conv1(x))) + # Depthwise convolution + out = swish(self.bn2(self.conv2(out))) + # Squeeze-and-excitation + out = self.se(out) + # Pointwise convolution + out = self.bn3(self.conv3(out)) + # Shortcut + if self.has_skip: + if self.training and self.drop_rate > 0: + out = drop_connect(out, self.drop_rate) + out = out + x + return out + +class EfficientNet(nn.Module): + '''EfficientNet模型 + + Args: + width_coefficient: 宽度系数 + depth_coefficient: 深度系数 + dropout_rate: 分类层的dropout率 + num_classes: 分类数量 + ''' + def __init__(self, + width_coefficient=1.0, + depth_coefficient=1.0, + dropout_rate=0.2, + num_classes=10): + super(EfficientNet, self).__init__() + + # 模型配置 + cfg = { + 'num_blocks': [1, 2, 2, 3, 3, 4, 1], # 每个stage的block数量 + 'expansion': [1, 6, 6, 6, 6, 6, 6], # 扩展比率 + 'out_channels': [16, 24, 40, 80, 112, 192, 320], # 输出通道数 + 'kernel_size': [3, 3, 5, 3, 5, 5, 3], # 卷积核大小 + 'stride': [1, 2, 2, 2, 1, 2, 1], # 步长 + 'dropout_rate': dropout_rate, + 'drop_connect_rate': 0.2, + } + + self.cfg = cfg + self.width_coefficient = width_coefficient + self.depth_coefficient = depth_coefficient + + # Stem layer + self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(32) + + # Build blocks + self.layers = self._make_layers(in_channels=32) + + # Head layer + final_channels = cfg['out_channels'][-1] * int(width_coefficient) + self.linear = nn.Linear(final_channels, num_classes) + + def _make_layers(self, in_channels): + layers = [] + cfg = [self.cfg[k] for k in ['expansion', 'out_channels', 'num_blocks', 'kernel_size', 'stride']] + blocks = sum(self.cfg['num_blocks']) + b = 0 # 用于计算drop_connect_rate + + for expansion, out_channels, num_blocks, kernel_size, stride in zip(*cfg): + out_channels = int(out_channels * self.width_coefficient) + num_blocks = int(math.ceil(num_blocks * self.depth_coefficient)) + + for i in range(num_blocks): + stride_i = stride if i == 0 else 1 + drop_rate = self.cfg['drop_connect_rate'] * b / blocks + layers.append( + MBConv(in_channels, + out_channels, + kernel_size, + stride_i, + expansion, + se_ratio=0.25, + drop_rate=drop_rate)) + in_channels = out_channels + b += 1 + + return nn.Sequential(*layers) + + def forward(self, x): + # Stem + out = swish(self.bn1(self.conv1(x))) + # Blocks + out = self.layers(out) + # Head + out = F.adaptive_avg_pool2d(out, 1) + out = out.view(out.size(0), -1) + if self.training and self.cfg['dropout_rate'] > 0: + out = F.dropout(out, p=self.cfg['dropout_rate']) + out = self.linear(out) + return out + +def EfficientNetB0(num_classes=10): + """EfficientNet-B0""" + return EfficientNet(width_coefficient=1.0, + depth_coefficient=1.0, + dropout_rate=0.2, + num_classes=num_classes) + +def EfficientNetB1(num_classes=10): + """EfficientNet-B1""" + return EfficientNet(width_coefficient=1.0, + depth_coefficient=1.1, + dropout_rate=0.2, + num_classes=num_classes) + +def EfficientNetB2(num_classes=10): + """EfficientNet-B2""" + return EfficientNet(width_coefficient=1.1, + depth_coefficient=1.2, + dropout_rate=0.3, + num_classes=num_classes) + +def EfficientNetB3(num_classes=10): + """EfficientNet-B3""" + return EfficientNet(width_coefficient=1.2, + depth_coefficient=1.4, + dropout_rate=0.3, + num_classes=num_classes) + +def EfficientNetB4(num_classes=10): + """EfficientNet-B4""" + return EfficientNet(width_coefficient=1.4, + depth_coefficient=1.8, + dropout_rate=0.4, + num_classes=num_classes) + +def EfficientNetB5(num_classes=10): + """EfficientNet-B5""" + return EfficientNet(width_coefficient=1.6, + depth_coefficient=2.2, + dropout_rate=0.4, + num_classes=num_classes) + +def EfficientNetB6(num_classes=10): + """EfficientNet-B6""" + return EfficientNet(width_coefficient=1.8, + depth_coefficient=2.6, + dropout_rate=0.5, + num_classes=num_classes) + +def EfficientNetB7(num_classes=10): + """EfficientNet-B7""" + return EfficientNet(width_coefficient=2.0, + depth_coefficient=3.1, + dropout_rate=0.5, + num_classes=num_classes) + +def test(): + """测试函数""" + net = EfficientNetB0() + x = torch.randn(1, 3, 32, 32) + y = net(x) + print(y.size()) + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (1, 3, 32, 32)) + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/EfficientNet/code/train.py b/Image/EfficientNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7e3d032e329207b8041d5101b3bc957b667b70 --- /dev/null +++ b/Image/EfficientNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import EfficientNetB0 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = EfficientNetB0() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='efficientnet_b0' + ) + +if __name__ == '__main__': + main() diff --git a/Image/EfficientNet/dataset/.gitkeep b/Image/EfficientNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/EfficientNet/model/.gitkeep b/Image/EfficientNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/GoogLeNet/code/model.py b/Image/GoogLeNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..91ce924467dd0f63a62567b5ba11ed8c819366a2 --- /dev/null +++ b/Image/GoogLeNet/code/model.py @@ -0,0 +1,159 @@ +''' +GoogLeNet in PyTorch. + +Paper: "Going Deeper with Convolutions" +Reference: https://arxiv.org/abs/1409.4842 + +主要特点: +1. 使用Inception模块,通过多尺度卷积提取特征 +2. 采用1x1卷积降维,减少计算量 +3. 使用全局平均池化代替全连接层 +4. 引入辅助分类器帮助训练(本实现未包含) +''' +import torch +import torch.nn as nn + +class Inception(nn.Module): + '''Inception模块 + + Args: + in_planes: 输入通道数 + n1x1: 1x1卷积分支的输出通道数 + n3x3red: 3x3卷积分支的降维通道数 + n3x3: 3x3卷积分支的输出通道数 + n5x5red: 5x5卷积分支的降维通道数 + n5x5: 5x5卷积分支的输出通道数 + pool_planes: 池化分支的输出通道数 + ''' + def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes): + super(Inception, self).__init__() + + # 1x1卷积分支 + self.branch1 = nn.Sequential( + nn.Conv2d(in_planes, n1x1, kernel_size=1), + nn.BatchNorm2d(n1x1), + nn.ReLU(True), + ) + + # 1x1 -> 3x3卷积分支 + self.branch2 = nn.Sequential( + nn.Conv2d(in_planes, n3x3red, kernel_size=1), + nn.BatchNorm2d(n3x3red), + nn.ReLU(True), + nn.Conv2d(n3x3red, n3x3, kernel_size=3, padding=1), + nn.BatchNorm2d(n3x3), + nn.ReLU(True), + ) + + # 1x1 -> 5x5卷积分支(用两个3x3代替) + self.branch3 = nn.Sequential( + nn.Conv2d(in_planes, n5x5red, kernel_size=1), + nn.BatchNorm2d(n5x5red), + nn.ReLU(True), + nn.Conv2d(n5x5red, n5x5, kernel_size=3, padding=1), + nn.BatchNorm2d(n5x5), + nn.ReLU(True), + nn.Conv2d(n5x5, n5x5, kernel_size=3, padding=1), + nn.BatchNorm2d(n5x5), + nn.ReLU(True), + ) + + # 3x3池化 -> 1x1卷积分支 + self.branch4 = nn.Sequential( + nn.MaxPool2d(3, stride=1, padding=1), + nn.Conv2d(in_planes, pool_planes, kernel_size=1), + nn.BatchNorm2d(pool_planes), + nn.ReLU(True), + ) + + def forward(self, x): + '''前向传播,将四个分支的输出在通道维度上拼接''' + b1 = self.branch1(x) + b2 = self.branch2(x) + b3 = self.branch3(x) + b4 = self.branch4(x) + return torch.cat([b1, b2, b3, b4], 1) + + +class GoogLeNet(nn.Module): + '''GoogLeNet/Inception v1网络 + + 特点: + 1. 使用Inception模块构建深层网络 + 2. 通过1x1卷积降维减少计算量 + 3. 使用全局平均池化代替全连接层减少参数量 + ''' + def __init__(self, num_classes=10): + super(GoogLeNet, self).__init__() + + # 第一阶段:标准卷积层 + self.pre_layers = nn.Sequential( + nn.Conv2d(3, 192, kernel_size=3, padding=1), + nn.BatchNorm2d(192), + nn.ReLU(True), + ) + + # 第二阶段:2个Inception模块 + self.a3 = Inception(192, 64, 96, 128, 16, 32, 32) # 输出通道:256 + self.b3 = Inception(256, 128, 128, 192, 32, 96, 64) # 输出通道:480 + + # 最大池化层 + self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) + + # 第三阶段:5个Inception模块 + self.a4 = Inception(480, 192, 96, 208, 16, 48, 64) # 输出通道:512 + self.b4 = Inception(512, 160, 112, 224, 24, 64, 64) # 输出通道:512 + self.c4 = Inception(512, 128, 128, 256, 24, 64, 64) # 输出通道:512 + self.d4 = Inception(512, 112, 144, 288, 32, 64, 64) # 输出通道:528 + self.e4 = Inception(528, 256, 160, 320, 32, 128, 128) # 输出通道:832 + + # 第四阶段:2个Inception模块 + self.a5 = Inception(832, 256, 160, 320, 32, 128, 128) # 输出通道:832 + self.b5 = Inception(832, 384, 192, 384, 48, 128, 128) # 输出通道:1024 + + # 全局平均池化和分类器 + self.avgpool = nn.AvgPool2d(8, stride=1) + self.linear = nn.Linear(1024, num_classes) + + def forward(self, x): + # 第一阶段 + out = self.pre_layers(x) + + # 第二阶段 + out = self.a3(out) + out = self.b3(out) + out = self.maxpool(out) + + # 第三阶段 + out = self.a4(out) + out = self.b4(out) + out = self.c4(out) + out = self.d4(out) + out = self.e4(out) + out = self.maxpool(out) + + # 第四阶段 + out = self.a5(out) + out = self.b5(out) + + # 分类器 + out = self.avgpool(out) + out = out.view(out.size(0), -1) + out = self.linear(out) + return out + +def test(): + """测试函数""" + net = GoogLeNet() + x = torch.randn(1, 3, 32, 32) + y = net(x) + print(y.size()) + + # 打印模型结构 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (1, 3, 32, 32)) + +if __name__ == '__main__': + test() diff --git a/Image/GoogLeNet/code/train.py b/Image/GoogLeNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3f591f693deb32abc8fab1de35e255aa9cf62975 --- /dev/null +++ b/Image/GoogLeNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import GoogLeNet + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = GoogLeNet() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='googlenet' + ) + +if __name__ == '__main__': + main() diff --git a/Image/GoogLeNet/dataset/.gitkeep b/Image/GoogLeNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/GoogLeNet/model/.gitkeep b/Image/GoogLeNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/LeNet5/code/model.py b/Image/LeNet5/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed820811e24f28f57d68967d20d78969ef1f1f9 --- /dev/null +++ b/Image/LeNet5/code/model.py @@ -0,0 +1,175 @@ +''' +LeNet5 in PyTorch + +LeNet5是由Yann LeCun等人在1998年提出的一个经典卷积神经网络模型。 +主要用于手写数字识别,具有以下特点: +1. 使用卷积层提取特征 +2. 使用平均池化层降低特征维度 +3. 使用全连接层进行分类 +4. 网络结构简单,参数量少 + +网络架构: + 5x5 conv, 6 2x2 pool 5x5 conv, 16 2x2 pool FC 120 FC 84 FC 10 +input(32x32x3) -> [conv1+relu+pool] --------> 28x28x6 -----> 14x14x6 -----> 10x10x16 -----> 5x5x16 -> 120 -> 84 -> 10 + stride 1 stride 2 stride 1 stride 2 + +参考论文: +[1] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner, "Gradient-based learning applied to document recognition," + Proceedings of the IEEE, vol. 86, no. 11, pp. 2278-2324, Nov. 1998. +''' + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ConvBlock(nn.Module): + """卷积块模块 + + 包含: 卷积层 -> ReLU -> 最大池化层 + + Args: + in_channels (int): 输入通道数 + out_channels (int): 输出通道数 + kernel_size (int): 卷积核大小 + stride (int): 卷积步长 + padding (int): 填充大小 + """ + def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0): + super(ConvBlock, self).__init__() + self.conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding + ) + self.relu = nn.ReLU(inplace=True) # inplace操作可以节省内存 + self.pool = nn.MaxPool2d(kernel_size=2, stride=2) + + def forward(self, x): + """前向传播 + + Args: + x (torch.Tensor): 输入特征图 + + Returns: + torch.Tensor: 输出特征图 + """ + x = self.conv(x) + x = self.relu(x) + x = self.pool(x) + return x + + +class LeNet5(nn.Module): + '''LeNet5网络模型 + + 网络结构: + 1. 卷积层1: 3通道输入,6个5x5卷积核,步长1 + 2. 最大池化层1: 2x2窗口,步长2 + 3. 卷积层2: 6通道输入,16个5x5卷积核,步长1 + 4. 最大池化层2: 2x2窗口,步长2 + 5. 全连接层1: 400->120 + 6. 全连接层2: 120->84 + 7. 全连接层3: 84->num_classes + + Args: + num_classes (int): 分类数量,默认为10 + init_weights (bool): 是否初始化权重,默认为True + ''' + def __init__(self, num_classes=10, init_weights=True): + super(LeNet5, self).__init__() + + # 第一个卷积块: 32x32x3 -> 28x28x6 -> 14x14x6 + self.conv1 = ConvBlock( + in_channels=3, + out_channels=6, + kernel_size=5, + stride=1 + ) + + # 第二个卷积块: 14x14x6 -> 10x10x16 -> 5x5x16 + self.conv2 = ConvBlock( + in_channels=6, + out_channels=16, + kernel_size=5, + stride=1 + ) + + # 全连接层 + self.classifier = nn.Sequential( + nn.Linear(5*5*16, 120), + nn.ReLU(inplace=True), + nn.Linear(120, 84), + nn.ReLU(inplace=True), + nn.Linear(84, num_classes) + ) + + # 初始化权重 + if init_weights: + self._initialize_weights() + + def forward(self, x): + '''前向传播 + + Args: + x (torch.Tensor): 输入图像张量,[N,3,32,32] + + Returns: + torch.Tensor: 输出预测张量,[N,num_classes] + ''' + # 特征提取 + x = self.conv1(x) # -> [N,6,14,14] + x = self.conv2(x) # -> [N,16,5,5] + + # 分类 + x = torch.flatten(x, 1) # -> [N,16*5*5] + x = self.classifier(x) # -> [N,num_classes] + return x + + def _initialize_weights(self): + '''初始化模型权重 + + 采用kaiming初始化方法: + - 卷积层权重采用kaiming_normal_初始化 + - 线性层权重采用normal_初始化 + - 所有偏置项初始化为0 + ''' + for m in self.modules(): + if isinstance(m, nn.Conv2d): + # 采用kaiming初始化,适合ReLU激活函数 + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + # 采用正态分布初始化 + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + +def test(): + """测试函数 + + 创建模型并进行前向传播测试,打印模型结构和参数信息 + """ + # 创建模型 + net = LeNet5() + print('Model Structure:') + print(net) + + # 测试前向传播 + x = torch.randn(2,3,32,32) + y = net(x) + print('\nInput Shape:', x.shape) + print('Output Shape:', y.shape) + + # 打印模型信息 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (2,3,32,32)) + + +if __name__ == '__main__': + test() diff --git a/Image/LeNet5/code/train.py b/Image/LeNet5/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..14cc502d2760223b8b82ad74d3943586f2cad070 --- /dev/null +++ b/Image/LeNet5/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import LeNet5 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = LeNet5() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='lenet5' + ) + +if __name__ == '__main__': + main() diff --git a/Image/LeNet5/dataset/.gitkeep b/Image/LeNet5/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/LeNet5/model/.gitkeep b/Image/LeNet5/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv1/code/model.py b/Image/MobileNetv1/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..215a894aec5cea342787d4f55ef64bc87ea9b0c6 --- /dev/null +++ b/Image/MobileNetv1/code/model.py @@ -0,0 +1,163 @@ +''' +MobileNetv1 in PyTorch. + +论文: "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" +参考: https://arxiv.org/abs/1704.04861 + +主要特点: +1. 使用深度可分离卷积(Depthwise Separable Convolution)减少参数量和计算量 +2. 引入宽度乘子(Width Multiplier)和分辨率乘子(Resolution Multiplier)进一步压缩模型 +3. 适用于移动设备和嵌入式设备的轻量级CNN架构 +''' + +import torch +import torch.nn as nn + + +class Block(nn.Module): + '''深度可分离卷积块 (Depthwise Separable Convolution Block) + + 包含: + 1. 深度卷积(Depthwise Conv): 对每个通道单独进行空间卷积 + 2. 逐点卷积(Pointwise Conv): 1x1卷积实现通道混合 + + Args: + in_channels: 输入通道数 + out_channels: 输出通道数 + stride: 卷积步长 + ''' + def __init__(self, in_channels, out_channels, stride=1): + super(Block, self).__init__() + + # 深度卷积 - 每个通道单独进行3x3卷积 + self.conv1 = nn.Conv2d( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + stride=stride, + padding=1, + groups=in_channels, # groups=in_channels 即为深度可分离卷积 + bias=False + ) + self.bn1 = nn.BatchNorm2d(in_channels) + self.relu1 = nn.ReLU(inplace=True) + + # 逐点卷积 - 1x1卷积用于通道混合 + self.conv2 = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + bias=False + ) + self.bn2 = nn.BatchNorm2d(out_channels) + self.relu2 = nn.ReLU(inplace=True) + + def forward(self, x): + # 深度卷积 + x = self.conv1(x) + x = self.bn1(x) + x = self.relu1(x) + + # 逐点卷积 + x = self.conv2(x) + x = self.bn2(x) + x = self.relu2(x) + return x + + +class MobileNet(nn.Module): + '''MobileNet v1网络 + + Args: + num_classes: 分类数量 + alpha: 宽度乘子,用于控制网络宽度(默认1.0) + beta: 分辨率乘子,用于控制输入分辨率(默认1.0) + init_weights: 是否初始化权重 + ''' + # 网络配置: (输出通道数, 步长),步长默认为1 + cfg = [64, (128,2), 128, (256,2), 256, (512,2), + 512, 512, 512, 512, 512, (1024,2), 1024] + + def __init__(self, num_classes=10, alpha=1.0, beta=1.0, init_weights=True): + super(MobileNet, self).__init__() + + # 第一层标准卷积 + self.conv1 = nn.Sequential( + nn.Conv2d(3, 32, kernel_size=3, stride=1, bias=False), + nn.BatchNorm2d(32), + nn.ReLU(inplace=True) + ) + + # 深度可分离卷积层 + self.layers = self._make_layers(in_channels=32) + + # 全局平均池化和分类器 + self.avg = nn.AdaptiveAvgPool2d(1) # 自适应平均池化,输出大小为1x1 + self.linear = nn.Linear(1024, num_classes) + + # 初始化权重 + if init_weights: + self._initialize_weights() + + def _make_layers(self, in_channels): + '''构建深度可分离卷积层 + + Args: + in_channels: 输入通道数 + ''' + layers = [] + for x in self.cfg: + out_channels = x if isinstance(x, int) else x[0] + stride = 1 if isinstance(x, int) else x[1] + layers.append(Block(in_channels, out_channels, stride)) + in_channels = out_channels + return nn.Sequential(*layers) + + def forward(self, x): + # 标准卷积 + x = self.conv1(x) + + # 深度可分离卷积层 + x = self.layers(x) + + # 全局平均池化和分类器 + x = self.avg(x) + x = x.view(x.size(0), -1) + x = self.linear(x) + return x + + def _initialize_weights(self): + '''初始化模型权重''' + for m in self.modules(): + if isinstance(m, nn.Conv2d): + # 使用kaiming初始化卷积层 + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + # 初始化BN层 + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + # 初始化全连接层 + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + +def test(): + """测试函数""" + net = MobileNet() + x = torch.randn(2, 3, 32, 32) + y = net(x) + print(y.size()) + + # 打印模型结构 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (2, 3, 32, 32)) + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/MobileNetv1/code/train.py b/Image/MobileNetv1/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..827a2a0940b517d9e013dfb26e784b4584537122 --- /dev/null +++ b/Image/MobileNetv1/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import MobileNet + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = MobileNet() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='mobilenetv1' + ) + +if __name__ == '__main__': + main() diff --git a/Image/MobileNetv1/dataset/.gitkeep b/Image/MobileNetv1/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv1/model/.gitkeep b/Image/MobileNetv1/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv2/code/model.py b/Image/MobileNetv2/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c92a0f20828c73e72ff8d685e799d719a1da11a6 --- /dev/null +++ b/Image/MobileNetv2/code/model.py @@ -0,0 +1,176 @@ +''' +MobileNetV2 in PyTorch. + +论文: "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" +参考: https://arxiv.org/abs/1801.04381 + +主要特点: +1. 引入倒残差结构(Inverted Residual),先升维后降维 +2. 使用线性瓶颈(Linear Bottlenecks),去除最后一个ReLU保留特征 +3. 使用ReLU6作为激活函数,提高在低精度计算下的鲁棒性 +4. 残差连接时使用加法而不是拼接,减少内存占用 +''' + +import torch +import torch.nn as nn + + +class Block(nn.Module): + '''倒残差块 (Inverted Residual Block) + + 结构: expand(1x1) -> depthwise(3x3) -> project(1x1) + 特点: + 1. 使用1x1卷积先升维再降维(与ResNet相反) + 2. 使用深度可分离卷积减少参数量 + 3. 使用shortcut连接(当stride=1且输入输出通道数相同时) + + Args: + in_channels: 输入通道数 + out_channels: 输出通道数 + expansion: 扩展因子,控制中间层的通道数 + stride: 步长,控制特征图大小 + ''' + def __init__(self, in_channels, out_channels, expansion, stride): + super(Block, self).__init__() + self.stride = stride + channels = expansion * in_channels # 扩展通道数 + + # 1x1卷积升维 + self.conv1 = nn.Conv2d( + in_channels, channels, + kernel_size=1, stride=1, padding=0, bias=False + ) + self.bn1 = nn.BatchNorm2d(channels) + + # 3x3深度可分离卷积 + self.conv2 = nn.Conv2d( + channels, channels, + kernel_size=3, stride=stride, padding=1, + groups=channels, bias=False # groups=channels即为深度可分离卷积 + ) + self.bn2 = nn.BatchNorm2d(channels) + + # 1x1卷积降维(线性瓶颈,不使用激活函数) + self.conv3 = nn.Conv2d( + channels, out_channels, + kernel_size=1, stride=1, padding=0, bias=False + ) + self.bn3 = nn.BatchNorm2d(out_channels) + + # shortcut连接 + self.shortcut = nn.Sequential() + if stride == 1 and in_channels != out_channels: + self.shortcut = nn.Sequential( + nn.Conv2d( + in_channels, out_channels, + kernel_size=1, stride=1, padding=0, bias=False + ), + nn.BatchNorm2d(out_channels) + ) + + self.relu6 = nn.ReLU6(inplace=True) + + def forward(self, x): + # 主分支 + out = self.relu6(self.bn1(self.conv1(x))) # 升维 + out = self.relu6(self.bn2(self.conv2(out))) # 深度卷积 + out = self.bn3(self.conv3(out)) # 降维(线性瓶颈) + + # shortcut连接(仅在stride=1时) + out = out + self.shortcut(x) if self.stride == 1 else out + return out + + +class MobileNetV2(nn.Module): + '''MobileNetV2网络 + + Args: + num_classes: 分类数量 + + 网络配置: + cfg = [(expansion, out_channels, num_blocks, stride), ...] + - expansion: 扩展因子 + - out_channels: 输出通道数 + - num_blocks: 块的数量 + - stride: 第一个块的步长 + ''' + # 网络结构配置 + cfg = [ + # (expansion, out_channels, num_blocks, stride) + (1, 16, 1, 1), # conv1 + (6, 24, 2, 1), # conv2,注意:原论文stride=2,这里改为1以适应CIFAR10 + (6, 32, 3, 2), # conv3 + (6, 64, 4, 2), # conv4 + (6, 96, 3, 1), # conv5 + (6, 160, 3, 2), # conv6 + (6, 320, 1, 1), # conv7 + ] + + def __init__(self, num_classes=10): + super(MobileNetV2, self).__init__() + + # 第一层卷积(注意:原论文stride=2,这里改为1以适应CIFAR10) + self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(32) + + # 主干网络 + self.layers = self._make_layers(in_channels=32) + + # 最后的1x1卷积 + self.conv2 = nn.Conv2d(320, 1280, kernel_size=1, stride=1, padding=0, bias=False) + self.bn2 = nn.BatchNorm2d(1280) + + # 分类器 + self.avgpool = nn.AdaptiveAvgPool2d(1) # 全局平均池化 + self.linear = nn.Linear(1280, num_classes) + self.relu6 = nn.ReLU6(inplace=True) + + def _make_layers(self, in_channels): + '''构建网络层 + + Args: + in_channels: 输入通道数 + ''' + layers = [] + for expansion, out_channels, num_blocks, stride in self.cfg: + # 对于每个配置,第一个block使用指定的stride,后续blocks使用stride=1 + strides = [stride] + [1]*(num_blocks-1) + for stride in strides: + layers.append( + Block(in_channels, out_channels, expansion, stride) + ) + in_channels = out_channels + return nn.Sequential(*layers) + + def forward(self, x): + # 第一层卷积 + out = self.relu6(self.bn1(self.conv1(x))) + + # 主干网络 + out = self.layers(out) + + # 最后的1x1卷积 + out = self.relu6(self.bn2(self.conv2(out))) + + # 分类器 + out = self.avgpool(out) + out = out.view(out.size(0), -1) + out = self.linear(out) + return out + + +def test(): + """测试函数""" + net = MobileNetV2() + x = torch.randn(2, 3, 32, 32) + y = net(x) + print(y.size()) + + # 打印模型结构 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (2, 3, 32, 32)) + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/MobileNetv2/code/train.py b/Image/MobileNetv2/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f757f97dbdf145cf76ec4852c47d95ab2ab6b9 --- /dev/null +++ b/Image/MobileNetv2/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import MobileNetV2 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = MobileNetV2() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='mobilenetv2' + ) + +if __name__ == '__main__': + main() diff --git a/Image/MobileNetv2/dataset/.gitkeep b/Image/MobileNetv2/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv2/model/.gitkeep b/Image/MobileNetv2/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv3/code/model.py b/Image/MobileNetv3/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..460b44d3788071260ba8844ebb8332eb4fb3f827 --- /dev/null +++ b/Image/MobileNetv3/code/model.py @@ -0,0 +1,252 @@ +''' +MobileNetV3 in PyTorch. + +论文: "Searching for MobileNetV3" +参考: https://arxiv.org/abs/1905.02244 + +主要特点: +1. 引入基于NAS的网络架构搜索 +2. 使用改进的SE注意力机块 +3. 使用h-swish激活函数 +4. 重新设计了网络的最后几层 +5. 提供了Large和Small两个版本 +''' + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def get_activation(name): + '''获取激活函数 + + Args: + name: 激活函数名称 ('relu' 或 'hardswish') + ''' + if name == 'relu': + return nn.ReLU(inplace=True) + elif name == 'hardswish': + return nn.Hardswish(inplace=True) + else: + raise NotImplementedError + + +class SEModule(nn.Module): + '''Squeeze-and-Excitation模块 + + 通过全局平均池化和两层全连接网络学习通道注意力权重 + + Args: + channel: 输入通道数 + reduction: 降维比例 + ''' + def __init__(self, channel, reduction=4): + super(SEModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Sequential( + nn.Linear(channel, channel // reduction, bias=False), + nn.ReLU(inplace=True), + nn.Linear(channel // reduction, channel, bias=False), + nn.Hardsigmoid(inplace=True) + ) + + def forward(self, x): + b, c, _, _ = x.size() + y = self.avg_pool(x).view(b, c) # squeeze + y = self.fc(y).view(b, c, 1, 1) # excitation + return x * y.expand_as(x) # scale + + +class Bottleneck(nn.Module): + '''MobileNetV3 Bottleneck + + 包含: + 1. Expansion layer (1x1 conv) + 2. Depthwise layer (3x3 or 5x5 depthwise conv) + 3. SE module (optional) + 4. Projection layer (1x1 conv) + + Args: + in_channels: 输入通道数 + exp_channels: 扩展层通道数 + out_channels: 输出通道数 + kernel_size: 深度卷积核大小 + stride: 步长 + use_SE: 是否使用SE模块 + activation: 激活函数类型 + use_residual: 是否使用残差连接 + ''' + def __init__(self, in_channels, exp_channels, out_channels, kernel_size, + stride, use_SE, activation, use_residual=True): + super(Bottleneck, self).__init__() + self.use_residual = use_residual and stride == 1 and in_channels == out_channels + padding = (kernel_size - 1) // 2 + + layers = [] + # Expansion layer + if exp_channels != in_channels: + layers.extend([ + nn.Conv2d(in_channels, exp_channels, 1, bias=False), + nn.BatchNorm2d(exp_channels), + get_activation(activation) + ]) + + # Depthwise conv + layers.extend([ + nn.Conv2d( + exp_channels, exp_channels, kernel_size, + stride, padding, groups=exp_channels, bias=False + ), + nn.BatchNorm2d(exp_channels), + get_activation(activation) + ]) + + # SE module + if use_SE: + layers.append(SEModule(exp_channels)) + + # Projection layer + layers.extend([ + nn.Conv2d(exp_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels) + ]) + + self.conv = nn.Sequential(*layers) + + def forward(self, x): + if self.use_residual: + return x + self.conv(x) + else: + return self.conv(x) + + +class MobileNetV3(nn.Module): + '''MobileNetV3网络 + + Args: + num_classes: 分类数量 + mode: 'large' 或 'small',选择网络版本 + ''' + def __init__(self, num_classes=10, mode='small'): + super(MobileNetV3, self).__init__() + + if mode == 'large': + # MobileNetV3-Large架构 + self.config = [ + # k, exp, out, SE, activation, stride + [3, 16, 16, False, 'relu', 1], + [3, 64, 24, False, 'relu', 2], + [3, 72, 24, False, 'relu', 1], + [5, 72, 40, True, 'relu', 2], + [5, 120, 40, True, 'relu', 1], + [5, 120, 40, True, 'relu', 1], + [3, 240, 80, False, 'hardswish', 2], + [3, 200, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 480, 112, True, 'hardswish', 1], + [3, 672, 112, True, 'hardswish', 1], + [5, 672, 160, True, 'hardswish', 2], + [5, 960, 160, True, 'hardswish', 1], + [5, 960, 160, True, 'hardswish', 1], + ] + init_conv_out = 16 + final_conv_out = 960 + else: + # MobileNetV3-Small架构 + self.config = [ + # k, exp, out, SE, activation, stride + [3, 16, 16, True, 'relu', 2], + [3, 72, 24, False, 'relu', 2], + [3, 88, 24, False, 'relu', 1], + [5, 96, 40, True, 'hardswish', 2], + [5, 240, 40, True, 'hardswish', 1], + [5, 240, 40, True, 'hardswish', 1], + [5, 120, 48, True, 'hardswish', 1], + [5, 144, 48, True, 'hardswish', 1], + [5, 288, 96, True, 'hardswish', 2], + [5, 576, 96, True, 'hardswish', 1], + [5, 576, 96, True, 'hardswish', 1], + ] + init_conv_out = 16 + final_conv_out = 576 + + # 第一层卷积 + self.conv_stem = nn.Sequential( + nn.Conv2d(3, init_conv_out, 3, 2, 1, bias=False), + nn.BatchNorm2d(init_conv_out), + get_activation('hardswish') + ) + + # 构建Bottleneck层 + features = [] + in_channels = init_conv_out + for k, exp, out, se, activation, stride in self.config: + features.append( + Bottleneck(in_channels, exp, out, k, stride, se, activation) + ) + in_channels = out + self.features = nn.Sequential(*features) + + # 最后的卷积层 + self.conv_head = nn.Sequential( + nn.Conv2d(in_channels, final_conv_out, 1, bias=False), + nn.BatchNorm2d(final_conv_out), + get_activation('hardswish') + ) + + # 分类器 + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Sequential( + nn.Linear(final_conv_out, num_classes) + ) + + # 初始化权重 + self._initialize_weights() + + def _initialize_weights(self): + '''初始化模型权重''' + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def forward(self, x): + x = self.conv_stem(x) + x = self.features(x) + x = self.conv_head(x) + x = self.avgpool(x) + x = x.view(x.size(0), -1) + x = self.classifier(x) + return x + + +def test(): + """测试函数""" + # 测试Large版本 + net_large = MobileNetV3(mode='large') + x = torch.randn(2, 3, 32, 32) + y = net_large(x) + print('Large output size:', y.size()) + + # 测试Small版本 + net_small = MobileNetV3(mode='small') + y = net_small(x) + print('Small output size:', y.size()) + + # 打印模型结构 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net_small = net_small.to(device) + summary(net_small, (2, 3, 32, 32)) + +if __name__ == '__main__': + test() diff --git a/Image/MobileNetv3/code/train.py b/Image/MobileNetv3/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad4591340554c4a74628b75ddbacba1799e6fb1 --- /dev/null +++ b/Image/MobileNetv3/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import MobileNetV3 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = MobileNetV3(num_classes=10, mode='small') # 使用small版本,适合CIFAR10 + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='mobilenetv3_small' + ) + +if __name__ == '__main__': + main() diff --git a/Image/MobileNetv3/dataset/.gitkeep b/Image/MobileNetv3/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/MobileNetv3/model/.gitkeep b/Image/MobileNetv3/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ResNet/code/model.py b/Image/ResNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e65e4fed1b8259436a3f4dcbc3ace8e6d738bf --- /dev/null +++ b/Image/ResNet/code/model.py @@ -0,0 +1,259 @@ +''' +ResNet in PyTorch. + +ResNet(深度残差网络)是由微软研究院的Kaiming He等人提出的深度神经网络架构。 +主要创新点是引入了残差学习的概念,通过跳跃连接解决了深层网络的退化问题。 + +主要特点: +1. 引入残差块(Residual Block),使用跳跃连接 +2. 使用Batch Normalization进行归一化 +3. 支持更深的网络结构(最深可达152层) +4. 在多个计算机视觉任务上取得了突破性进展 + +Reference: +[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun + Deep Residual Learning for Image Recognition. arXiv:1512.03385 +''' +import torch +import torch.nn as nn + +class BasicBlock(nn.Module): + """基础残差块 + + 用于ResNet18/34等浅层网络。结构为: + x -> Conv -> BN -> ReLU -> Conv -> BN -> (+) -> ReLU + |------------------------------------------| + + Args: + in_channels: 输入通道数 + out_channels: 输出通道数 + stride: 步长,用于下采样,默认为1 + + 注意:基础模块没有通道压缩,expansion=1 + """ + expansion = 1 + + def __init__(self, in_channels, out_channels, stride=1): + super(BasicBlock,self).__init__() + self.features = nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(True), + nn.Conv2d(out_channels,out_channels, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(out_channels) + ) + + # 如果输入输出维度不等,则使用1x1卷积层来改变维度 + self.shortcut = nn.Sequential() + if stride != 1 or in_channels != self.expansion * out_channels: + self.shortcut = nn.Sequential( + nn.Conv2d(in_channels, self.expansion * out_channels, kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(self.expansion * out_channels), + ) + + def forward(self, x): + out = self.features(x) + out += self.shortcut(x) + out = torch.relu(out) + return out + + +class Bottleneck(nn.Module): + """瓶颈残差块 + + 用于ResNet50/101/152等深层网络。结构为: + x -> 1x1Conv -> BN -> ReLU -> 3x3Conv -> BN -> ReLU -> 1x1Conv -> BN -> (+) -> ReLU + |-------------------------------------------------------------------| + + Args: + in_channels: 输入通道数 + zip_channels: 压缩后的通道数 + stride: 步长,用于下采样,默认为1 + + 注意:通过1x1卷积先压缩通道数,再还原,expansion=4 + """ + expansion = 4 + + def __init__(self, in_channels, zip_channels, stride=1): + super(Bottleneck, self).__init__() + out_channels = self.expansion * zip_channels + self.features = nn.Sequential( + # 1x1卷积压缩通道 + nn.Conv2d(in_channels, zip_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(zip_channels), + nn.ReLU(inplace=True), + # 3x3卷积提取特征 + nn.Conv2d(zip_channels, zip_channels, kernel_size=3, stride=stride, padding=1, bias=False), + nn.BatchNorm2d(zip_channels), + nn.ReLU(inplace=True), + # 1x1卷积还原通道 + nn.Conv2d(zip_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels) + ) + + self.shortcut = nn.Sequential() + if stride != 1 or in_channels != out_channels: + self.shortcut = nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(out_channels) + ) + + def forward(self, x): + out = self.features(x) + out += self.shortcut(x) + out = torch.relu(out) + return out + +class ResNet(nn.Module): + """ResNet模型 + + 网络结构: + 1. 一个卷积层用于特征提取 + 2. 四个残差层,每层包含多个残差块 + 3. 平均池化和全连接层进行分类 + + 对于CIFAR10,特征图大小变化为: + (32,32,3) -> [Conv] -> (32,32,64) -> [Layer1] -> (32,32,64) -> [Layer2] + -> (16,16,128) -> [Layer3] -> (8,8,256) -> [Layer4] -> (4,4,512) -> [AvgPool] + -> (1,1,512) -> [FC] -> (num_classes) + + Args: + block: 残差块类型(BasicBlock或Bottleneck) + num_blocks: 每层残差块数量的列表 + num_classes: 分类数量,默认为10 + verbose: 是否打印中间特征图大小 + init_weights: 是否初始化权重 + """ + def __init__(self, block, num_blocks, num_classes=10, verbose=False, init_weights=True): + super(ResNet, self).__init__() + self.verbose = verbose + self.in_channels = 64 + + # 第一层卷积 + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True) + ) + + # 四个残差层 + self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) + self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) + self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) + self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) + + # 分类层 + self.avg_pool = nn.AvgPool2d(kernel_size=4) + self.classifier = nn.Linear(512 * block.expansion, num_classes) + + if init_weights: + self._initialize_weights() + + def _make_layer(self, block, out_channels, num_blocks, stride): + """构建残差层 + + Args: + block: 残差块类型 + out_channels: 输出通道数 + num_blocks: 残差块数量 + stride: 第一个残差块的步长(用于下采样) + + Returns: + nn.Sequential: 残差层 + """ + strides = [stride] + [1] * (num_blocks - 1) + layers = [] + for stride in strides: + layers.append(block(self.in_channels, out_channels, stride)) + self.in_channels = out_channels * block.expansion + return nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x: 输入张量,[N,3,32,32] + + Returns: + out: 输出张量,[N,num_classes] + """ + out = self.features(x) + if self.verbose: + print('block 1 output: {}'.format(out.shape)) + + out = self.layer1(out) + if self.verbose: + print('block 2 output: {}'.format(out.shape)) + + out = self.layer2(out) + if self.verbose: + print('block 3 output: {}'.format(out.shape)) + + out = self.layer3(out) + if self.verbose: + print('block 4 output: {}'.format(out.shape)) + + out = self.layer4(out) + if self.verbose: + print('block 5 output: {}'.format(out.shape)) + + out = self.avg_pool(out) + out = out.view(out.size(0), -1) + out = self.classifier(out) + return out + + def _initialize_weights(self): + """初始化模型权重 + + 采用kaiming初始化方法: + - 卷积层权重采用kaiming_normal_初始化 + - BN层参数采用常数初始化 + - 线性层采用正态分布初始化 + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + 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) + nn.init.constant_(m.bias, 0) + +def ResNet18(verbose=False): + """ResNet-18模型""" + return ResNet(BasicBlock, [2,2,2,2], verbose=verbose) + +def ResNet34(verbose=False): + """ResNet-34模型""" + return ResNet(BasicBlock, [3,4,6,3], verbose=verbose) + +def ResNet50(verbose=False): + """ResNet-50模型""" + return ResNet(Bottleneck, [3,4,6,3], verbose=verbose) + +def ResNet101(verbose=False): + """ResNet-101模型""" + return ResNet(Bottleneck, [3,4,23,3], verbose=verbose) + +def ResNet152(verbose=False): + """ResNet-152模型""" + return ResNet(Bottleneck, [3,8,36,3], verbose=verbose) + +def test(): + """测试函数""" + net = ResNet34() + x = torch.randn(2,3,32,32) + y = net(x) + print('Output shape:', y.size()) + + # 打印模型结构 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net,(2,3,32,32)) + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/ResNet/code/train.py b/Image/ResNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..07fe5fd4ed01473f40c66e95d14995df326d67d2 --- /dev/null +++ b/Image/ResNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import ResNet18 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = ResNet18() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='resnet18' + ) + +if __name__ == '__main__': + main() diff --git a/Image/ResNet/dataset/.gitkeep b/Image/ResNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ResNet/model/.gitkeep b/Image/ResNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/SENet/code/model.py b/Image/SENet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..88899e5bcc30f78fc61076a5667acd5dc680d564 --- /dev/null +++ b/Image/SENet/code/model.py @@ -0,0 +1,251 @@ +''' +SENet (Squeeze-and-Excitation Networks) in PyTorch. + +SENet通过引入SE模块来自适应地重新校准通道特征响应。SE模块可以集成到现有的网络架构中, +通过显式建模通道之间的相互依赖关系,自适应地重新校准通道特征响应。 + +主要特点: +1. 引入Squeeze-and-Excitation(SE)模块,增强特征的表示能力 +2. SE模块包含squeeze操作(全局平均池化)和excitation操作(两个FC层) +3. 通过attention机制来增强重要通道的权重,抑制不重要通道 +4. 几乎可以嵌入到任何现有的网络结构中 + +Reference: +[1] Jie Hu, Li Shen, Samuel Albanie, Gang Sun, Enhua Wu + Squeeze-and-Excitation Networks. CVPR 2018. +''' +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class BasicBlock(nn.Module): + """基础残差块+SE模块 + + 结构: + x -> Conv -> BN -> ReLU -> Conv -> BN -> SE -> (+) -> ReLU + |------------------------------------------| + + Args: + in_channels: 输入通道数 + channels: 输出通道数 + stride: 步长,用于下采样,默认为1 + """ + def __init__(self, in_channels, channels, stride=1): + super(BasicBlock, self).__init__() + self.conv1 = nn.Conv2d(in_channels, channels, kernel_size=3, stride=stride, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(channels) + self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(channels) + + # 残差连接 + self.shortcut = nn.Sequential() + if stride != 1 or in_channels != channels: + self.shortcut = nn.Sequential( + nn.Conv2d(in_channels, channels, kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(channels) + ) + + # SE模块 + self.squeeze = nn.AdaptiveAvgPool2d(1) # 全局平均池化 + self.excitation = nn.Sequential( + nn.Conv2d(channels, channels//16, kernel_size=1), # 通道降维 + nn.ReLU(inplace=True), + nn.Conv2d(channels//16, channels, kernel_size=1), # 通道升维 + nn.Sigmoid() # 归一化到[0,1] + ) + + def forward(self, x): + # 主分支 + out = F.relu(self.bn1(self.conv1(x))) + out = self.bn2(self.conv2(out)) + + # SE模块 + w = self.squeeze(out) # Squeeze + w = self.excitation(w) # Excitation + out = out * w # 特征重标定 + + # 残差连接 + out += self.shortcut(x) + out = F.relu(out) + return out + + +class PreActBlock(nn.Module): + """Pre-activation版本的基础块+SE模块 + + 结构: + x -> BN -> ReLU -> Conv -> BN -> ReLU -> Conv -> SE -> (+) + |-------------------------------------------| + + Args: + in_channels: 输入通道数 + channels: 输出通道数 + stride: 步长,用于下采样,默认为1 + """ + def __init__(self, in_channels, channels, stride=1): + super(PreActBlock, self).__init__() + self.bn1 = nn.BatchNorm2d(in_channels) + self.conv1 = nn.Conv2d(in_channels, channels, kernel_size=3, stride=stride, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(channels) + self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1, bias=False) + + # 残差连接 + if stride != 1 or in_channels != channels: + self.shortcut = nn.Sequential( + nn.Conv2d(in_channels, channels, kernel_size=1, stride=stride, bias=False) + ) + + # SE模块 + self.squeeze = nn.AdaptiveAvgPool2d(1) + self.excitation = nn.Sequential( + nn.Conv2d(channels, channels//16, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(channels//16, channels, kernel_size=1), + nn.Sigmoid() + ) + + def forward(self, x): + # Pre-activation + out = F.relu(self.bn1(x)) + shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x + + # 主分支 + out = self.conv1(out) + out = self.conv2(F.relu(self.bn2(out))) + + # SE模块 + w = self.squeeze(out) + w = self.excitation(w) + out = out * w + + # 残差连接 + out += shortcut + return out + + +class SENet(nn.Module): + """SENet模型 + + 网络结构: + 1. 一个卷积层进行特征提取 + 2. 四个残差层,每层包含多个带SE模块的残差块 + 3. 平均池化和全连接层进行分类 + + Args: + block: 残差块类型(BasicBlock或PreActBlock) + num_blocks: 每层残差块数量的列表 + num_classes: 分类数量,默认为10 + """ + def __init__(self, block, num_blocks, num_classes=10): + super(SENet, self).__init__() + self.in_channels = 64 + + # 第一层卷积 + self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(64) + + # 四个残差层 + self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) + self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) + self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) + self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) + + # 分类层 + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Linear(512, num_classes) + + # 初始化权重 + self._initialize_weights() + + def _make_layer(self, block, channels, num_blocks, stride): + """构建残差层 + + Args: + block: 残差块类型 + channels: 输出通道数 + num_blocks: 残差块数量 + stride: 第一个残差块的步长(用于下采样) + + Returns: + nn.Sequential: 残差层 + """ + strides = [stride] + [1]*(num_blocks-1) + layers = [] + for stride in strides: + layers.append(block(self.in_channels, channels, stride)) + self.in_channels = channels + return nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x: 输入张量,[N,3,32,32] + + Returns: + out: 输出张量,[N,num_classes] + """ + # 特征提取 + out = F.relu(self.bn1(self.conv1(x))) + + # 残差层 + out = self.layer1(out) + out = self.layer2(out) + out = self.layer3(out) + out = self.layer4(out) + + # 分类 + out = self.avg_pool(out) + out = out.view(out.size(0), -1) + out = self.classifier(out) + return out + + def _initialize_weights(self): + """初始化模型权重 + + 采用kaiming初始化方法: + - 卷积层权重采用kaiming_normal_初始化 + - BN层参数采用常数初始化 + - 线性层采用正态分布初始化 + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + 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) + nn.init.constant_(m.bias, 0) + + +def SENet18(): + """SENet-18模型""" + return SENet(PreActBlock, [2,2,2,2]) + + +def test(): + """测试函数""" + # 创建模型 + net = SENet18() + print('Model Structure:') + print(net) + + # 测试前向传播 + x = torch.randn(1,3,32,32) + y = net(x) + print('\nInput Shape:', x.shape) + print('Output Shape:', y.shape) + + # 打印模型信息 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (1,3,32,32)) + + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/SENet/code/train.py b/Image/SENet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..90d81b2333c4916595e86f28fa246a6bd884081b --- /dev/null +++ b/Image/SENet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import SENet18 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = SENet18() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='senet18' + ) + +if __name__ == '__main__': + main() diff --git a/Image/SENet/dataset/.gitkeep b/Image/SENet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/SENet/model/.gitkeep b/Image/SENet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ShuffleNet/code/model.py b/Image/ShuffleNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb599570de101d901f3b6065eee4b30e146def3 --- /dev/null +++ b/Image/ShuffleNet/code/model.py @@ -0,0 +1,263 @@ +''' +ShuffleNet in PyTorch. + +ShuffleNet是一个专门为移动设备设计的高效卷积神经网络。其主要创新点在于使用了两个新操作: +1. 逐点组卷积(pointwise group convolution) +2. 通道重排(channel shuffle) +这两个操作大大降低了计算复杂度,同时保持了良好的准确率。 + +主要特点: +1. 使用组卷积减少参数量和计算量 +2. 使用通道重排操作使不同组之间的信息可以流通 +3. 使用深度可分离卷积进一步降低计算复杂度 +4. 设计了多个计算复杂度版本以适应不同的设备 + +Reference: +[1] Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun + ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices. CVPR 2018. +''' +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ShuffleBlock(nn.Module): + """通道重排模块 + + 通过重新排列通道的顺序来实现不同组之间的信息交流。 + + Args: + groups (int): 分组数量 + """ + def __init__(self, groups): + super(ShuffleBlock, self).__init__() + self.groups = groups + + def forward(self, x): + """通道重排的前向传播 + + 步骤: + 1. [N,C,H,W] -> [N,g,C/g,H,W] # 重塑为g组 + 2. [N,g,C/g,H,W] -> [N,C/g,g,H,W] # 转置g维度 + 3. [N,C/g,g,H,W] -> [N,C,H,W] # 重塑回原始形状 + + Args: + x: 输入张量,[N,C,H,W] + + Returns: + out: 通道重排后的张量,[N,C,H,W] + """ + N, C, H, W = x.size() + g = self.groups + return x.view(N,g,C//g,H,W).permute(0,2,1,3,4).reshape(N,C,H,W) + + +class Bottleneck(nn.Module): + """ShuffleNet的基本模块 + + 结构: + x -> 1x1 GConv -> BN -> Shuffle -> 3x3 DWConv -> BN -> 1x1 GConv -> BN -> (+) -> ReLU + |---------------------| + + Args: + in_channels (int): 输入通道数 + out_channels (int): 输出通道数 + stride (int): 步长,用于下采样 + groups (int): 组卷积的分组数 + """ + def __init__(self, in_channels, out_channels, stride, groups): + super(Bottleneck, self).__init__() + self.stride = stride + + # 确定中间通道数和分组数 + mid_channels = out_channels // 4 + g = 1 if in_channels == 24 else groups + + # 第一个1x1组卷积 + self.conv1 = nn.Conv2d(in_channels, mid_channels, + kernel_size=1, groups=g, bias=False) + self.bn1 = nn.BatchNorm2d(mid_channels) + self.shuffle1 = ShuffleBlock(groups=g) + + # 3x3深度可分离卷积 + self.conv2 = nn.Conv2d(mid_channels, mid_channels, + kernel_size=3, stride=stride, padding=1, + groups=mid_channels, bias=False) + self.bn2 = nn.BatchNorm2d(mid_channels) + + # 第二个1x1组卷积 + self.conv3 = nn.Conv2d(mid_channels, out_channels, + kernel_size=1, groups=groups, bias=False) + self.bn3 = nn.BatchNorm2d(out_channels) + + # 残差连接 + self.shortcut = nn.Sequential() + if stride == 2: + self.shortcut = nn.Sequential( + nn.AvgPool2d(3, stride=2, padding=1) + ) + + def forward(self, x): + # 主分支 + out = F.relu(self.bn1(self.conv1(x))) + out = self.shuffle1(out) + out = F.relu(self.bn2(self.conv2(out))) + out = self.bn3(self.conv3(out)) + + # 残差连接 + res = self.shortcut(x) + + # 如果是下采样层,拼接残差;否则相加 + out = F.relu(torch.cat([out, res], 1)) if self.stride == 2 else F.relu(out + res) + return out + + +class ShuffleNet(nn.Module): + """ShuffleNet模型 + + 网络结构: + 1. 一个卷积层进行特征提取 + 2. 三个阶段,每个阶段包含多个带重排的残差块 + 3. 平均池化和全连接层进行分类 + + Args: + cfg (dict): 配置字典,包含: + - out_channels (list): 每个阶段的输出通道数 + - num_blocks (list): 每个阶段的块数 + - groups (int): 组卷积的分组数 + """ + def __init__(self, cfg): + super(ShuffleNet, self).__init__() + out_channels = cfg['out_channels'] + num_blocks = cfg['num_blocks'] + groups = cfg['groups'] + + # 第一层卷积 + self.conv1 = nn.Conv2d(3, 24, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(24) + self.in_channels = 24 + + # 三个阶段 + self.layer1 = self._make_layer(out_channels[0], num_blocks[0], groups) + self.layer2 = self._make_layer(out_channels[1], num_blocks[1], groups) + self.layer3 = self._make_layer(out_channels[2], num_blocks[2], groups) + + # 分类层 + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Linear(out_channels[2], 10) + + # 初始化权重 + self._initialize_weights() + + def _make_layer(self, out_channels, num_blocks, groups): + """构建ShuffleNet的一个阶段 + + Args: + out_channels (int): 输出通道数 + num_blocks (int): 块的数量 + groups (int): 分组数 + + Returns: + nn.Sequential: 一个阶段的层序列 + """ + layers = [] + for i in range(num_blocks): + stride = 2 if i == 0 else 1 + cat_channels = self.in_channels if i == 0 else 0 + layers.append( + Bottleneck( + self.in_channels, + out_channels - cat_channels, + stride=stride, + groups=groups + ) + ) + self.in_channels = out_channels + return nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x: 输入张量,[N,3,32,32] + + Returns: + out: 输出张量,[N,num_classes] + """ + # 特征提取 + out = F.relu(self.bn1(self.conv1(x))) + + # 三个阶段 + out = self.layer1(out) + out = self.layer2(out) + out = self.layer3(out) + + # 分类 + out = self.avg_pool(out) + out = out.view(out.size(0), -1) + out = self.classifier(out) + return out + + def _initialize_weights(self): + """初始化模型权重 + + 采用kaiming初始化方法: + - 卷积层权重采用kaiming_normal_初始化 + - BN层参数采用常数初始化 + - 线性层采用正态分布初始化 + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + 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) + nn.init.constant_(m.bias, 0) + + +def ShuffleNetG2(): + """返回groups=2的ShuffleNet模型""" + cfg = { + 'out_channels': [200,400,800], + 'num_blocks': [4,8,4], + 'groups': 2 + } + return ShuffleNet(cfg) + + +def ShuffleNetG3(): + """返回groups=3的ShuffleNet模型""" + cfg = { + 'out_channels': [240,480,960], + 'num_blocks': [4,8,4], + 'groups': 3 + } + return ShuffleNet(cfg) + + +def test(): + """测试函数""" + # 创建模型 + net = ShuffleNetG2() + print('Model Structure:') + print(net) + + # 测试前向传播 + x = torch.randn(1,3,32,32) + y = net(x) + print('\nInput Shape:', x.shape) + print('Output Shape:', y.shape) + + # 打印模型信息 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (1,3,32,32)) + + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/ShuffleNet/code/train.py b/Image/ShuffleNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..ea3b75657e744cd4c67ccabc6de44223f7d7fbf6 --- /dev/null +++ b/Image/ShuffleNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import ShuffleNet + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = ShuffleNet() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='shufflenet' + ) + +if __name__ == '__main__': + main() diff --git a/Image/ShuffleNet/dataset/.gitkeep b/Image/ShuffleNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ShuffleNet/model/.gitkeep b/Image/ShuffleNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ShuffleNetv2/code/model.py b/Image/ShuffleNetv2/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ca097bcd85c9fba957263f59fa9100c22c5e24fb --- /dev/null +++ b/Image/ShuffleNetv2/code/model.py @@ -0,0 +1,345 @@ +''' +ShuffleNetV2 in PyTorch. + +ShuffleNetV2是ShuffleNet的改进版本,通过实验总结出了四个高效网络设计的实用准则: +1. 输入输出通道数相等时计算量最小 +2. 过度使用组卷积会增加MAC(内存访问代价) +3. 网络碎片化会降低并行度 +4. Element-wise操作不可忽视 + +主要改进: +1. 通道分离(Channel Split)替代组卷积 +2. 重新设计了基本单元,使输入输出通道数相等 +3. 每个阶段使用不同的通道数配置 +4. 简化了下采样模块的设计 + +Reference: +[1] Ningning Ma, Xiangyu Zhang, Hai-Tao Zheng, Jian Sun + ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design. ECCV 2018. +''' +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ShuffleBlock(nn.Module): + """通道重排模块 + + 通过重新排列通道的顺序来实现不同特征的信息交流。 + + Args: + groups (int): 分组数量,默认为2 + """ + def __init__(self, groups=2): + super(ShuffleBlock, self).__init__() + self.groups = groups + + def forward(self, x): + """通道重排的前向传播 + + 步骤: + 1. [N,C,H,W] -> [N,g,C/g,H,W] # 重塑为g组 + 2. [N,g,C/g,H,W] -> [N,C/g,g,H,W] # 转置g维度 + 3. [N,C/g,g,H,W] -> [N,C,H,W] # 重塑回原始形状 + + Args: + x: 输入张量,[N,C,H,W] + + Returns: + out: 通道重排后的张量,[N,C,H,W] + """ + N, C, H, W = x.size() + g = self.groups + return x.view(N, g, C//g, H, W).permute(0, 2, 1, 3, 4).reshape(N, C, H, W) + + +class SplitBlock(nn.Module): + """通道分离模块 + + 将输入特征图按比例分成两部分。 + + Args: + ratio (float): 分离比例,默认为0.5 + """ + def __init__(self, ratio): + super(SplitBlock, self).__init__() + self.ratio = ratio + + def forward(self, x): + """通道分离的前向传播 + + Args: + x: 输入张量,[N,C,H,W] + + Returns: + tuple: 分离后的两个张量,[N,C1,H,W]和[N,C2,H,W] + """ + c = int(x.size(1) * self.ratio) + return x[:, :c, :, :], x[:, c:, :, :] + + +class BasicBlock(nn.Module): + """ShuffleNetV2的基本模块 + + 结构: + x -------|-----------------| + | | | + | 1x1 Conv | + | 3x3 DWConv | + | 1x1 Conv | + | | + |------------------Concat + | + Channel Shuffle + + Args: + in_channels (int): 输入通道数 + split_ratio (float): 通道分离比例,默认为0.5 + """ + def __init__(self, in_channels, split_ratio=0.5): + super(BasicBlock, self).__init__() + self.split = SplitBlock(split_ratio) + in_channels = int(in_channels * split_ratio) + + # 主分支 + self.conv1 = nn.Conv2d(in_channels, in_channels, + kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(in_channels) + + self.conv2 = nn.Conv2d(in_channels, in_channels, + kernel_size=3, stride=1, padding=1, + groups=in_channels, bias=False) + self.bn2 = nn.BatchNorm2d(in_channels) + + self.conv3 = nn.Conv2d(in_channels, in_channels, + kernel_size=1, bias=False) + self.bn3 = nn.BatchNorm2d(in_channels) + + self.shuffle = ShuffleBlock() + + def forward(self, x): + # 通道分离 + x1, x2 = self.split(x) + + # 主分支 + out = F.relu(self.bn1(self.conv1(x2))) + out = self.bn2(self.conv2(out)) + out = F.relu(self.bn3(self.conv3(out))) + + # 拼接并重排 + out = torch.cat([x1, out], 1) + out = self.shuffle(out) + return out + + +class DownBlock(nn.Module): + """下采样模块 + + 结构: + 3x3 DWConv(s=2) 1x1 Conv + x -----> 1x1 Conv 3x3 DWConv(s=2) + 1x1 Conv + | + Concat + | + Channel Shuffle + + Args: + in_channels (int): 输入通道数 + out_channels (int): 输出通道数 + """ + def __init__(self, in_channels, out_channels): + super(DownBlock, self).__init__() + mid_channels = out_channels // 2 + + # 左分支 + self.branch1 = nn.Sequential( + # 3x3深度可分离卷积,步长为2 + nn.Conv2d(in_channels, in_channels, + kernel_size=3, stride=2, padding=1, + groups=in_channels, bias=False), + nn.BatchNorm2d(in_channels), + # 1x1卷积 + nn.Conv2d(in_channels, mid_channels, + kernel_size=1, bias=False), + nn.BatchNorm2d(mid_channels) + ) + + # 右分支 + self.branch2 = nn.Sequential( + # 1x1卷积 + nn.Conv2d(in_channels, mid_channels, + kernel_size=1, bias=False), + nn.BatchNorm2d(mid_channels), + # 3x3深度可分离卷积,步长为2 + nn.Conv2d(mid_channels, mid_channels, + kernel_size=3, stride=2, padding=1, + groups=mid_channels, bias=False), + nn.BatchNorm2d(mid_channels), + # 1x1卷积 + nn.Conv2d(mid_channels, mid_channels, + kernel_size=1, bias=False), + nn.BatchNorm2d(mid_channels) + ) + + self.shuffle = ShuffleBlock() + + def forward(self, x): + # 左分支 + out1 = self.branch1(x) + + # 右分支 + out2 = self.branch2(x) + + # 拼接并重排 + out = torch.cat([out1, out2], 1) + out = self.shuffle(out) + return out + + +class ShuffleNetV2(nn.Module): + """ShuffleNetV2模型 + + 网络结构: + 1. 一个卷积层进行特征提取 + 2. 三个阶段,每个阶段包含多个基本块和一个下采样块 + 3. 最后一个卷积层 + 4. 平均池化和全连接层进行分类 + + Args: + net_size (float): 网络大小系数,可选0.5/1.0/1.5/2.0 + """ + def __init__(self, net_size): + super(ShuffleNetV2, self).__init__() + out_channels = configs[net_size]['out_channels'] + num_blocks = configs[net_size]['num_blocks'] + + # 第一层卷积 + self.conv1 = nn.Conv2d(3, 24, kernel_size=3, + stride=1, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(24) + self.in_channels = 24 + + # 三个阶段 + self.layer1 = self._make_layer(out_channels[0], num_blocks[0]) + self.layer2 = self._make_layer(out_channels[1], num_blocks[1]) + self.layer3 = self._make_layer(out_channels[2], num_blocks[2]) + + # 最后的1x1卷积 + self.conv2 = nn.Conv2d(out_channels[2], out_channels[3], + kernel_size=1, stride=1, padding=0, bias=False) + self.bn2 = nn.BatchNorm2d(out_channels[3]) + + # 分类层 + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Linear(out_channels[3], 10) + + # 初始化权重 + self._initialize_weights() + + def _make_layer(self, out_channels, num_blocks): + """构建一个阶段 + + Args: + out_channels (int): 输出通道数 + num_blocks (int): 基本块的数量 + + Returns: + nn.Sequential: 一个阶段的层序列 + """ + layers = [DownBlock(self.in_channels, out_channels)] + for i in range(num_blocks): + layers.append(BasicBlock(out_channels)) + self.in_channels = out_channels + return nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x: 输入张量,[N,3,32,32] + + Returns: + out: 输出张量,[N,num_classes] + """ + # 特征提取 + out = F.relu(self.bn1(self.conv1(x))) + + # 三个阶段 + out = self.layer1(out) + out = self.layer2(out) + out = self.layer3(out) + + # 最后的特征提取 + out = F.relu(self.bn2(self.conv2(out))) + + # 分类 + out = self.avg_pool(out) + out = out.view(out.size(0), -1) + out = self.classifier(out) + return out + + def _initialize_weights(self): + """初始化模型权重 + + 采用kaiming初始化方法: + - 卷积层权重采用kaiming_normal_初始化 + - BN层参数采用常数初始化 + - 线性层采用正态分布初始化 + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + 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) + nn.init.constant_(m.bias, 0) + + +# 不同大小的网络配置 +configs = { + 0.5: { + 'out_channels': (48, 96, 192, 1024), + 'num_blocks': (3, 7, 3) + }, + 1.0: { + 'out_channels': (116, 232, 464, 1024), + 'num_blocks': (3, 7, 3) + }, + 1.5: { + 'out_channels': (176, 352, 704, 1024), + 'num_blocks': (3, 7, 3) + }, + 2.0: { + 'out_channels': (224, 488, 976, 2048), + 'num_blocks': (3, 7, 3) + } +} + + +def test(): + """测试函数""" + # 创建模型 + net = ShuffleNetV2(net_size=0.5) + print('Model Structure:') + print(net) + + # 测试前向传播 + x = torch.randn(1,3,32,32) + y = net(x) + print('\nInput Shape:', x.shape) + print('Output Shape:', y.shape) + + # 打印模型信息 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (1,3,32,32)) + + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/ShuffleNetv2/code/train.py b/Image/ShuffleNetv2/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..678a4ca68a139e6805a8b0c032a64fbaea3c1e42 --- /dev/null +++ b/Image/ShuffleNetv2/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import ShuffleNetV2 + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = ShuffleNetV2(1) # width_mult=1.0 + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='shufflenetv2' + ) + +if __name__ == '__main__': + main() diff --git a/Image/ShuffleNetv2/dataset/.gitkeep b/Image/ShuffleNetv2/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ShuffleNetv2/model/.gitkeep b/Image/ShuffleNetv2/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/SwinTransformer/code/model.py b/Image/SwinTransformer/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c34d517f0e8e5ca70a4e901ff5527d6a766a2b78 --- /dev/null +++ b/Image/SwinTransformer/code/model.py @@ -0,0 +1,230 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +import numpy as np +from timm.models.layers import DropPath, trunc_normal_ + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + +def window_partition(x, window_size): + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + +def window_reverse(windows, window_size, H, W): + B = int(windows.shape[0] / (H * W / window_size / window_size)) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + +class WindowAttention(nn.Module): + def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.): + super().__init__() + self.dim = dim + self.window_size = window_size + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim ** -0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x): + B_, N, C = x.shape + qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + attn = self.softmax(attn) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class SwinTransformerBlock(nn.Module): + def __init__(self, dim, num_heads, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + + self.norm1 = norm_layer(dim) + self.attn = WindowAttention( + dim, window_size=window_size, num_heads=num_heads, + qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) + + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x): + H, W = self.H, self.W + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + + shortcut = x + x = self.norm1(x) + x = x.view(B, H, W, C) + + # pad feature maps to multiples of window size + pad_l = pad_t = 0 + pad_r = (self.window_size - W % self.window_size) % self.window_size + pad_b = (self.window_size - H % self.window_size) % self.window_size + x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) + _, Hp, Wp, _ = x.shape + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + else: + shifted_x = x + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) + + # W-MSA/SW-MSA + attn_windows = self.attn(x_windows) + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + + if pad_r > 0 or pad_b > 0: + x = x[:, :H, :W, :].contiguous() + + x = x.view(B, H * W, C) + + # FFN + x = shortcut + self.drop_path(x) + x = x + self.drop_path(self.mlp(self.norm2(x))) + + return x + +class PatchEmbed(nn.Module): + def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): + super().__init__() + self.patch_size = patch_size + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x): + _, _, H, W = x.shape + + # padding + pad_input = (H % self.patch_size != 0) or (W % self.patch_size != 0) + if pad_input: + x = F.pad(x, (0, self.patch_size - W % self.patch_size, + 0, self.patch_size - H % self.patch_size, + 0, 0)) + + x = self.proj(x) + x = x.flatten(2).transpose(1, 2) # B Ph*Pw C + x = self.norm(x) + return x + +class SwinTransformer(nn.Module): + def __init__(self, img_size=32, patch_size=4, in_chans=3, num_classes=10, + embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], + window_size=7, mlp_ratio=4., qkv_bias=True, + drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, + norm_layer=nn.LayerNorm, patch_norm=True): + super().__init__() + + self.num_classes = num_classes + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.patch_norm = patch_norm + + # split image into non-overlapping patches + self.patch_embed = PatchEmbed( + patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, + norm_layer=norm_layer if self.patch_norm else None) + + self.pos_drop = nn.Dropout(p=drop_rate) + + # build layers + layers = [] + for i_layer in range(self.num_layers): + layer = SwinTransformerBlock( + dim=embed_dim, + num_heads=num_heads[i_layer], + window_size=window_size, + shift_size=0 if (i_layer % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=drop_path_rate, + norm_layer=norm_layer) + layers.append(layer) + + self.layers = nn.ModuleList(layers) + self.norm = norm_layer(embed_dim) + self.avgpool = nn.AdaptiveAvgPool1d(1) + self.head = nn.Linear(embed_dim, num_classes) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def forward(self, x): + x = self.patch_embed(x) + x = self.pos_drop(x) + + for layer in self.layers: + layer.H, layer.W = x.size(1), x.size(2) + x = layer(x) + + x = self.norm(x) + x = self.avgpool(x.transpose(1, 2)) + x = torch.flatten(x, 1) + x = self.head(x) + + return x diff --git a/Image/SwinTransformer/code/train.py b/Image/SwinTransformer/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..56bbdd1734a09861cfac1d5116955853accb0771 --- /dev/null +++ b/Image/SwinTransformer/code/train.py @@ -0,0 +1,43 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import SwinTransformer + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = SwinTransformer( + img_size=32, + patch_size=4, + in_chans=3, + num_classes=10, + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=7, + mlp_ratio=4., + qkv_bias=True, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.1 + ) + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.001, # Transformer类模型通常使用较小的学习率 + device='cuda', + save_dir='../model', + model_name='swin_transformer' + ) + +if __name__ == '__main__': + main() diff --git a/Image/SwinTransformer/dataset/.gitkeep b/Image/SwinTransformer/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/SwinTransformer/model/.gitkeep b/Image/SwinTransformer/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/VGG/code/model.py b/Image/VGG/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..61a15d361d553288fca05524db618534c292ee1b --- /dev/null +++ b/Image/VGG/code/model.py @@ -0,0 +1,204 @@ +''' +VGG Networks in PyTorch + +VGG是由牛津大学Visual Geometry Group提出的一个深度卷积神经网络模型。 +主要特点: +1. 使用小卷积核(3x3)代替大卷积核,降低参数量 +2. 深层网络结构,多个卷积层叠加 +3. 使用多个3x3卷积层的组合来代替大的感受野 +4. 结构规整,易于扩展 + +网络结构示例(VGG16): +input + └─> [(Conv3x3, 64) × 2, MaxPool] + └─> [(Conv3x3, 128) × 2, MaxPool] + └─> [(Conv3x3, 256) × 3, MaxPool] + └─> [(Conv3x3, 512) × 3, MaxPool] + └─> [(Conv3x3, 512) × 3, MaxPool] + └─> [AvgPool, Flatten] + └─> FC(512, num_classes) + +参考论文: +[1] K. Simonyan and A. Zisserman, "Very Deep Convolutional Networks for Large-Scale Image Recognition," + arXiv preprint arXiv:1409.1556, 2014. +''' + +import torch +import torch.nn as nn + + +# VGG配置参数 +# M表示MaxPool层,数字表示输出通道数 +cfg = { + 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], + 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], +} + + +class ConvBlock(nn.Module): + """VGG的基本卷积块 + + 包含: Conv2d -> BatchNorm -> ReLU + 使用3x3卷积核,步长为1,padding为1以保持特征图大小不变 + + Args: + in_channels (int): 输入通道数 + out_channels (int): 输出通道数 + batch_norm (bool): 是否使用BatchNorm,默认为True + """ + def __init__(self, in_channels, out_channels, batch_norm=True): + super(ConvBlock, self).__init__() + + layers = [] + # 3x3卷积,padding=1保持特征图大小不变 + layers.append( + nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1 + ) + ) + + # 添加BatchNorm + if batch_norm: + layers.append(nn.BatchNorm2d(out_channels)) + + # ReLU激活函数 + layers.append(nn.ReLU(inplace=True)) + + self.block = nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x (torch.Tensor): 输入特征图 + + Returns: + torch.Tensor: 输出特征图 + """ + return self.block(x) + + +class VGG(nn.Module): + """VGG网络模型 + + Args: + vgg_name (str): VGG变体名称,可选VGG11/13/16/19 + num_classes (int): 分类数量,默认为10 + batch_norm (bool): 是否使用BatchNorm,默认为True + init_weights (bool): 是否初始化权重,默认为True + """ + def __init__(self, vgg_name='VGG16', num_classes=10, batch_norm=True, init_weights=True): + super(VGG, self).__init__() + + # 特征提取层 + self.features = self._make_layers(cfg[vgg_name], batch_norm) + + # 全局平均池化 + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + + # 分类器 + self.classifier = nn.Sequential( + nn.Linear(512, num_classes) + ) + + # 初始化权重 + if init_weights: + self._initialize_weights() + + def _make_layers(self, cfg, batch_norm=True): + """构建VGG的特征提取层 + + Args: + cfg (List): 网络配置参数 + batch_norm (bool): 是否使用BatchNorm + + Returns: + nn.Sequential: 特征提取层序列 + """ + layers = [] + in_channels = 3 + + for x in cfg: + if x == 'M': # 最大池化层 + layers.append(nn.MaxPool2d(kernel_size=2, stride=2)) + else: # 卷积块 + layers.append(ConvBlock(in_channels, x, batch_norm)) + in_channels = x + + return nn.Sequential(*layers) + + def forward(self, x): + """前向传播 + + Args: + x (torch.Tensor): 输入图像张量,[N,3,H,W] + + Returns: + torch.Tensor: 输出预测张量,[N,num_classes] + """ + # 特征提取 + x = self.features(x) + + # 全局平均池化 + x = self.avgpool(x) + + # 展平 + x = torch.flatten(x, 1) + + # 分类 + x = self.classifier(x) + return x + + def _initialize_weights(self): + """初始化模型权重 + + 采用论文中的初始化方法: + - 卷积层: xavier初始化 + - BatchNorm: weight=1, bias=0 + - 线性层: 正态分布初始化(std=0.01) + """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + # VGG论文中使用了xavier初始化 + nn.init.xavier_normal_(m.weight) + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + +def test(): + """测试函数 + + 创建VGG模型并进行前向传播测试,打印模型结构和参数信息 + """ + # 创建模型 + net = VGG('VGG16') + print('Model Structure:') + print(net) + + # 测试前向传播 + x = torch.randn(2, 3, 32, 32) + y = net(x) + print('\nInput Shape:', x.shape) + print('Output Shape:', y.shape) + + # 打印模型信息 + from torchinfo import summary + device = 'cuda' if torch.cuda.is_available() else 'cpu' + net = net.to(device) + summary(net, (2, 3, 32, 32)) + + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/Image/VGG/code/train.py b/Image/VGG/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..46a69ab5f524dc6f047ca3e7f50d9e20290064c4 --- /dev/null +++ b/Image/VGG/code/train.py @@ -0,0 +1,32 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import VGG + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + cfg = { + 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'] + } + model = VGG('VGG16') + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='vgg16' + ) + +if __name__ == '__main__': + main() diff --git a/Image/VGG/dataset/.gitkeep b/Image/VGG/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/VGG/model/.gitkeep b/Image/VGG/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ViT/code/model.py b/Image/ViT/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f34402724e1c857622a8e8eb0e7e2ad4ae795353 --- /dev/null +++ b/Image/ViT/code/model.py @@ -0,0 +1,171 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +class PatchEmbed(nn.Module): + """ 将图像分成patch并进行embedding """ + def __init__(self, img_size=32, patch_size=4, in_chans=3, embed_dim=96): + super().__init__() + self.img_size = img_size + self.patch_size = patch_size + self.n_patches = (img_size // patch_size) ** 2 + + self.proj = nn.Conv2d( + in_chans, embed_dim, + kernel_size=patch_size, stride=patch_size + ) + + def forward(self, x): + x = self.proj(x) # (B, E, H/P, W/P) + x = x.flatten(2) # (B, E, N) + x = x.transpose(1, 2) # (B, N, E) + return x + +class Attention(nn.Module): + """ 多头自注意力机制 """ + def __init__(self, dim, n_heads=8, qkv_bias=True, attn_p=0., proj_p=0.): + super().__init__() + self.n_heads = n_heads + self.dim = dim + self.head_dim = dim // n_heads + self.scale = self.head_dim ** -0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_p) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_p) + + def forward(self, x): + n_samples, n_tokens, dim = x.shape + + if dim != self.dim: + raise ValueError + + qkv = self.qkv(x) # (n_samples, n_patches + 1, 3 * dim) + qkv = qkv.reshape( + n_samples, n_tokens, 3, self.n_heads, self.head_dim + ) # (n_samples, n_patches + 1, 3, n_heads, head_dim) + qkv = qkv.permute(2, 0, 3, 1, 4) # (3, n_samples, n_heads, n_patches + 1, head_dim) + q, k, v = qkv[0], qkv[1], qkv[2] # each with shape (n_samples, n_heads, n_patches + 1, head_dim) + + k_t = k.transpose(-2, -1) # (n_samples, n_heads, head_dim, n_patches + 1) + dp = (q @ k_t) * self.scale # (n_samples, n_heads, n_patches + 1, n_patches + 1) + attn = dp.softmax(dim=-1) # (n_samples, n_heads, n_patches + 1, n_patches + 1) + attn = self.attn_drop(attn) + + weighted_avg = attn @ v # (n_samples, n_heads, n_patches + 1, head_dim) + weighted_avg = weighted_avg.transpose(1, 2) # (n_samples, n_patches + 1, n_heads, head_dim) + weighted_avg = weighted_avg.flatten(2) # (n_samples, n_patches + 1, dim) + + x = self.proj(weighted_avg) # (n_samples, n_patches + 1, dim) + x = self.proj_drop(x) # (n_samples, n_patches + 1, dim) + + return x + +class MLP(nn.Module): + """ 多层感知机 """ + def __init__(self, in_features, hidden_features, out_features, p=0.): + super().__init__() + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = nn.GELU() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(p) + + def forward(self, x): + x = self.fc1(x) # (n_samples, n_patches + 1, hidden_features) + x = self.act(x) # (n_samples, n_patches + 1, hidden_features) + x = self.drop(x) # (n_samples, n_patches + 1, hidden_features) + x = self.fc2(x) # (n_samples, n_patches + 1, out_features) + x = self.drop(x) # (n_samples, n_patches + 1, out_features) + + return x + +class Block(nn.Module): + """ Transformer编码器块 """ + def __init__(self, dim, n_heads, mlp_ratio=4.0, qkv_bias=True, + p=0., attn_p=0.): + super().__init__() + self.norm1 = nn.LayerNorm(dim, eps=1e-6) + self.attn = Attention( + dim, + n_heads=n_heads, + qkv_bias=qkv_bias, + attn_p=attn_p, + proj_p=p + ) + self.norm2 = nn.LayerNorm(dim, eps=1e-6) + hidden_features = int(dim * mlp_ratio) + self.mlp = MLP( + in_features=dim, + hidden_features=hidden_features, + out_features=dim, + ) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x + +class ViT(nn.Module): + """ Vision Transformer """ + def __init__( + self, + img_size=32, + patch_size=4, + in_chans=3, + n_classes=10, + embed_dim=96, + depth=12, + n_heads=8, + mlp_ratio=4., + qkv_bias=True, + p=0., + attn_p=0., + ): + super().__init__() + + self.patch_embed = PatchEmbed( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + ) + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter( + torch.zeros(1, 1 + self.patch_embed.n_patches, embed_dim) + ) + self.pos_drop = nn.Dropout(p=p) + + self.blocks = nn.ModuleList([ + Block( + dim=embed_dim, + n_heads=n_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + p=p, + attn_p=attn_p, + ) + for _ in range(depth) + ]) + + self.norm = nn.LayerNorm(embed_dim, eps=1e-6) + self.head = nn.Linear(embed_dim, n_classes) + + def forward(self, x): + n_samples = x.shape[0] + x = self.patch_embed(x) + + cls_token = self.cls_token.expand(n_samples, -1, -1) + x = torch.cat((cls_token, x), dim=1) + x = x + self.pos_embed + x = self.pos_drop(x) + + for block in self.blocks: + x = block(x) + + x = self.norm(x) + + cls_token_final = x[:, 0] + x = self.head(cls_token_final) + + return x diff --git a/Image/ViT/code/train.py b/Image/ViT/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..16916fc0213df4962837bd81a51a6f4249c2d0be --- /dev/null +++ b/Image/ViT/code/train.py @@ -0,0 +1,41 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import ViT + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = ViT( + img_size=32, + patch_size=4, + in_chans=3, + n_classes=10, + embed_dim=96, + depth=12, + n_heads=8, + mlp_ratio=4., + qkv_bias=True, + p=0.1, + attn_p=0.1, + ) + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.001, # Vision Transformer通常使用较小的学习率 + device='cuda', + save_dir='../model', + model_name='vit' + ) + +if __name__ == '__main__': + main() diff --git a/Image/ViT/dataset/.gitkeep b/Image/ViT/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ViT/model/.gitkeep b/Image/ViT/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ZFNet/code/model.py b/Image/ZFNet/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb0a193087c0c3e85366c201d789e8ebf73b729 --- /dev/null +++ b/Image/ZFNet/code/model.py @@ -0,0 +1,50 @@ +import torch +import torch.nn as nn + +class ZFNet(nn.Module): + def __init__(self, num_classes=10): + super(ZFNet, self).__init__() + self.features = nn.Sequential( + # conv1 + nn.Conv2d(3, 96, kernel_size=7, stride=2, padding=1), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, padding=1), + nn.LocalResponseNorm(size=5, alpha=0.0001, beta=0.75, k=2), + + # conv2 + nn.Conv2d(96, 256, kernel_size=5, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, padding=1), + nn.LocalResponseNorm(size=5, alpha=0.0001, beta=0.75, k=2), + + # conv3 + nn.Conv2d(256, 384, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + + # conv4 + nn.Conv2d(384, 384, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + + # conv5 + nn.Conv2d(384, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, padding=1), + ) + + self.classifier = nn.Sequential( + nn.Linear(256 * 2 * 2, 4096), + nn.ReLU(inplace=True), + nn.Dropout(), + + nn.Linear(4096, 4096), + nn.ReLU(inplace=True), + nn.Dropout(), + + nn.Linear(4096, num_classes), + ) + + def forward(self, x): + x = self.features(x) + x = x.view(x.size(0), -1) + x = self.classifier(x) + return x diff --git a/Image/ZFNet/code/train.py b/Image/ZFNet/code/train.py new file mode 100644 index 0000000000000000000000000000000000000000..858ea00509aaa544ec01b2093319d6a2d5d915cb --- /dev/null +++ b/Image/ZFNet/code/train.py @@ -0,0 +1,29 @@ +import sys +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from utils.dataset_utils import get_cifar10_dataloaders +from utils.train_utils import train_model +from model import ZFNet + +def main(): + # 获取数据加载器 + trainloader, testloader = get_cifar10_dataloaders(batch_size=128) + + # 创建模型 + model = ZFNet() + + # 训练模型 + train_model( + model=model, + trainloader=trainloader, + testloader=testloader, + epochs=200, + lr=0.1, + device='cuda', + save_dir='../model', + model_name='zfnet' + ) + +if __name__ == '__main__': + main() diff --git a/Image/ZFNet/dataset/.gitkeep b/Image/ZFNet/dataset/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/ZFNet/model/.gitkeep b/Image/ZFNet/model/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Image/utils/dataset_utils.py b/Image/utils/dataset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ef808ee293d760027de7227c4b970db00484b6cf --- /dev/null +++ b/Image/utils/dataset_utils.py @@ -0,0 +1,55 @@ +import torch +import torchvision +import torchvision.transforms as transforms +import os + +def get_cifar10_dataloaders(batch_size=128, num_workers=2, local_dataset_path=None): + """获取CIFAR10数据集的数据加载器 + + Args: + batch_size: 批次大小 + num_workers: 数据加载的工作进程数 + local_dataset_path: 本地数据集路径,如果提供则使用本地数据集,否则下载 + + Returns: + trainloader: 训练数据加载器 + testloader: 测试数据加载器 + """ + # 数据预处理 + transform_train = transforms.Compose([ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ]) + + transform_test = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ]) + + # 设置数据集路径 + if local_dataset_path: + print(f"使用本地数据集: {local_dataset_path}") + download = False + dataset_path = local_dataset_path + else: + print("未指定本地数据集路径,将下载数据集") + download = True + dataset_path = '../dataset' + + # 创建数据集路径 + if not os.path.exists(dataset_path): + os.makedirs(dataset_path) + + trainset = torchvision.datasets.CIFAR10( + root=dataset_path, train=True, download=download, transform=transform_train) + trainloader = torch.utils.data.DataLoader( + trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers) + + testset = torchvision.datasets.CIFAR10( + root=dataset_path, train=False, download=download, transform=transform_test) + testloader = torch.utils.data.DataLoader( + testset, batch_size=100, shuffle=False, num_workers=num_workers) + + return trainloader, testloader diff --git a/Image/utils/train_utils.py b/Image/utils/train_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..39daaf5ce9b20f454db4d152b8f7f868ce3e7a7e --- /dev/null +++ b/Image/utils/train_utils.py @@ -0,0 +1,283 @@ +""" +通用模型训练工具 + +提供了模型训练、评估、保存等功能,支持: +1. 训练进度可视化 +2. 日志记录 +3. 模型检查点保存 +4. 嵌入向量收集 +""" + +import torch +import torch.nn as nn +import torch.optim as optim +import time +import os +import json +import logging +import numpy as np +from tqdm import tqdm +from datetime import datetime + + +def setup_logger(log_file): + """配置日志记录器,如果日志文件存在则覆盖 + + Args: + log_file: 日志文件路径 + + Returns: + logger: 配置好的日志记录器 + """ + # 创建logger + logger = logging.getLogger('train') + logger.setLevel(logging.INFO) + + # 移除现有的处理器 + if logger.hasHandlers(): + logger.handlers.clear() + + # 创建文件处理器,使用'w'模式覆盖现有文件 + fh = logging.FileHandler(log_file, mode='w') + fh.setLevel(logging.INFO) + + # 创建控制台处理器 + ch = logging.StreamHandler() + ch.setLevel(logging.INFO) + + # 创建格式器 + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + fh.setFormatter(formatter) + ch.setFormatter(formatter) + + # 添加处理器 + logger.addHandler(fh) + logger.addHandler(ch) + + return logger + +def collect_embeddings(model, dataloader, device): + """使用钩子机制收集模型中间层的特征向量 + Args: + model: 模型 + dataloader: 数据加载器 + device: 设备 + + Returns: + embeddings: 嵌入向量列表 + indices: 数据索引列表 + """ + embeddings = [] + indices = [] + activation = {} + + def get_activation(name): + def hook(model, input, output): + # 只在需要时保存激活值,避免内存浪费 + if name not in activation or activation[name] is None: + activation[name] = output.detach() + return hook + + # 注册钩子到所有可能的特征提取层 + handles = [] + for name, module in model.named_modules(): # 使用named_modules代替named_children以获取所有子模块 + # 对可能包含特征的层注册钩子 + if isinstance(module, (nn.Conv2d, nn.Linear, nn.Sequential)): + handles.append(module.register_forward_hook(get_activation(name))) + + model.eval() + with torch.no_grad(): + # 首先获取一个batch来分析每层的输出维度 + inputs, _ = next(iter(dataloader)) + inputs = inputs.to(device) + _ = model(inputs) + + # 找到维度最大的层 + max_dim = 0 + max_layer_name = None + + # 分析所有层的输出维度 + for name, feat in activation.items(): + if feat is None or len(feat.shape) < 2: + continue + # 计算展平后的维度 + flat_dim = feat.numel() // feat.shape[0] # 每个样本的特征维度 + if flat_dim > max_dim: + max_dim = flat_dim + max_layer_name = name + + # 清除第一次运行的激活值 + activation.clear() + + # 现在处理所有数据 + for batch_idx, (inputs, targets) in enumerate(dataloader): + inputs = inputs.to(device) + _ = model(inputs) + + # 获取并处理特征 + features = activation[max_layer_name] + flat_features = torch.flatten(features, start_dim=1) + embeddings.append(flat_features.cpu().numpy()) + indices.extend(range(batch_idx * dataloader.batch_size, + min((batch_idx + 1) * dataloader.batch_size, + len(dataloader.dataset)))) + + # 清除本次的激活值 + activation.clear() + + # 移除所有钩子 + for handle in handles: + handle.remove() + + if len(embeddings) > 0: + return np.vstack(embeddings), indices + else: + return np.array([]), indices + +def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda:0', + save_dir='./checkpoints', model_name='model'): + """通用的模型训练函数 + Args: + model: 要训练的模型 + trainloader: 训练数据加载器 + testloader: 测试数据加载器 + epochs: 训练轮数 + lr: 学习率 + device: 训练设备,格式为'cuda:N',其中N为GPU编号(0,1,2,3) + save_dir: 模型保存目录 + model_name: 模型名称 + """ + # 检查并设置GPU设备 + if not torch.cuda.is_available(): + print("CUDA不可用,将使用CPU训练") + device = 'cpu' + elif not device.startswith('cuda:'): + device = f'cuda:0' + + # 确保device格式正确 + if device.startswith('cuda:'): + gpu_id = int(device.split(':')[1]) + if gpu_id >= torch.cuda.device_count(): + print(f"GPU {gpu_id} 不可用,将使用GPU 0") + device = 'cuda:0' + + # 设置保存目录 + if not os.path.exists(save_dir): + os.makedirs(save_dir) + + # 设置日志 + log_file = os.path.join(os.path.dirname(save_dir), 'code', 'train.log') + if not os.path.exists(os.path.dirname(log_file)): + os.makedirs(os.path.dirname(log_file)) + logger = setup_logger(log_file) + + # 损失函数和优化器 + criterion = nn.CrossEntropyLoss() + optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200) + + # 移动模型到指定设备 + model = model.to(device) + best_acc = 0 + start_time = time.time() + + logger.info(f'开始训练 {model_name}') + logger.info(f'总轮数: {epochs}, 学习率: {lr}, 设备: {device}') + + for epoch in range(epochs): + # 训练阶段 + model.train() + train_loss = 0 + correct = 0 + total = 0 + + train_pbar = tqdm(trainloader, desc=f'Epoch {epoch+1}/{epochs} [Train]') + for batch_idx, (inputs, targets) in enumerate(train_pbar): + inputs, targets = inputs.to(device), targets.to(device) + optimizer.zero_grad() + outputs = model(inputs) + loss = criterion(outputs, targets) + loss.backward() + optimizer.step() + + train_loss += loss.item() + _, predicted = outputs.max(1) + total += targets.size(0) + correct += predicted.eq(targets).sum().item() + + # 更新进度条 + train_pbar.set_postfix({ + 'loss': f'{train_loss/(batch_idx+1):.3f}', + 'acc': f'{100.*correct/total:.2f}%' + }) + + # 每100步记录一次 + if batch_idx % 100 == 0: + logger.info(f'Epoch: {epoch+1} | Batch: {batch_idx} | ' + f'Loss: {train_loss/(batch_idx+1):.3f} | ' + f'Acc: {100.*correct/total:.2f}%') + + # 测试阶段 + model.eval() + test_loss = 0 + correct = 0 + total = 0 + + test_pbar = tqdm(testloader, desc=f'Epoch {epoch+1}/{epochs} [Test]') + with torch.no_grad(): + for batch_idx, (inputs, targets) in enumerate(test_pbar): + inputs, targets = inputs.to(device), targets.to(device) + outputs = model(inputs) + loss = criterion(outputs, targets) + + test_loss += loss.item() + _, predicted = outputs.max(1) + total += targets.size(0) + correct += predicted.eq(targets).sum().item() + + # 更新进度条 + test_pbar.set_postfix({ + 'loss': f'{test_loss/(batch_idx+1):.3f}', + 'acc': f'{100.*correct/total:.2f}%' + }) + + # 计算测试精度 + acc = 100.*correct/total + logger.info(f'Epoch: {epoch+1} | Test Loss: {test_loss/(batch_idx+1):.3f} | ' + f'Test Acc: {acc:.2f}%') + + # 创建epoch保存目录 + epoch_dir = os.path.join(save_dir, f'epoch_{epoch+1}') + if not os.path.exists(epoch_dir): + os.makedirs(epoch_dir) + + # 保存模型权重 + model_path = os.path.join(epoch_dir, 'subject_model.pth') + torch.save(model.state_dict(), model_path) + + # 收集并保存嵌入向量 + embeddings, indices = collect_embeddings(model, trainloader, device) + # 保存嵌入向量 + np.save(os.path.join(epoch_dir, 'train_data.npy'), embeddings) + + # 保存索引信息 - 仅保存数据点的索引列表 + with open(os.path.join(epoch_dir, 'index.json'), 'w') as f: + json.dump(indices, f) + + # 如果是最佳精度,额外保存一份 + if acc > best_acc: + logger.info(f'Best accuracy: {acc:.2f}%') + best_dir = os.path.join(save_dir, 'best') + if not os.path.exists(best_dir): + os.makedirs(best_dir) + # 复制最佳模型文件 + best_model_path = os.path.join(best_dir, 'subject_model.pth') + torch.save(model.state_dict(), best_model_path) + best_acc = acc + + scheduler.step() + + # 训练结束 + total_time = time.time() - start_time + logger.info(f'训练完成! 总用时: {total_time/3600:.2f}小时') + logger.info(f'最佳测试精度: {best_acc:.2f}%') diff --git a/README.md b/README.md index 10f7e5a1229ebfbe83b5e27098ec9bc8690ae6c1..80323f02432723a4d2c7e6e0e1fd1c08415f28b9 100644 --- a/README.md +++ b/README.md @@ -19,70 +19,182 @@ license: mit Clone-detection-BigCloneBench 基于大规模代码克隆基准数据集的代码克隆检测模型,任务是进行二元分类(0/1),其中1代表语义等价,0代表其他情况。 代码克隆检测 - 2个epoch + 待上传 BigCloneBench数据集 Clone-detection-POJ-104 基于POJ-104数据集的代码克隆检测模型,任务是识别不同编程题目中相似的代码实现,给定一段代码和一组候选代码,任务是返回具有相同语义的Top K个代码 代码克隆检测 - 2个epoch (0-1) + 待上传 POJ-104编程题目数据集 CodeCompletion-token 基于token级别的代码自动补全模型 代码补全 - 5个epoch (Java语料库) + 待上传 Java代码token序列数据集 Defect-detection 代码缺陷检测模型,通过分析代码来识别潜在的缺陷和错误(进行二元分类(0/1)) 代码缺陷检测 - 5个epoch + 待上传 包含缺陷标注的C语言代码数据集 code-refinement 代码优化模型 代码优化/重构 - 34个epoch(small数据集) + 待上传 代码优化前后对数据集(C语言) code-to-text 代码到自然语言的转换模型 代码注释生成 - 每种语言10个epoch (支持Python/Java/JavaScript/PHP/Ruby/Go) + 待上传 多语言代码-文本对数据集 NL-code-search-Adv 高级自然语言代码搜索模型,通过计算自然语言查询与代码片段之间的相似性来实现代码搜索, 代码搜索 - 2个epoch + 待上传 自然语言-(python)代码对数据集 NL-code-search-WebQuery 基于Web查询的代码搜索模型,该模型通过编码器处理代码和自然语言输入,并利用多层感知器(MLP)来计算相似性得分 代码搜索 - 两个数据集各3个epoch + 待上传 Web查询-代码对数据集(CodeSearchNet数据集和CoSQA数据集(python)) text-to-code 自然语言到代码的生成模型 代码生成 - 23个epoch + 待上传 文本描述-代码(c语言)对数据集 Graph 在QM9数据集上训练的图掩码自编码器,通过对分子图中的原子的坐标以及类型进行预测实现自监督训练 图自编码器 - 10个epoch + 待上传 分子属性预测数据集 + + AlexNet + 2012年获得ImageNet冠军的经典模型,首次证明了深度学习在图像识别上的强大能力。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + DenseNet + 每一层都直接与其他所有层相连,像搭积木一样层层堆叠,可以更好地学习图像特征。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + EfficientNet + 通过平衡网络的深度、宽度和图像分辨率,用更少的计算量达到更好的效果。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + GoogLeNet + 谷歌开发的模型,像多个眼睛同时看图片的不同部分,既省资源又准确。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + LeNet5 + 深度学习领域的开山之作,虽然简单但奠定了现代CNN的基础架构。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + MobileNetv1 + 专门为手机设计的轻量级模型,用特殊的卷积方式减少计算量。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + MobileNetv2 + MobileNet的升级版,增加了特征复用机制,性能更好。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + MobileNetv3 + 结合自动搜索技术的新版本,自动找到最适合手机的网络结构。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + ResNet + 通过特殊的"快捷连接"解决深层网络训练难的问题,可以训练超级深的网络。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + SENet + 为网络添加了"注意力机制",让模型能够关注图片中重要的部分。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + ShuffleNet + 通过巧妙地打乱和分组计算,实现了手机上的高效运行。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + ShuffleNetv2 + 在原版基础上优化设计,速度更快,效果更好。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + SwinTransformer + 把自然语言处理的先进技术用于图像,通过逐步关注图片不同区域来理解图像。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + VGG + 用统一的小型卷积核堆叠成深层网络,结构简单但效果好。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + ViT + 把图片切成小块后像读文章一样处理,是一种全新的图像处理方式。 + 图像分类 + 待补充 + CIFAR-10数据集 + + + ZFNet + 通过可视化研究改进的AlexNet,帮助人们理解网络是如何"看"图片的。 + 图像分类 + 待补充 + CIFAR-10数据集 +