网站建设外文文献,企业官网建站的流程,网站横条广告,wordpress背景自动变幻图形B站学习视频 up主的csdn博客
1、什么是Faster R-CNN 2、pytorch-gpu环境配置#xff08;跳过#xff09;
3、Faster R-CNN整体结构介绍 Faster-RCNN可以采用多种的主干特征提取网络#xff0c;常用的有VGG#xff0c;Resnet#xff0c;Xception等等。 Faster-RCNN对输入…B站学习视频 up主的csdn博客
1、什么是Faster R-CNN 2、pytorch-gpu环境配置跳过
3、Faster R-CNN整体结构介绍 Faster-RCNN可以采用多种的主干特征提取网络常用的有VGGResnetXception等等。 Faster-RCNN对输入进来的图片尺寸没有固定但一般会把输入进来的图片短边固定成600.
4、Resnet50-主干特征提取网络介绍
具体学习见Resnet50
import mathimport torch.nn as nn
from torch.hub import load_state_dict_from_urlclass Bottleneck(nn.Module):expansion 4 #最后一个卷积层输出通道数相对于输入通道数的倍数def __init__(self, inplanes, planes, stride1, downsampleNone):inplanes输入通道数planes卷积层输出的通道数stride卷积的步长默认为1downsample是否对输入进行下采样super(Bottleneck, self).__init__()#使用1*1卷积核压缩通道数self.conv1 nn.Conv2d(inplanes, planes, kernel_size1, stridestride, biasFalse)#二维卷积层self.bn1 nn.BatchNorm2d(planes)#二维批归一化层#使用3*3卷积核特征提取padding1在输入的周围使用1个零填充以保持特征图的尺寸self.conv2 nn.Conv2d(planes, planes, kernel_size3, stride1, padding1, biasFalse)self.bn2 nn.BatchNorm2d(planes)#使用1*1卷积核扩张通道数self.conv3 nn.Conv2d(planes, planes * 4, kernel_size1, biasFalse)self.bn3 nn.BatchNorm2d(planes * 4)self.relu nn.ReLU(inplaceTrue)self.downsample downsampleself.stride stridedef forward(self, x):residual 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)if self.downsample is not None:residual self.downsample(x)out residualout self.relu(out)return outclass ResNet(nn.Module):def __init__(self, block, layers, num_classes1000):#-----------------------------------## 假设输入进来的图片是600,600,3#-----------------------------------#self.inplanes 64 #初始化ResNet模型的通道数为64super(ResNet, self).__init__()# 600,600,3 - 300,300,64self.conv1 nn.Conv2d(3, 64, kernel_size7, stride2, padding3, biasFalse)self.bn1 nn.BatchNorm2d(64)self.relu nn.ReLU(inplaceTrue)# 300,300,64 - 150,150,64 最大池化层用于降低特征图的空间分辨率self.maxpool nn.MaxPool2d(kernel_size3, stride2, padding0, ceil_modeTrue)#构建4个残差块组成的特征提取部分每个部分的通道数和空间分辨率逐渐增加# 150,150,64 - 150,150,256self.layer1 self._make_layer(block, 64, layers[0])# 150,150,256 - 75,75,512self.layer2 self._make_layer(block, 128, layers[1], stride2)# 75,75,512 - 38,38,1024 到这里可以获得一个38,38,1024的共享特征层self.layer3 self._make_layer(block, 256, layers[2], stride2)# self.layer4被用在classifier模型中self.layer4 self._make_layer(block, 512, layers[3], stride2)self.avgpool nn.AvgPool2d(7)#全局平均池化层 池化核7*7#将最终的特征映射到类别数量的空间self.fc nn.Linear(512 * block.expansion, num_classes) #全连接层for m in self.modules():if isinstance(m, nn.Conv2d):n m.kernel_size[0] * m.kernel_size[1] * m.out_channelsm.weight.data.normal_(0, math.sqrt(2. / n))elif isinstance(m, nn.BatchNorm2d):m.weight.data.fill_(1)m.bias.data.zero_()def _make_layer(self, block, planes, blocks, stride1):downsample None#-------------------------------------------------------------------## 当模型需要进行高和宽的压缩的时候就需要用到残差边的downsample#-------------------------------------------------------------------#if stride ! 1 or self.inplanes ! planes * block.expansion:downsample nn.Sequential(nn.Conv2d(self.inplanes, planes * block.expansion,kernel_size1, stridestride, biasFalse),nn.BatchNorm2d(planes * block.expansion),)layers []layers.append(block(self.inplanes, planes, stride, downsample))self.inplanes planes * block.expansionfor i in range(1, blocks):layers.append(block(self.inplanes, planes))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)x self.avgpool(x)x x.view(x.size(0), -1)x self.fc(x)return xdef resnet50(pretrained False):model ResNet(Bottleneck, [3, 4, 6, 3])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)#----------------------------------------------------------------------------## 获取特征提取部分从conv1到model.layer3最终获得一个38,38,1024的特征层#----------------------------------------------------------------------------#features list([model.conv1, model.bn1, model.relu, model.maxpool, model.layer1, model.layer2, model.layer3])#----------------------------------------------------------------------------## 获取分类部分从model.layer4到model.avgpool#----------------------------------------------------------------------------#classifier list([model.layer4, model.avgpool])features nn.Sequential(*features)classifier nn.Sequential(*classifier)return features, classifier5、RPN-建议框网络构建 6、Anchors-先验框详解
import numpy as np#--------------------------------------------#
# 生成基础的先验框
#--------------------------------------------#
def generate_anchor_base(base_size16, ratios[0.5, 1, 2], anchor_scales[8, 16, 32]):base_size基础框的大小默认为16ratios生成锚框的宽高比默认为[0.5,1,2]anchor_scales生成锚框的尺度默认为[8,16,32]#创建一个形状为((len(ratios) * len(anchor_scales), 4)的全零数组用于存储生成的基础先验框的坐标信息#每个先验框由4个坐标值表示anchor_base np.zeros((len(ratios) * len(anchor_scales), 4), dtypenp.float32)for i in range(len(ratios)):for j in range(len(anchor_scales)):#使用两个嵌套的循环遍历宽高比和尺度的所有组合宽高比定义面积不变性h base_size * anchor_scales[j] * np.sqrt(ratios[i])w base_size * anchor_scales[j] * np.sqrt(1. / ratios[i])index i * len(anchor_scales) janchor_base[index, 0] - h / 2.anchor_base[index, 1] - w / 2.anchor_base[index, 2] h / 2.anchor_base[index, 3] w / 2.return anchor_base#--------------------------------------------#
# 对基础先验框进行拓展对应到所有特征点上
#--------------------------------------------#
def _enumerate_shifted_anchor(anchor_base, feat_stride, height, width):#---------------------------------## 计算网格中心点#---------------------------------#anchor_base 表示基础先验框的坐标信息feat_stride 特征点间距步长height 和 width 表示特征图的高度和宽度。shift_x np.arange(0, width * feat_stride, feat_stride)shift_y np.arange(0, height * feat_stride, feat_stride)shift_x, shift_y np.meshgrid(shift_x, shift_y)shift np.stack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel(),), axis1)#---------------------------------## 每个网格点上的9个先验框#---------------------------------#A anchor_base.shape[0]K shift.shape[0]anchor anchor_base.reshape((1, A, 4)) shift.reshape((K, 1, 4))#---------------------------------## 所有的先验框#---------------------------------#anchor anchor.reshape((K * A, 4)).astype(np.float32)return anchorif __name__ __main__:import matplotlib.pyplot as pltnine_anchors generate_anchor_base()print(nine_anchors)height, width, feat_stride 38,38,16anchors_all _enumerate_shifted_anchor(nine_anchors, feat_stride, height, width)print(np.shape(anchors_all))fig plt.figure()ax fig.add_subplot(111)plt.ylim(-300,900)plt.xlim(-300,900)shift_x np.arange(0, width * feat_stride, feat_stride)shift_y np.arange(0, height * feat_stride, feat_stride)shift_x, shift_y np.meshgrid(shift_x, shift_y)plt.scatter(shift_x,shift_y)box_widths anchors_all[:,2]-anchors_all[:,0]box_heights anchors_all[:,3]-anchors_all[:,1]for i in [108, 109, 110, 111, 112, 113, 114, 115, 116]:rect plt.Rectangle([anchors_all[i, 0],anchors_all[i, 1]],box_widths[i],box_heights[i],colorr,fillFalse)ax.add_patch(rect)plt.show()7、模型训练及测试结果
结合博客及视频完成VOC2007数据集的训练及预测对faster rcnn原理及如何使用有了初步的认识。train.py frcnn.py predict.py get_map.py 相关结果如下