【Faster RCNN源码解读/复现】Faster RCNN网络总览

写在前面

博主是一名刚转行CV不久的一枚小硕,大约半年前对目标检测相关的几个经典网络(RCNN, Fast RCNN, Faster RCNN, YOLO, SSD)等有一些简单的了解(听说而已)。这学期转行以来,准备从Faster RCNN着手,研读论文,理解并努力复现源码。经过大约一个月的努力,Faster RCNN已基本上复现完成,借优快云平台,分享自己的一些理解和感悟,希望和大家一起进步。

网络框图

在读完Faster RCNN论文之后,可以知道,Faster RCNN总体上可分为三部分,如下图所示,

  1. 用于提取图像特征,实现参数共享的多个卷积层;
  2. 用于得到Proposal(候选框)的RPN层,这也是Faster RCNN最经典的部分;
  3. 用于完成分类和边界框回归的RoI Pooling层和分类层。

Faster RCNN结构图
在实现网络的过程中,必定会将这三部分进一步地划分为最小的功能单元。

对于提取特征的卷积层,通常使用VGG、ResNet等预训练模型,当前,也可使用ShuffleNet、Inception等实现,只需要在搭建出相应网络的基本结构,下载预训练模型并在源码上做出相应的更改即可;

对于RPN层,又可分为产生anchors的generate_anchors层,对anchors进行前景/背景分类和boungding box回归的rpn_anchor_target层,以及产生最终用于目标检测的proposals的proposal_layer;

对于ROI_Pooling层,则需要将尺寸不一的proposals通过相关的Pooling技术,转换为同样的尺寸,只有这样,才能将这些proposals作为一个batch输入分类层;

对于分类层,不单单

### Faster R-CNN 实现教程 #### 一、环境准备 为了成功运行Faster R-CNN,需先配置好开发环境。推荐使用Anaconda来管理Python包和虚拟环境。 安装PyTorch及相关依赖库: ```bash conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch ``` #### 二、获取代码资源 可以从GitHub上找到多个开源项目提供完整的Faster R-CNN实现方案[^3]。例如biluko的仓库提供了详尽的目标检测算法实践指南以及配套的数据集处理工具。 下载并解压源码文件夹后,在命令行界面进入该项目目录下继续操作: ```bash git clone https://github.com/biluko/Faster-RCNN-Pytorch.git cd Faster-RCNN-Pytorch ``` #### 三、数据预处理 对于输入图像尺寸不一致的情况,通常会采用固定大小缩放的方式统一图片分辨率。此外还需要对原始标注信息进行转换以便后续训练过程调用。 创建自定义Dataset类继承`torch.utils.data.Dataset`接口,并重写其内部函数完成读取样本路径列表、加载单张图及其对应标签等功能。 ```python from PIL import Image import os.path as osp class MyDataSet(Dataset): def __init__(self, root_dir, anno_file, transform=None): self.root_dir = root_dir self.transform = transform with open(anno_file,'r') as f: lines=f.readlines() self.img_files=[osp.join(root_dir,line.strip().split(' ')[0])for line in lines] self.label_files=[line.strip().split(' ')[1:]for line in lines] def __len__(self):return len(self.img_files) def __getitem__(self,idx): img_path=self.img_files[idx] labels=self.label_files[idx] image = Image.open(img_path).convert("RGB") target={} boxes=torch.as_tensor([[float(i) for i in box.split(',')]for box in labels],dtype=torch.float32) area=(boxes[:,3]-boxes[:,1])*(boxes[:,2]-boxes[:,0]) iscrowd=torch.zeros((boxes.shape[0],),dtype=torch.int64) target["boxes"]=boxes target["labels"]=torch.ones((boxes.shape[0]),dtype=torch.int64)#假设所有类别都是同一类 target["image_id"]=torch.tensor([idx]) target["area"]=area target["iscrowd"]=iscrowd if self.transform!=None:image,target=self.transform(image,target) return image,target ``` #### 四、构建模型结构 基于官方文档说明搭建基础骨干网VGG16作为特征抽取器部分;接着引入Region Proposal Network (RPN),用于生成候选框;最后通过RoI Pooling层连接到分类回归子网络完成最终预测输出。 ```python model=models.detection.fasterrcnn_resnet50_fpn(pretrained=True) in_features=model.roi_heads.box_predictor.cls_score.in_features model.roi_heads.box_predictor=FasterRCNNPredictor(in_features,num_classes=len(CLASSES)) ``` #### 五、设置超参数与优化策略 调整学习率衰减机制、权重初始化方式等细节有助于提高收敛速度及泛化能力。同时考虑到GPU显存限制因素可适当减少batch size大小以适应不同硬件条件下的实验需求。 ```python device='cuda'if torch.cuda.is_available()else 'cpu' num_epochs=10 lr=0.005 momentum=0.9 weight_decay=0.0005 optimizer=torch.optim.SGD(model.parameters(),lr,momentum=momentum, weight_decay=weight_decay,nesterov=True) scheduler=torch.optim.lr_scheduler.StepLR(optimizer,step_size=3,gamma=0.1) ``` #### 六、启动训练流程 编写循环迭代逻辑控制整个训练周期内的前向传播计算损失值反传更新权值等一系列动作直至满足停止准则为止。 ```python def train_one_epoch(model,data_loader,optimizer,device,scheduler=None): model.train() losses_avg=[] for images,targets in tqdm(data_loader): images=list(image.to(device)for image in images) targets=[{k:v.to(device)for k,v in t.items()}for t in targets] loss_dict=model(images,targets) losses=sum(loss for loss in loss_dict.values()) optimizer.zero_grad() losses.backward() optimizer.step() losses_reduced=synchronize_losses(losses) losses_avg.append(losses_reduced.item()) scheduler.step() return np.mean(losses_avg) for epoch in range(num_epochs): mean_loss=train_one_epoch(model,dataloader_train,optimizer,device,scheduler) print(f"Epoch {epoch}/{num_epochs}, Loss:{mean_loss:.4f}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值