DL之RetinaNet:基于RetinaNet算法(keras框架)利用resnet50_coco数据集(.h5文件)实现目标检测

简介: DL之RetinaNet:基于RetinaNet算法(keras框架)利用resnet50_coco数据集(.h5文件)实现目标检测

输出结果

image.png


image.png

image.png

设计思路

更新中


核心代码

def __create_pyramid_features(C3, C4, C5, feature_size=256):

   """ Creates the FPN layers on top of the backbone features.

      在ResNet基础上创建FPN金字塔特征:参照博客的框架图,输入[C3,C4,C5],返回5个特征级别[P3, P4, P5, P6, P7]

      参考博客:https://yunyaniu.blog.csdn.net/article/details/100010853

   Args

       C3           : Feature stage C3 from the backbone.

       C4           : Feature stage C4 from the backbone.

       C5           : Feature stage C5 from the backbone.

       feature_size : The feature size to use for the resulting feature levels.

   Returns

       A list of feature levels [P3, P4, P5, P6, P7].

   """

   # upsample C5 to get P5 from the FPN paper

   P5           = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C5_reduced')(C5)

   P5_upsampled = layers.UpsampleLike(name='P5_upsampled')([P5, C4])

   P5           = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, padding='same', name='P5')(P5)

   # add P5 elementwise to C4

   P4           = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C4_reduced')(C4)

   P4           = keras.layers.Add(name='P4_merged')([P5_upsampled, P4])

   P4_upsampled = layers.UpsampleLike(name='P4_upsampled')([P4, C3])

   P4           = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, padding='same', name='P4')(P4)

   # add P4 elementwise to C3

   P3 = keras.layers.Conv2D(feature_size, kernel_size=1, strides=1, padding='same', name='C3_reduced')(C3)

   P3 = keras.layers.Add(name='P3_merged')([P4_upsampled, P3])

   P3 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=1, padding='same', name='P3')(P3)

   # "P6 is obtained via a 3x3 stride-2 conv on C5"

   P6 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=2, padding='same', name='P6')(C5)

   # "P7 is computed by applying ReLU followed by a 3x3 stride-2 conv on P6"

   P7 = keras.layers.Activation('relu', name='C6_relu')(P6)

   P7 = keras.layers.Conv2D(feature_size, kernel_size=3, strides=2, padding='same', name='P7')(P7)

   return [P3, P4, P5, P6, P7]

def default_submodels(num_classes, num_anchors):

   """ Create a list of default submodels used for object detection.

            两个子模型:目标分类子模型default_classification_model、框回归子模型default_regression_model

   The default submodels contains a regression submodel and a classification submodel.

   Args

       num_classes : Number of classes to use.

       num_anchors : Number of base anchors.

   Returns

       A list of tuple, where the first element is the name of the submodel and the second element is the submodel itself.

   """

   return [

       ('regression', default_regression_model(4, num_anchors)),

       ('classification', default_classification_model(num_classes, num_anchors))

   ]

def __build_model_pyramid(name, model, features):

   """ Applies a single submodel to each FPN level.

       真正的构造金字塔模型

   Args

       name     : Name of the submodel.

       model    : The submodel to evaluate.

       features : The FPN features.

   Returns

       A tensor containing the response from the submodel on the FPN features.

   """

   return keras.layers.Concatenate(axis=1, name=name)([model(f) for f in features])

"""

The default anchor parameters. 默认的anchors参数,组合以后有9个anchors

"""

AnchorParameters.default = AnchorParameters(

   sizes   = [32, 64, 128, 256, 512],

   strides = [8, 16, 32, 64, 128],

   ratios  = np.array([0.5, 1, 2], keras.backend.floatx()),

   scales  = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)], keras.backend.floatx()),

)

def anchor_targets_bbox(

   anchors,

   image_group,

   annotations_group,

   num_classes,

   #negative_overlap和positive_overlap,根据IOU区分

   negative_overlap=0.4,  

   positive_overlap=0.5

):

