Pointnet++改进:更换不同的激活函数,打造更优性能

2024-01-02 16:12

本文主要是介绍Pointnet++改进:更换不同的激活函数,打造更优性能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

简介:
1.该教程提供大量的首发改进的方式,降低上手难度,多种结构改进,助力寻找创新点!
2.本篇文章对Pointnet++进行激活函数的改进,助力解决RELU激活函数缺陷。
3.专栏持续更新,紧随最新的研究内容。


文章目录

  • 步骤一
  • 步骤二
  • 步骤三


代码地址

步骤一

新建activate.py文件,我存放在新建的block目录下,加入以下代码:

# Activation functionsimport torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np# SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
class SiLU(nn.Module):  # export-friendly version of nn.SiLU()@staticmethoddef forward(x):return x * torch.sigmoid(x)class Hardswish(nn.Module):  # export-friendly version of nn.Hardswish()@staticmethoddef forward(x):# return x * F.hardsigmoid(x)  # for torchscript and CoreMLreturn x * F.hardtanh(x + 3, 0., 6.) / 6.  # for torchscript, CoreML and ONNXclass MemoryEfficientSwish(nn.Module):class F(torch.autograd.Function):@staticmethoddef forward(ctx, x):ctx.save_for_backward(x)return x * torch.sigmoid(x)@staticmethoddef backward(ctx, grad_output):x = ctx.saved_tensors[0]sx = torch.sigmoid(x)return grad_output * (sx * (1 + x * (1 - sx)))def forward(self, x):return self.F.apply(x)# Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
class Mish(nn.Module):@staticmethoddef forward(x):return x * F.softplus(x).tanh()class MemoryEfficientMish(nn.Module):class F(torch.autograd.Function):@staticmethoddef forward(ctx, x):ctx.save_for_backward(x)return x.mul(torch.tanh(F.softplus(x)))  # x * tanh(ln(1 + aconcxunlian(x)))@staticmethoddef backward(ctx, grad_output):x = ctx.saved_tensors[0]sx = torch.sigmoid(x)fx = F.softplus(x).tanh()return grad_output * (fx + x * sx * (1 - fx * fx))def forward(self, x):return self.F.apply(x)# FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
class FReLU(nn.Module):def __init__(self, c1, k=3):  # ch_in, kernelsuper().__init__()self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)self.bn = nn.BatchNorm2d(c1)def forward(self, x):return torch.max(x, self.bn(self.conv(x)))class GELU(nn.Module):def __init__(self):super(GELU, self).__init__()def forward(self, x):return 0.5 * x * (1 + torch.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))#
class MetaAconC(nn.Module):r""" ACON activation (activate or not).MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small networkaccording to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>."""def __init__(self, c1, k=1, s=1, r=16):  # ch_in, kernel, stride, rsuper().__init__()c2 = max(r, c1 // r)self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)# self.bn1 = nn.BatchNorm2d(c2)# self.bn2 = nn.BatchNorm2d(c1)def forward(self, x):y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)# batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891# beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y)))))  # bug/unstablebeta = torch.sigmoid(self.fc2(self.fc1(y)))  # bug patch BN layers removeddpx = (self.p1 - self.p2) * xreturn dpx * torch.sigmoid(beta * dpx) + self.p2 * x
###
class AconC(nn.Module):"""ACON https://arxiv.org/pdf/2009.04759.pdfACON activation (activate or not).AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameteraccording to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>."""def __init__(self, c1):super().__init__()self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))def forward(self, x):dpx = (self.p1 - self.p2) * xreturn dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x

步骤二

在models/pointnet2_utils.py中加入以下代码,该代码将PointNetSetAbstraction中的mlp三层感知机重新封装成一个class Conv模块,便于直接在Conv模块中修改激活函数,修改后的代码和源码结构是一致的。修改不同的激活函数直接在Conv类中修改即可。
PointNetSetAbstraction结构图如下,PointNetSetAbstractionMSG比PointNetSetAbstraction多一个不同尺度的三层mlp,其他结构是一样的。
在这里插入图片描述

