孪生网络pytoch实现,以resnet为特征提取网络
我的孪生网络代码来源于孪生网络博主,这里的源代码使用的vgg16作为特征提取网络,我的主要工作是将vgg16替换为resnet网络。
1.建立resnet网络
import torch.nn as nn
import torch
# from torchvision.models.utils import load_state_dict_from_url
from torchsummary import summary
from torch.hub import load_state_dict_from_urlclass BasicBlock(nn.Module):#resnet18和resnet34的主干网络搭建expansion = 1def __init__(self, in_channel, out_channel, stride=1, downsample=None, **kwargs):super(BasicBlock, self).__init__()self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,kernel_size=3, stride=stride, padding=1, bias=False)self.bn1 = nn.BatchNorm2d(out_channel)self.relu = nn.ReLU()self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,kernel_size=3, stride=1, padding=1, bias=False)self.bn2 = nn.BatchNorm2d(out_channel)self.downsample = downsampledef forward(self, x):identity = xif self.downsample is not None:identity = self.downsample(x)out = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)out += identityout = self.relu(out)return outclass Bottleneck(nn.Module):"""注意:原论文中,在虚线残差结构的主分支上,第一个1x1卷积层的步距是2,第二个3x3卷积层步距是1。但在pytorch官方实现过程中是第一个1x1卷积层的步距是1,第二个3x3卷积层步距是2,这么做的好处是能够在top1上提升大概0.5%的准确率。可参考Resnet v1.5 https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch"""expansion = 4def __init__(self, in_channel, out_channel, stride=1, downsample=None,groups=1, width_per_group=64):super(Bottleneck, self).__init__()width = int(out_channel * (width_per_group / 64.)) * groupsself.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=width,kernel_size=1, stride=1, bias=False) # squeeze channelsself.bn1 = nn.BatchNorm2d(width)# -----------------------------------------self.conv2 = nn.Conv2d(in_channels=width, out_channels=width, groups=groups,kernel_size=3, stride=stride, bias=False, padding=1)self.bn2 = nn.BatchNorm2d(width)# -----------------------------------------self.conv3 = nn.Conv2d(in_channels=width, out_channels=out_channel*self.expansion,kernel_size=1, stride=1, bias=False) # unsqueeze channelsself.bn3 = nn.BatchNorm2d(out_channel*self.expansion)self.relu = nn.ReLU(inplace=True)self.downsample = downsampledef forward(self, x):identity = xif self.downsample is not None:identity = self.downsample(x)out = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)out = self.relu(out)out = self.conv3(out)out = self.bn3(out)out += identityout = self.relu(out)return outclass ResNet(nn.Module):def __init__(self,block,blocks_num,num_classes=1000,include_top=True,groups=1,width_per_group=64):super(ResNet, self).__init__()self.include_top = include_topself.in_channel = 64self.groups = groupsself.width_per_group = width_per_groupself.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,padding=3, bias=False)self.bn1 = nn.BatchNorm2d(self.in_channel)self.relu = nn.ReLU(inplace=True)self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)self.layer1 = self._make_layer(block, 64, blocks_num[0])self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)if self.include_top:self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # output size = (1, 1)self.fc = nn.Linear(512 * block.expansion, num_classes)for m in self.modules():if isinstance(m, nn.Conv2d):nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')def _make_layer(self, block, channel, block_num, stride=1):downsample = Noneif stride != 1 or self.in_channel != channel * block.expansion:downsample = nn.Sequential(nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False),nn.BatchNorm2d(channel * block.expansion))layers = []layers.append(block(self.in_channel,channel,downsample=downsample,stride=stride,groups=self.groups,width_per_group=self.width_per_group))self.in_channel = channel * block.expansionfor _ in range(1, block_num):layers.append(block(self.in_channel,channel,groups=self.groups,width_per_group=self.width_per_group))return nn.Sequential(*layers)def forward(self, x):x = self.conv1(x)x = self.bn1(x)x = self.relu(x)x = self.maxpool(x)x = self.layer1(x)x = self.layer2(x)x = self.layer3(x)x = self.layer4(x)if self.include_top:x = self.avgpool(x)x = torch.flatten(x, 1)x = self.fc(x)return xdef resnet34(pretrained,num_classes=1000, include_top=True):# https://download.pytorch.org/models/resnet34-333f7ec4.pthmodel = ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)if pretrained:state_dict = load_state_dict_from_url("https://download.pytorch.org/models/resnet34-333f7ec4.pth",model_dir="./model_data")model.load_state_dict(state_dict)return modeldef resnet50(pretrained,num_classes=1000, include_top=True):# https://download.pytorch.org/models/resnet50-19c8e357.pthmodel=ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)if pretrained:state_dict = load_state_dict_from_url("https://download.pytorch.org/models/resnet50-19c8e357.pth",model_dir="./model_data")model.load_state_dict(state_dict)return modeldef resnet101(pretrained,num_classes=1000, include_top=True):# https://download.pytorch.org/models/resnet101-5d3b4d8f.pthmodel=ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, include_top=include_top)if pretrained:state_dict = load_state_dict_from_url("https://download.pytorch.org/models/resnet101-5d3b4d8f.pth",model_dir="./model_data")model.load_state_dict(state_dict)return modeldef resnext50_32x4d(num_classes=1000, include_top=True):# https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pthgroups = 32width_per_group = 4return ResNet(Bottleneck, [3, 4, 6, 3],num_classes=num_classes,include_top=include_top,groups=groups,width_per_group=width_per_group)def resnext101_32x8d(num_classes=1000, include_top=True):# https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pthgroups = 32width_per_group = 8return ResNet(Bottleneck, [3, 4, 23, 3],num_classes=num_classes,include_top=include_top,groups=groups,width_per_group=width_per_group)if __name__=='__main__':net=resnet101(False)# del net.avgpoolsummary(net,(3,105,105))x=torch.rand(1,3,105,105)out=net(x)print(out.shape)
2.修改调用网络的siamese.py文件
修改的主要思路就是按照原来调用vgg16的思路,将调用vgg16的地方全部修改为调用resnet网络。这里可以修改为调用resnet34,resnet50和resnet101.
原来的调用vgg16部分:
class Siamese(nn.Module):def __init__(self, input_shape, pretrained=False):super(Siamese, self).__init__()self.vgg = VGG16(pretrained, input_shape[-1])del self.vgg.avgpooldel self.vgg.classifierflat_shape = 512 * get_img_output_length(input_shape[1], input_shape[0])self.fully_connect1 = torch.nn.Linear(flat_shape, 512)self.fully_connect2 = torch.nn.Linear(512, 1)def forward(self, x):x1, x2 = x#------------------------------------------## 我们将两个输入传入到主干特征提取网络#------------------------------------------#x1 = self.vgg.features(x1)x2 = self.vgg.features(x2) #-------------------------## 相减取绝对值#-------------------------# x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs(x1 - x2)#-------------------------## 进行两次全连接#-------------------------#x = self.fully_connect1(x)x = self.fully_connect2(x)return x
修改后调用resnet网络的部分:这是调用resnet50的修改部分。
class Siamese(nn.Module):def __init__(self, input_shape, pretrained=False):super(Siamese, self).__init__()self.resnet= resnet50(pretrained, include_top=True)del self.resnet.avgpooldel self.resnet.fc# flat_shape = 512 * get_img_output_length(input_shape[1], input_shape[0])flat_shape = 2048 * 4*4self.fully_connect1 = torch.nn.Linear(flat_shape, 512)self.fully_connect2 = torch.nn.Linear(512, 1)def forward(self, x):x1, x2 = x#------------------------------------------## 我们将两个输入传入到主干特征提取网络#------------------------------------------#x1 = self.resnet.conv1(x1)x1 = self.resnet.bn1(x1)x1 = self.resnet.relu(x1)x1 = self.resnet.maxpool(x1)x1 = self.resnet.layer1(x1)x1 = self.resnet.layer2(x1)x1 = self.resnet.layer3(x1)x1 = self.resnet.layer4(x1)x2 = self.resnet.conv1(x2)x2 = self.resnet.bn1(x2)x2 = self.resnet.relu(x2)x2 = self.resnet.maxpool(x2)x2 = self.resnet.layer1(x2)x2 = self.resnet.layer2(x2)x2 = self.resnet.layer3(x2)x2 = self.resnet.layer4(x2)#-------------------------## 相减取绝对值#-------------------------# x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs(x1 - x2)#-------------------------## 进行两次全连接#-------------------------#x = self.fully_connect1(x)x = self.fully_connect2(x)return x
对于原文的:
flat_shape = 512 * get_img_output_length(input_shape[1], input_shape[0])
我不是很明白它的长宽是怎么计算的,我就根据resnet50的输出关系,将其直接手动修改为512*4*4,在resnet50的特征提取的最后一个池化层之后的输出特征维度就是512*4*4,当然这是对对应105*105长宽输入图像的时候,如果要自己修改一个图像输入尺寸,只需要看看resnet最后一个池化层的输出特征维度即可。如果是resnet101,则需要将这部分改为2048*4*4.
对于特征提取部分,源码写的是:
x1 = self.vgg.features(x1)
x2 = self.vgg.features(x2)
如果我按照源码这样去写是这样的:
x1 = self.resnet(x1)
x2 = self.resnet(x2)
但是这样总是会报错,因此我就将特征提取部分改为这样:
x1 = self.resnet.conv1(x1)x1 = self.resnet.bn1(x1)x1 = self.resnet.relu(x1)x1 = self.resnet.maxpool(x1)x1 = self.resnet.layer1(x1)x1 = self.resnet.layer2(x1)x1 = self.resnet.layer3(x1)x1 = self.resnet.layer4(x1)x2 = self.resnet.conv1(x2)x2 = self.resnet.bn1(x2)x2 = self.resnet.relu(x2)x2 = self.resnet.maxpool(x2)x2 = self.resnet.layer1(x2)x2 = self.resnet.layer2(x2)x2 = self.resnet.layer3(x2)x2 = self.resnet.layer4(x2)
对于最后的向量相似度计算:源码用的是相减的绝对值
x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs(x1 - x2)
我试过:
x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs((x1 - x2)**2)
x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs(x1*x1 - x2*x2)
x1 = torch.flatten(x1, 1)x2 = torch.flatten(x2, 1)x = torch.abs((x1*x1 - x2*x2)**2)
感觉结果都差不多。
孪生网络pytoch实现,以resnet为特征提取网络相关推荐
- 小白入门计算机视觉系列——ReID(二):baseline构建:基于PyTorch的全局特征提取网络(Finetune ResNet50+tricks)
ReID(二):baseline构建:基于PyTorch的全局特征提取网络(Finetune ResNet50+tricks) 本次带来的是计算机视觉中比较热门的重点的一块,行人重识别(也叫Perso ...
- yolov4源码_YOLOv4特征提取网络——CSPDarkNet结构解析及PyTorch实现
1 YOLOv4目标检测模型 自从Redmon说他不在更新YOLO系列之后,我一度以为这么好用的框架就要慢慢淡入历史了,事实是我多虑了.YOLOv4在使用YOLO Loss的基础上,使用了新的back ...
- 【YOLOV4】(7) 特征提取网络代码复现(CSPDarknet53+SPP+PANet+Head),附Tensorflow完整代码
各位同学好,今天和大家分享一下如何使用 TensorFlow 构建YOLOV4目标检测算法的特征提取网络. 完整代码在我的Gitee中,有需要的自取:https://gitee.com/dgvv4/y ...
- 基于并行附加特征提取网络的SSD地面小目标检测模型
人工智能技术与咨询 来源:<电子学报> ,作者李宝奇等 摘 要: 针对SSD原始附加特征提取网络(Original Additional Feature Extraction Networ ...
- resnet结构_经典卷积网络(二)-ResNet
一.ResNet(总结自csdn文章) 随着网络的加深,出现了训练集准确率下降的现象,确定这不是由于Overfit过拟合造成的.作者针对这个问题提出了一种全新的网络,叫深度残差网络,它允许网络尽可能的 ...
- ResNet深度残差网络
ResNet 论文:"Deep Residual Learning for Image Recognition" 面临的问题 ResNet解决的是深度神经网络的"退化&q ...
- ResNet、ResNeXt网络详解及复现
网络详解: ResNet网络详解 ResNeXt网络详解 torch复现: import torch.nn as nn import torch''' 对应着18层和34层的残差结构 既要拥有实现部分 ...
- 深度学习:ResNet(残差网络)
ResNet在ILSVRC2015竞赛中惊艳亮相,一下子将网络深度提升到152层,将错误率降到了3.57,在图像识别错误率和网络深度方面,比往届比赛有了非常大的提升,ResNet毫无悬念地夺得了ILS ...
- 深度学习笔记(七)--ResNet(残差网络)
内容来自吴恩达老师视频,网易云课堂有哦 ResNets 非常非常深的神经网络是很难训练的,因为存在梯度消失和梯度爆炸问题.ResNets是由残差块(Residual block)构建的,首先解释一下什 ...
- 非深度网络 Non-deep Network:低延迟平行网络 ParNet,仅 12 层媲美 ResNet
Non-deep Network Ankit Goyal1,2 Alexey Bochkovskiy2 Jia Deng1 Vladlen Koltun2 1Princeton Unive ...
最新文章
- C#垃圾回收(GC)
- MIT_18.03_微分方程_Fourier_Series_傅里叶级数_Notes
- AI:《A Simple Tool to Start Making Decisions with the Help of AI—借助人工智能开始决策的简单工具》翻译与解读
- IBM公司扩展云平台 计划推出SmartCloud
- Netty(一)——Netty入门程序
- linux centos查看CPU型号及物理CPU个数
- 开发中关于Fragment异常的两个问题
- 牛客 - A Simple Game(尼姆博弈变形)
- IOS:APP三种状态下收到推送后的跳转操作
- GitHub 向别人的仓库贡献代码
- python爬取网站大数据_[Python]爬虫抓取大数据职位数据
- Python | Path 让文件路径提取变得简单(含代码)
- 全球及中国毫米波人体安检仪行业竞争格局分析与投资战略规划研究报告2022-2028年
- linux-----基本操作指令(2)
- CSS 样式实现单边阴影
- 给自己的android扫盲文 - 1
- 绘制图像灰度直方图——将图像的灰度分布可视化方法总结
- 微信字 签到 java_java微信签到功能实现:java做的一个简易的微信签到系统
- 6.百度地图例子讲解
- A1-2017级算法上机第一次练习赛 J 怠惰的园丁王木木