def focal(alpha=0.25, gamma=2.0):

   """ Create a functor for computing the focal loss.

   Args

       alpha: Scale the focal weight with alpha.

       gamma: Take the power of the focal weight with gamma.

   Returns

       A functor that computes the focal loss using the alpha and gamma.

   """

   def _focal(y_true, y_pred):

       """ Compute the focal loss given the target tensor and the predicted tensor.

       As defined in https://arxiv.org/abs/1708.02002

       Args

           y_true: Tensor of target data from the generator with shape (B, N, num_classes).

           y_pred: Tensor of predicted data from the network with shape (B, N, num_classes).

       Returns

           The focal loss of y_pred w.r.t. y_true.

       """

       labels         = y_true[:, :, :-1]

       anchor_state   = y_true[:, :, -1]  # -1 for ignore, 0 for background, 1 for object

       classification = y_pred

       # filter out "ignore" anchors

       indices        = backend.where(keras.backend.not_equal(anchor_state, -1))

       labels         = backend.gather_nd(labels, indices)

       classification = backend.gather_nd(classification, indices)

       # compute the focal loss

       alpha_factor = keras.backend.ones_like(labels) * alpha

       alpha_factor = backend.where(keras.backend.equal(labels, 1), alpha_factor, 1 - alpha_factor)

       focal_weight = backend.where(keras.backend.equal(labels, 1), 1 - classification, classification)

       focal_weight = alpha_factor * focal_weight ** gamma

     

       #定义分类损失: 权重*原来的交叉熵损失

       cls_loss = focal_weight * keras.backend.binary_crossentropy(labels, classification)

       # compute the normalizer: the number of positive anchors

       normalizer = backend.where(keras.backend.equal(anchor_state, 1))

       normalizer = keras.backend.cast(keras.backend.shape(normalizer)[0], keras.backend.floatx())

       normalizer = keras.backend.maximum(keras.backend.cast_to_floatx(1.0), normalizer)

       return keras.backend.sum(cls_loss) / normalizer

   return _focal

def smooth_l1(sigma=3.0):  #框回归损失采用smooth_l1函数

   """ Create a smooth L1 loss functor.

   Args

       sigma: This argument defines the point where the loss changes from L2 to L1.

   Returns

       A functor for computing the smooth L1 loss given target data and predicted data.

   """

   sigma_squared = sigma ** 2

   def _smooth_l1(y_true, y_pred):

       """ Compute the smooth L1 loss of y_pred w.r.t. y_true.

       Args

           y_true: Tensor from the generator of shape (B, N, 5). The last value for each box is the state of the anchor (ignore, negative, positive).

           y_pred: Tensor from the network of shape (B, N, 4).

       Returns

           The smooth L1 loss of y_pred w.r.t. y_true.

       """

       # separate target and state

       regression        = y_pred

       regression_target = y_true[:, :, :-1]

       anchor_state      = y_true[:, :, -1]

       # filter out "ignore" anchors

       indices           = backend.where(keras.backend.equal(anchor_state, 1))

       regression        = backend.gather_nd(regression, indices)

       regression_target = backend.gather_nd(regression_target, indices)

       # compute smooth L1 loss

       # f(x) = 0.5 * (sigma * x)^2          if |x| < 1 / sigma / sigma

       #        |x| - 0.5 / sigma / sigma    otherwise

       regression_diff = regression - regression_target

       regression_diff = keras.backend.abs(regression_diff)

       regression_loss = backend.where(

           keras.backend.less(regression_diff, 1.0 / sigma_squared),

           0.5 * sigma_squared * keras.backend.pow(regression_diff, 2),

           regression_diff - 0.5 / sigma_squared

       )

       # compute the normalizer: the number of positive anchors

       normalizer = keras.backend.maximum(1, keras.backend.shape(indices)[0])

       normalizer = keras.backend.cast(normalizer, dtype=keras.backend.floatx())

       return keras.backend.sum(regression_loss) / normalizer

   return _smooth_l1