class Conv(nn.Module):# Standard convolutiondef __init__(self, c1, c2, k=1):  # ch_in, ch_out, kernel, stride, padding, groupssuper(Conv, self).__init__()self.conv = nn.Conv2d(c1, c2, k)self.bn = nn.BatchNorm2d(c2)#self.act = nn.SiLU()#self.act = nn.LeakyReLU(0.1)self.act = nn.ReLU()#self.act = MetaAconC(c2)#self.act = AconC(c2)#self.act = Mish()#self.act = Hardswish()#self.act = FReLU(c2)def forward(self, x):return self.act(self.bn(self.conv(x)))def fuseforward(self, x):return self.act(self.conv(x))class PointNetSetAbstractionAttention(nn.Module):def __init__(self, npoint, radius, nsample, in_channel, mlp, group_all):super(PointNetSetAbstractionAttention, self).__init__()self.npoint = npointself.radius = radiusself.nsample = nsample#self.mlp_convs = nn.ModuleList()self.mlp_conv1 = Conv(in_channel,mlp[0],1)self.mlp_attention = CBAM(mlp[0])self.mlp_conv2 = Conv(mlp[0],mlp[1],1)self.mlp_conv3 = Conv(mlp[1],mlp[2],1)self.group_all = group_alldef forward(self, xyz, points):"""Input:xyz: input points position data, [B, C, N]points: input points data, [B, D, N]Return:new_xyz: sampled points position data, [B, C, S]new_points_concat: sample points feature data, [B, D', S]"""xyz = xyz.permute(0, 2, 1)if points is not None:points = points.permute(0, 2, 1)if self.group_all:new_xyz, new_points = sample_and_group_all(xyz, points)else:new_xyz, new_points = sample_and_group(self.npoint, self.radius, self.nsample, xyz, points)# new_xyz: sampled points position data, [B, npoint, C]# new_points: sampled points data, [B, npoint, nsample, C+D]new_points = new_points.permute(0, 3, 2, 1)  # [B, C+D, nsample,npoint]new_points=self.mlp_conv1(new_points)new_points = self.mlp_attention(new_points)new_points = self.mlp_conv2(new_points)new_points = self.mlp_conv3(new_points)new_points = torch.max(new_points, 2)[0]new_xyz = new_xyz.permute(0, 2, 1)return new_xyz, new_pointsclass PointNetSetAbstractionMsgAttention(nn.Module):def __init__(self, npoint, radius_list, nsample_list, in_channel, mlp_list):super(PointNetSetAbstractionMsgAttention, self).__init__()self.npoint = npointself.radius_list = radius_listself.nsample_list = nsample_listself.mlp_conv00 = Conv(in_channel+3,mlp_list[0][0],1)self.mlp_conv01 = Conv(mlp_list[0][0],mlp_list[0][1],1)self.mlp_conv02 = Conv(mlp_list[0][1],mlp_list[0][2],1)self.mlp_conv10 = Conv(in_channel+3,mlp_list[1][0],1)self.mlp_conv11 = Conv(mlp_list[1][0],mlp_list[1][1],1)self.mlp_conv12 = Conv(mlp_list[1][1],mlp_list[1][2],1)# self.conv_blocks = nn.ModuleList()# self.bn_blocks = nn.ModuleList()# for i in range(len(mlp_list)):#     convs = nn.ModuleList()#     bns = nn.ModuleList()#     last_channel = in_channel + 3#     for out_channel in mlp_list[i]:#         convs.append(nn.Conv2d(last_channel, out_channel, 1))#         bns.append(nn.BatchNorm2d(out_channel))#         last_channel = out_channel#     self.conv_blocks.append(convs)#     self.bn_blocks.append(bns)def forward(self, xyz, points):"""Input:xyz: input points position data, [B, C, N]points: input points data, [B, D, N]Return:new_xyz: sampled points position data, [B, C, S]new_points_concat: sample points feature data, [B, D', S]"""xyz = xyz.permute(0, 2, 1)if points is not None:points = points.permute(0, 2, 1)B, N, C = xyz.shapeS = self.npointnew_xyz = index_points(xyz, farthest_point_sample(xyz, S))new_points_list = []for i, radius in enumerate(self.radius_list):K = self.nsample_list[i]group_idx = query_ball_point(radius, K, xyz, new_xyz)grouped_xyz = index_points(xyz, group_idx)grouped_xyz -= new_xyz.view(B, S, 1, C)if points is not None:grouped_points = index_points(points, group_idx)grouped_points = torch.cat([grouped_points, grouped_xyz], dim=-1)else:grouped_points = grouped_xyzgrouped_points = grouped_points.permute(0, 3, 2, 1)  # [B, D, K, S]if i==0:grouped_points =self.mlp_conv00(grouped_points)grouped_points = self.mlp_conv01(grouped_points)grouped_points = self.mlp_conv02(grouped_points)else:grouped_points = self.mlp_conv10(grouped_points)grouped_points = self.mlp_conv11(grouped_points)grouped_points = self.mlp_conv12(grouped_points)# for j in range(len(self.conv_blocks[i])):#     conv = self.conv_blocks[i][j]#     bn = self.bn_blocks[i][j]#     grouped_points =  F.relu(bn(conv(grouped_points)))new_points = torch.max(grouped_points, 2)[0]  # [B, D', S]new_points_list.append(new_points)new_xyz = new_xyz.permute(0, 2, 1)new_points_concat = torch.cat(new_points_list, dim=1)return new_xyz, new_points_concat

步骤三

在不同的模型中修改调用即可,如在models/pointnet2_sem_seg.py文件中修改,训练即可

