欢迎访问 生活随笔!

ag凯发k8国际

当前位置: ag凯发k8国际 > 人工智能 > 目标检测 >内容正文

目标检测

深度学习和目标检测系列教程 11-ag凯发k8国际

发布时间:2024/10/8 目标检测 0 豆豆
ag凯发k8国际 收集整理的这篇文章主要介绍了 深度学习和目标检测系列教程 11-300:小麦数据集训练faster-rcnn模型 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

@author:runsen

上次训练的faster-rcnn的数据格式是xml和jpg图片提供,在很多object-detection中,数据有的是csv格式,

  • 数据集来源:https://www.kaggle.com/c/global-wheat-detection

width和heigth是图片的长和宽,bbox是框的位置。

我们需要在小麦植物的室外图像中检测小麦头,分类的类别只有一个。

我们来看一个牛逼人的做法:https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train

这次使用torch训练faster-rcnn和之前的没有什么不一样。

import pandas as pd import numpy as np import cv2 import os import refrom pil import imageimport albumentations as a from albumentations.pytorch.transforms import totensorv2import torch import torchvisionfrom torchvision.models.detection.faster_rcnn import fastrcnnpredictor from torchvision.models.detection import fasterrcnn from torchvision.models.detection.rpn import anchorgeneratorfrom torch.utils.data import dataloader, dataset from torch.utils.data.sampler import sequentialsamplerfrom matplotlib import pyplot as pltdir_input = '/kaggle/input/global-wheat-detection' dir_train = f'{dir_input}/train' dir_test = f'{dir_input}/test'train_df = pd.read_csv(f'{dir_input}/train.csv')train_df['x'] = -1 train_df['y'] = -1 train_df['w'] = -1 train_df['h'] = -1def expand_bbox(x):r = np.array(re.findall("([0-9] [.]?[0-9]*)", x))if len(r) == 0:r = [-1, -1, -1, -1]return r # 读取'x', 'y', 'w', 'h' train_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x))) train_df.drop(columns=['bbox'], inplace=true) train_df['x'] = train_df['x'].astype(np.float) train_df['y'] = train_df['y'].astype(np.float) train_df['w'] = train_df['w'].astype(np.float) train_df['h'] = train_df['h'].astype(np.float)image_ids = train_df['image_id'].unique() valid_ids = image_ids[-665:] train_ids = image_ids[:-665]# albumentations def get_train_transform():return a.compose([a.flip(0.5),totensorv2(p=1.0)], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})def get_valid_transform():return a.compose([totensorv2(p=1.0)], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})# load a model; pre-trained on coco model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=true)num_classes = 2 # 1 class (wheat) background# get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features# replace the pre-trained head with a new one model.roi_heads.box_predictor = fastrcnnpredictor(in_features, num_classes)

不同的是定义了averager类,这一个类来保存对应的loss。

device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') images, targets, image_ids = next(iter(train_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] boxes = targets[2]['boxes'].cpu().numpy().astype(np.int32) sample = images[2].permute(1,2,0).cpu().numpy()fig, ax = plt.subplots(1, 1, figsize=(16, 8))for box in boxes:cv2.rectangle(sample,(box[0], box[1]),(box[2], box[3]),(220, 0, 0), 3)ax.set_axis_off() ax.imshow(sample) model.to(device) params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.sgd(params, lr=0.005, momentum=0.9, weight_decay=0.0005) # lr_scheduler = torch.optim.lr_scheduler.steplr(optimizer, step_size=3, gamma=0.1) lr_scheduler = nonenum_epochs = 2loss_hist = averager() itr = 1for epoch in range(num_epochs):loss_hist.reset()for images, targets, image_ids in train_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())loss_value = losses.item()loss_hist.send(loss_value)optimizer.zero_grad()losses.backward()optimizer.step()if itr % 50 == 0:print(f"iteration #{itr} loss: {loss_value}")itr = 1# update the learning rateif lr_scheduler is not none:lr_scheduler.step()print(f"epoch #{epoch} loss: {loss_hist.value}") images, targets, image_ids = next(iter(valid_data_loader)) images = list(img.to(device) for img in images) targets = [{k: v.to(device) for k, v in t.items()} for t in targets] boxes = targets[1]['boxes'].cpu().numpy().astype(np.int32) sample = images[1].permute(1,2,0).cpu().numpy() model.eval() cpu_device = torch.device("cpu")outputs = model(images) outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs] fig, ax = plt.subplots(1, 1, figsize=(16, 8))for box in boxes:cv2.rectangle(sample,(box[0], box[1]),(box[2], box[3]),(220, 0, 0), 3)ax.set_axis_off() ax.imshow(sample) torch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')

这个代码真的值得学习和模仿:
https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是ag凯发k8国际为你收集整理的深度学习和目标检测系列教程 11-300:小麦数据集训练faster-rcnn模型的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得ag凯发k8国际网站内容还不错,欢迎将ag凯发k8国际推荐给好友。

网站地图