相关文章
|
10天前
|
机器学习/深度学习 存储 算法
解锁文件共享软件背后基于 Python 的二叉搜索树算法密码
文件共享软件在数字化时代扮演着连接全球用户、促进知识与数据交流的重要角色。二叉搜索树作为一种高效的数据结构,通过有序存储和快速检索文件,极大提升了文件共享平台的性能。它依据文件名或时间戳等关键属性排序,支持高效插入、删除和查找操作,显著优化用户体验。本文还展示了用Python实现的简单二叉搜索树代码,帮助理解其工作原理,并展望了该算法在分布式计算和机器学习领域的未来应用前景。
|
3天前
|
算法 数据安全/隐私保护 计算机视觉
基于FPGA的图像双线性插值算法verilog实现,包括tb测试文件和MATLAB辅助验证
本项目展示了256×256图像通过双线性插值放大至512×512的效果,无水印展示。使用Matlab 2022a和Vivado 2019.2开发,提供完整代码及详细中文注释、操作视频。核心程序实现图像缩放,并在Matlab中验证效果。双线性插值算法通过FPGA高效实现图像缩放,确保质量。
|
3月前
|
机器学习/深度学习 算法 数据挖掘
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构。本文介绍了K-means算法的基本原理,包括初始化、数据点分配与簇中心更新等步骤,以及如何在Python中实现该算法,最后讨论了其优缺点及应用场景。
193 6
|
20天前
|
机器学习/深度学习 算法 数据可视化
利用SVM(支持向量机)分类算法对鸢尾花数据集进行分类
本文介绍了如何使用支持向量机(SVM)算法对鸢尾花数据集进行分类。作者通过Python的sklearn库加载数据,并利用pandas、matplotlib等工具进行数据分析和可视化。
136 70
|
12天前
|
存储 算法 Java
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。
|
6月前
|
搜索推荐 前端开发 数据可视化
【优秀python web毕设案例】基于协同过滤算法的酒店推荐系统,django框架+bootstrap前端+echarts可视化,有后台有爬虫
本文介绍了一个基于Django框架、协同过滤算法、ECharts数据可视化以及Bootstrap前端技术的酒店推荐系统,该系统通过用户行为分析和推荐算法优化,提供个性化的酒店推荐和直观的数据展示,以提升用户体验。
239 1
【优秀python web毕设案例】基于协同过滤算法的酒店推荐系统,django框架+bootstrap前端+echarts可视化,有后台有爬虫
|
1月前
|
存储 算法 Serverless
剖析文件共享工具背后的Python哈希表算法奥秘
在数字化时代,文件共享工具不可或缺。哈希表算法通过将文件名或哈希值映射到存储位置,实现快速检索与高效管理。Python中的哈希表可用于创建简易文件索引,支持快速插入和查找文件路径。哈希表不仅提升了文件定位速度,还优化了存储管理和多节点数据一致性,确保文件共享工具高效运行,满足多用户并发需求,推动文件共享领域向更高效、便捷的方向发展。
|
1月前
|
存储 算法 安全
基于哈希表的文件共享平台 C++ 算法实现与分析
在数字化时代,文件共享平台不可或缺。本文探讨哈希表在文件共享中的应用,包括原理、优势及C++实现。哈希表通过键值对快速访问文件元数据(如文件名、大小、位置等),查找时间复杂度为O(1),显著提升查找速度和用户体验。代码示例展示了文件上传和搜索功能,实际应用中需解决哈希冲突、动态扩容和线程安全等问题,以优化性能。
|
5月前
|
机器学习/深度学习 人工智能 算法
鸟类识别系统Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+ResNet50算法模型+图像识别
鸟类识别系统。本系统采用Python作为主要开发语言,通过使用加利福利亚大学开源的200种鸟类图像作为数据集。使用TensorFlow搭建ResNet50卷积神经网络算法模型,然后进行模型的迭代训练,得到一个识别精度较高的模型,然后在保存为本地的H5格式文件。在使用Django开发Web网页端操作界面,实现用户上传一张鸟类图像,识别其名称。
163 12
鸟类识别系统Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+ResNet50算法模型+图像识别
|
3月前
|
算法
”回溯算法“框架及练习题
”回溯算法“框架及练习题
58 0

热门文章

最新文章