import torch.nn as nn
import torch.nn.functional as F
# from models.pointnet2_utils import PointNetSetAbstraction, PointNetFeaturePropagation, PointNetSetAbstractionKPconv, \
#     PointNetSetAbstractionAttention
from models.pointnet2_utils import *class get_model(nn.Module):def __init__(self, num_classes):super(get_model, self).__init__()self.sa1 = PointNetSetAbstractionAttention(1024, 0.1, 32, 9 + 3, [32, 32, 64], False)self.sa2 = PointNetSetAbstraction(256, 0.2, 32, 64 + 3, [64, 64, 128], False)self.sa3 = PointNetSetAbstraction(64, 0.4, 32, 128 + 3, [128, 128, 256], False)self.sa4 = PointNetSetAbstraction(16, 0.8, 32, 256 + 3, [256, 256, 512], False)self.fp4 = PointNetFeaturePropagation(768, [256, 256])self.fp3 = PointNetFeaturePropagation(384, [256, 256])self.fp2 = PointNetFeaturePropagation(320, [256, 128])self.fp1 = PointNetFeaturePropagation(128, [128, 128, 128])self.conv1 = nn.Conv1d(128, 128, 1)self.bn1 = nn.BatchNorm1d(128)self.drop1 = nn.Dropout(0.5)self.conv2 = nn.Conv1d(128, num_classes, 1)def forward(self, xyz):l0_points = xyzl0_xyz = xyz[:,:3,:]l1_xyz, l1_points = self.sa1(l0_xyz, l0_points)l2_xyz, l2_points = self.sa2(l1_xyz, l1_points)l3_xyz, l3_points = self.sa3(l2_xyz, l2_points)l4_xyz, l4_points = self.sa4(l3_xyz, l3_points)l3_points = self.fp4(l3_xyz, l4_xyz, l3_points, l4_points)l2_points = self.fp3(l2_xyz, l3_xyz, l2_points, l3_points)l1_points = self.fp2(l1_xyz, l2_xyz, l1_points, l2_points)l0_points = self.fp1(l0_xyz, l1_xyz, None, l1_points)x = self.drop1(F.relu(self.bn1(self.conv1(l0_points))))x = self.conv2(x)x = F.log_softmax(x, dim=1)x = x.permute(0, 2, 1)return x, l4_pointsclass get_loss(nn.Module):def __init__(self):super(get_loss, self).__init__()self.gamma=2def forward(self, pred, target, trans_feat, weight):#pred: 模型预测的输出   target: 真实的标签或数据,用于计算损失total_loss = F.nll_loss(pred, target, weight=weight)return total_loss
if __name__ == '__main__':import  torchmodel = get_model(13)xyz = torch.rand(6, 9, 2048)(model(xyz))

这篇关于Pointnet++改进:更换不同的激活函数,打造更优性能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/562972

相关文章

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.

用Java打造简易计算器的实现步骤

《用Java打造简易计算器的实现步骤》:本文主要介绍如何设计和实现一个简单的Java命令行计算器程序,该程序能够执行基本的数学运算(加、减、乘、除),文中通过代码介绍的非常详细,需要的朋友可以参考... 目录目标:一、项目概述与功能规划二、代码实现步骤三、测试与优化四、总结与收获总结目标:简单计算器,设计

macOS怎么轻松更换App图标? Mac电脑图标更换指南

《macOS怎么轻松更换App图标?Mac电脑图标更换指南》想要给你的Mac电脑按照自己的喜好来更换App图标?其实非常简单,只需要两步就能搞定,下面我来详细讲解一下... 虽然 MACOS 的个性化定制选项已经「缩水」,不如早期版本那么丰富,www.chinasem.cn但我们仍然可以按照自己的喜好来更换

Oracle的to_date()函数详解

《Oracle的to_date()函数详解》Oracle的to_date()函数用于日期格式转换,需要注意Oracle中不区分大小写的MM和mm格式代码,应使用mi代替分钟,此外,Oracle还支持毫... 目录oracle的to_date()函数一.在使用Oracle的to_date函数来做日期转换二.日

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

正则表达式高级应用与性能优化记录

《正则表达式高级应用与性能优化记录》本文介绍了正则表达式的高级应用和性能优化技巧,包括文本拆分、合并、XML/HTML解析、数据分析、以及性能优化方法,通过这些技巧,可以更高效地利用正则表达式进行复杂... 目录第6章:正则表达式的高级应用6.1 模式匹配与文本处理6.1.1 文本拆分6.1.2 文本合并6

C++11的函数包装器std::function使用示例

《C++11的函数包装器std::function使用示例》C++11引入的std::function是最常用的函数包装器,它可以存储任何可调用对象并提供统一的调用接口,以下是关于函数包装器的详细讲解... 目录一、std::function 的基本用法1. 基本语法二、如何使用 std::function

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

性能测试介绍

性能测试是一种测试方法,旨在评估系统、应用程序或组件在现实场景中的性能表现和可靠性。它通常用于衡量系统在不同负载条件下的响应时间、吞吐量、资源利用率、稳定性和可扩展性等关键指标。 为什么要进行性能测试 通过性能测试,可以确定系统是否能够满足预期的性能要求,找出性能瓶颈和潜在的问题,并进行优化和调整。 发现性能瓶颈:性能测试可以帮助发现系统的性能瓶颈,即系统在高负载或高并发情况下可能出现的问题