当前位置: 首页 > news >正文

海淀中小企业网站开发wordpress如何设置评论页面

海淀中小企业网站开发,wordpress如何设置评论页面,wordpress 一小时建站,航佳网站建设一、本文介绍 本篇文章的内容是在大家得到一个改进版本的C2f一个新的注意力机制、或者一个新的卷积模块、或者是检测头的时候如何替换我们YOLOv8模型中的原有的模块#xff0c;从而用你的模块去进行训练模型或者检测。因为最近开了一个专栏里面涉及到挺多改进的地方#xff…一、本文介绍 本篇文章的内容是在大家得到一个改进版本的C2f一个新的注意力机制、或者一个新的卷积模块、或者是检测头的时候如何替换我们YOLOv8模型中的原有的模块从而用你的模块去进行训练模型或者检测。因为最近开了一个专栏里面涉及到挺多改进的地方不能每篇文章都去讲解一遍如何修改就想着在这里单独出一期文章进行一个总结性教程大家可以从我的其它文章中拿到修改后的代码从这篇文章学会如何去添加到你的模型结构中去。 YOLOv8专栏YOLOv8改进有效涨点专栏-持续复现各种最新机制 本文的讲解举例都以最新的YOLOv8的目录结构为例老版本的其实方法都一样只是目录构造不一样找到同样的文件名即可。  适用对象-本文适合那些拿到源码却不知道如何添加到网络结构中的朋友 目录 一、本文介绍 二、导入修改内容 2.1创建新文件导入新模块 2.1.1情况一 2.1.2情况二  三、Conv模块 3.1修改一 3.2修改二 3.3修改三  四、C2f、Bottleneck模块 4.1修改一 4.2步骤二  4.3修改三 4.4修改四 4.5修改五 4.6修改六 4.7修改七 四、注意力机制 4.1修改一  4.2修改二 4.3修改三 4.2.1有参数的注意力机制修改 4.2.2无参数的注意力机制修改 4.4配置注意力机制 五、Neck部分 六、检测头 七、损失函数 7.1 修改一 7.2 修改二 7.3 修改三 二、导入修改内容 大家拿到任何一个代码想要加入到模型的内部我们都需要先将其导入到模型的内部才可以将其添加到模型的结构中去下面的代码是一个ODConv和我创建的一个ODConv_yolo的类(官方的代码报错进行一定的处理想知道为啥可以看我单独讲解它的博客) 我们先拿其进行举例。 import torch import torch.nn as nn import torch.nn.functional as F import torch.autogradclass Attention(nn.Module):def __init__(self, in_planes, out_planes, kernel_size, groups1, reduction0.0625, kernel_num4, min_channel16):super(Attention, self).__init__()attention_channel max(int(in_planes * reduction), min_channel)self.kernel_size kernel_sizeself.kernel_num kernel_numself.temperature 1.0self.avgpool nn.AdaptiveAvgPool2d(1)self.fc nn.Conv2d(in_planes, attention_channel, 1, biasFalse)self.bn nn.BatchNorm2d(attention_channel)self.relu nn.ReLU(inplaceTrue)self.channel_fc nn.Conv2d(attention_channel, in_planes, 1, biasTrue)self.func_channel self.get_channel_attentionif in_planes groups and in_planes out_planes: # depth-wise convolutionself.func_filter self.skipelse:self.filter_fc nn.Conv2d(attention_channel, out_planes, 1, biasTrue)self.func_filter self.get_filter_attentionif kernel_size 1: # point-wise convolutionself.func_spatial self.skipelse:self.spatial_fc nn.Conv2d(attention_channel, kernel_size * kernel_size, 1, biasTrue)self.func_spatial self.get_spatial_attentionif kernel_num 1:self.func_kernel self.skipelse:self.kernel_fc nn.Conv2d(attention_channel, kernel_num, 1, biasTrue)self.func_kernel self.get_kernel_attentionself._initialize_weights()def _initialize_weights(self):for m in self.modules():if isinstance(m, nn.Conv2d):nn.init.kaiming_normal_(m.weight, modefan_out, nonlinearityrelu)if m.bias is not None:nn.init.constant_(m.bias, 0)if isinstance(m, nn.BatchNorm2d):nn.init.constant_(m.weight, 1)nn.init.constant_(m.bias, 0)def update_temperature(self, temperature):self.temperature temperaturestaticmethoddef skip(_):return 1.0def get_channel_attention(self, x):channel_attention torch.sigmoid(self.channel_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)return channel_attentiondef get_filter_attention(self, x):filter_attention torch.sigmoid(self.filter_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)return filter_attentiondef get_spatial_attention(self, x):spatial_attention self.spatial_fc(x).view(x.size(0), 1, 1, 1, self.kernel_size, self.kernel_size)spatial_attention torch.sigmoid(spatial_attention / self.temperature)return spatial_attentiondef get_kernel_attention(self, x):kernel_attention self.kernel_fc(x).view(x.size(0), -1, 1, 1, 1, 1)kernel_attention F.softmax(kernel_attention / self.temperature, dim1)return kernel_attentiondef forward(self, x):x self.avgpool(x)x self.fc(x)# x self.bn(x) # 在外面我提供了一个bn这里会报错x self.relu(x)return self.func_channel(x), self.func_filter(x), self.func_spatial(x), self.func_kernel(x)class ODConv2d(nn.Module):def __init__(self, in_planes, out_planes, kernel_size, stride1, padding1, dilation1, groups1,reduction0.0625, kernel_num4):super(ODConv2d, self).__init__()kernel_size kernel_size[0]in_planes in_planesself.in_planes in_planesself.out_planes out_planesself.kernel_size kernel_sizeself.stride strideself.padding paddingself.dilation dilationself.groups groupsself.kernel_num kernel_numself.attention Attention(in_planes, out_planes, kernel_size, groupsgroups,reductionreduction, kernel_numkernel_num)self.weight nn.Parameter(torch.randn(kernel_num, out_planes, in_planes//groups, kernel_size, kernel_size),requires_gradTrue)self._initialize_weights()if self.kernel_size 1 and self.kernel_num 1:self._forward_impl self._forward_impl_pw1xelse:self._forward_impl self._forward_impl_commondef _initialize_weights(self):for i in range(self.kernel_num):nn.init.kaiming_normal_(self.weight[i], modefan_out, nonlinearityrelu)def update_temperature(self, temperature):self.attention.update_temperature(temperature)def _forward_impl_common(self, x):# Multiplying channel attention (or filter attention) to weights and feature maps are equivalent,# while we observe that when using the latter method the models will run faster with less gpu memory cost.channel_attention, filter_attention, spatial_attention, kernel_attention self.attention(x)batch_size, in_planes, height, width x.size()x x * channel_attentionx x.reshape(1, -1, height, width)aggregate_weight spatial_attention * kernel_attention * self.weight.unsqueeze(dim0)aggregate_weight torch.sum(aggregate_weight, dim1).view([-1, self.in_planes // self.groups, self.kernel_size, self.kernel_size])output F.conv2d(x, weightaggregate_weight, biasNone, strideself.stride, paddingself.padding,dilationself.dilation, groupsself.groups * batch_size)output output.view(batch_size, self.out_planes, output.size(-2), output.size(-1))output output * filter_attentionreturn outputdef _forward_impl_pw1x(self, x):channel_attention, filter_attention, spatial_attention, kernel_attention self.attention(x)x x * channel_attentionoutput F.conv2d(x, weightself.weight.squeeze(dim0), biasNone, strideself.stride, paddingself.padding,dilationself.dilation, groupsself.groups)output output * filter_attentionreturn outputdef forward(self, x):return self._forward_impl(x) 拿到这种代码之后一般都很长有一些博主推荐直接将其复制粘贴到YOLOv8的ultralytics/nn/modules/conv.py或者ultralytics/nn/modules/block.py目录下面这种方法可不可以答案是可以的但是我建议大家最好新建一个文件在conv.py的同级目录下为什么这么做因为我们修改的模块越来越多你往conv.py文件或则block.py文件里面加的代码越来越多很容易就把代码改崩溃了最后就跌卸载进行重新下载包我们通过建立文件导入其中类的形式如果我们不用了也不会对我们的代码做出任何影响实在不行把新建立的文件删除了都可以下面开始进行实际操作的讲解。 2.1创建新文件导入新模块 我们将我们得到的任何一个Conv或者想要修改的任何一个模块都可以像下面的图片一样直接建立一个文件复制粘贴进去即可。 建立好上面的文件之后我们此时呢有两种情况一周呢官方的代码可以直接使用另一种呢需要进行一定的处理我们下面分别进行讲解两种情况。 2.1.1情况一 这种情况是官方的代码可以直接使用此时我们直接修改ultralytics/nn/modules/__init__.py文件就可以了修改如下- 2.1.2情况二  另一种情况(绝大多数)官方的代码不能直接使用我们本文的例子ODConv就是这种情况所以我们需要对其进行一定的处理我们找到如下的文件-ultralytics/nn/modules/conv.py对其进行修改如下-   修改一、导入模块 修改二、将额外处理代码添加至conv模块  将如下代码添加至该文件中的末尾处-  class ODConv2d_yolo(nn.Module):def __init__(self, in_channels, out_channels, kernel_size1, stride1, groups1, dilation1):super().__init__()self.conv Conv(in_channels, out_channels, k1)self.dcnv3 ODConv2d(out_channels,out_channels, kernel_sizekernel_size, stridestride, groupsgroups,dilationdilation)self.bn nn.BatchNorm2d(out_channels)self.gelu nn.GELU()def forward(self, x):x self.conv(x)x self.dcnv3(x)x self.gelu(self.bn(x))return x修改三、配置头文件 修改如下- 修改四 、重复情况一的步骤 修改ultralytics/nn/modules/__init__.py文件如下 总结通过建立文件这种方法导入想要加入到模型中的模块(这里举例的是ODConv2d)其已经在我们新创建的.py文件中定义好了然后直接导过来就可以用了从而不修改原有的conv.py文件就做到了这样就算我们随时不用了直接删除文件然后需要改的地方也很直观否则时间久了代码早晚跌崩溃。 三、Conv模块 上面我们已经把定义好的卷积模块代码中了此时我们还需要配置其位置当然不同的模块导入的方式也有可能略有不同。 3.1修改一 我们找到如下的文件ultralytics/nn/tasks.py图片如下- 我们先把我们在上面ultralytics/nn/modules/__init__.py 文件的函数头中导入的类在下面的地方导入进ultralytics/nn/tasks.py文件中修改内容如下-  3.2修改二 我们在这个文件中找到一个方法(def定义的就叫方法)因为其代码很长我们一行一行搜索很麻烦我们适用文件搜索功能(快捷键Ctrl F)弹出快捷栏如下- 我们搜索下面这个代码parse_model 然后进行翻滚很容易就找到了下面的部分同时进行红框内部的修改 3.3修改三  到此我们就已经将我们定义的三个模块添加到我们的模型中了已经可以修改yaml文件进行网络结构的配置了我们找到该文件ultralytics/cfg/models/v8/yolov8.yaml进行配置。 我们可以在其中的任何一个位置进行替换当然我们的替换要符合逻辑类似于之前这个位置是Conv那么你可以将你修改的卷积替换上之前这个位置是C2f那么你就将修改后的C2f替换上。 我们在yaml文件中进行了如下修改。 到此我们就配置完成了此时进行训练就可以开始训练了~ 四、C2f、Bottleneck模块 下面我们拿修改后的C2f、和Bottleneck举例这两个模块定义在该文件中ultralytics/nn/modules/block.py所以如果我们想添加修改后的C2f和Bottleneck(这俩一般配套使用)就需要在该文件中进行修改修改步骤如下- 4.1修改一 找到该文件ultralytics/nn/modules/block.py进行如下修改- 4.2步骤二  添加修改后的C2f和Bottleneck模块这里起名为C2f_ODConv和Bottleneck_ODConv class Bottleneck_ODConv(nn.Module):Standard bottleneck.def __init__(self, c1, c2, shortcutTrue, g1, k(3, 3), e0.5):Initializes a bottleneck module with given input/output channels, shortcut option, group, kernels, andexpansion.super().__init__()c_ int(c2 * e) # hidden channelsself.cv1 Conv(c1, c_, k[0], 1)self.cv2 ODConv2d_yolo(c_, c2, k[1], 1, groupsg)self.add shortcut and c1 c2def forward(self, x):forward() applies the YOLO FPN to input data.return x self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))class C2f_ODConv(nn.Module):Faster Implementation of CSP Bottleneck with 2 convolutions.def __init__(self, c1, c2, n1, shortcutFalse, g1, e0.5):Initialize CSP bottleneck layer with two convolutions with arguments ch_in, ch_out, number, shortcut, groups,expansion.super().__init__()self.c int(c2 * e) # hidden channelsself.cv1 Conv(c1, 2 * self.c, 1, 1)self.cv2 Conv((2 n) * self.c, c2, 1) # optional actFReLU(c2)self.m nn.ModuleList(Bottleneck_ODConv(self.c, self.c, shortcut, g, k((3, 3), (3, 3)), e1.0) for _ in range(n))def forward(self, x):Forward pass through C2f layer.y list(self.cv1(x).chunk(2, 1))y.extend(m(y[-1]) for m in self.m)return self.cv2(torch.cat(y, 1))def forward_split(self, x):Forward pass using split() instead of chunk().y list(self.cv1(x).split((self.c, self.c), 1))y.extend(m(y[-1]) for m in self.m)return self.cv2(torch.cat(y, 1)) 将以上代码复制到文件ultralytics/nn/modules/block.py的末尾  4.3修改三 修改头文件如下- 4.4修改四 找到文件ultralytics/nn/modules/__init__.py修改如下- 4.5修改五 找到该文件我们找到如下的文件ultralytics/nn/tasks.py进行修改(其实和卷积模块的一模一样) 4.6修改六 我们在这个文件中找到一个方法(def定义的就叫方法)因为其代码很长我们一行一行搜索很麻烦我们适用文件搜索功能(快捷键Ctrl F)弹出快捷栏如下- 我们搜索下面这个代码parse_model 然后进行翻滚很容易就找到了下面的部分同时进行红框内部的修改 4.7修改七 到此我们就已经将我们定义的三个模块添加到我们的模型中了已经可以修改yaml文件进行网络结构的配置了我们找到该文件ultralytics/cfg/models/v8/yolov8.yaml进行配置。 我们可以在其中的任何一个位置进行替换当然我们的替换要符合逻辑类似于之前这个位置是Conv那么你可以将你修改的卷积替换上之前这个位置是C2f那么你就将修改后的C2f替换上。 在yaml文件中进行了如下修改。 到此就完成了修改C2f和Bottleneck模块了已经可以开始进行训练了~ 至于修改这个ODConv的 效果如何可以看我的其它博客里面有详细的讲解~ 四、注意力机制 修改注意力机制的部分其实和上面都是类似只是在修改如下文件的时候有点不一样ultralytics/nn/tasks.py但是需要注意的是注意力机制分为两种一种是有参数的注意力机制我们需要像其中传入参数一种是无参数的注意力机制这两种机制的添加呢稍微有一些不同我会在下面进行标注大家仔细看 4.1修改一  这里我们拿Biformer注意力机制为例(我们拿有参数的注意力机制为例)首先我们找到该目录ultralytics/nn/modules该目录的构造如下- 我们在其中创建一个名字为Biformer的py文件如图所示我们在其中复制如下代码即可 Bi-Level Routing Attention.from typing import Tuple, Optional import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from torch import Tensor, LongTensorclass TopkRouting(nn.Module):differentiable topk routing with scalingArgs:qk_dim: int, feature dimension of query and keytopk: int, the topkqk_scale: int or None, temperature (multiply) of softmax activationwith_param: bool, wether inorporate learnable params in routing unitdiff_routing: bool, wether make routing differentiablesoft_routing: bool, wether make output value multiplied by routing weightsdef __init__(self, qk_dim, topk4, qk_scaleNone, param_routingFalse, diff_routingFalse):super().__init__()self.topk topkself.qk_dim qk_dimself.scale qk_scale or qk_dim ** -0.5self.diff_routing diff_routing# TODO: norm layer before/after linear?self.emb nn.Linear(qk_dim, qk_dim) if param_routing else nn.Identity()# routing activationself.routing_act nn.Softmax(dim-1)def forward(self, query: Tensor, key: Tensor) - Tuple[Tensor]:Args:q, k: (n, p^2, c) tensorReturn:r_weight, topk_index: (n, p^2, topk) tensorif not self.diff_routing:query, key query.detach(), key.detach()query_hat, key_hat self.emb(query), self.emb(key) # per-window pooling - (n, p^2, c)attn_logit (query_hat * self.scale) key_hat.transpose(-2, -1) # (n, p^2, p^2)topk_attn_logit, topk_index torch.topk(attn_logit, kself.topk, dim-1) # (n, p^2, k), (n, p^2, k)r_weight self.routing_act(topk_attn_logit) # (n, p^2, k)return r_weight, topk_indexclass KVGather(nn.Module):def __init__(self, mul_weightnone):super().__init__()assert mul_weight in [none, soft, hard]self.mul_weight mul_weightdef forward(self, r_idx: Tensor, r_weight: Tensor, kv: Tensor):r_idx: (n, p^2, topk) tensorr_weight: (n, p^2, topk) tensorkv: (n, p^2, w^2, c_kqc_v)Return:(n, p^2, topk, w^2, c_kqc_v) tensor# select kv according to routing indexn, p2, w2, c_kv kv.size()topk r_idx.size(-1)# print(r_idx.size(), r_weight.size())# FIXME: gather consumes much memory (topk times redundancy), write cuda kernel?topk_kv torch.gather(kv.view(n, 1, p2, w2, c_kv).expand(-1, p2, -1, -1, -1),# (n, p^2, p^2, w^2, c_kv) without mem cpydim2,indexr_idx.view(n, p2, topk, 1, 1).expand(-1, -1, -1, w2, c_kv)# (n, p^2, k, w^2, c_kv))if self.mul_weight soft:topk_kv r_weight.view(n, p2, topk, 1, 1) * topk_kv # (n, p^2, k, w^2, c_kv)elif self.mul_weight hard:raise NotImplementedError(differentiable hard routing TBA)# else: #none# topk_kv topk_kv # do nothingreturn topk_kvclass QKVLinear(nn.Module):def __init__(self, dim, qk_dim, biasTrue):super().__init__()self.dim dimself.qk_dim qk_dimself.qkv nn.Linear(dim, qk_dim qk_dim dim, biasbias)def forward(self, x):q, kv self.qkv(x).split([self.qk_dim, self.qk_dim self.dim], dim-1)return q, kv# q, k, v self.qkv(x).split([self.qk_dim, self.qk_dim, self.dim], dim-1)# return q, k, vclass BiLevelRoutingAttention(nn.Module):n_win: number of windows in one side (so the actual number of windows is n_win*n_win)kv_per_win: for kv_downsample_modeada_xxxpool only, number of key/values per window. Similar to n_win, the actual number is kv_per_win*kv_per_win.topk: topk for window filteringparam_attention: qkvo-linear for q,k,v and o, none: param free attentionparam_routing: extra linear for routingdiff_routing: wether to set routing differentiablesoft_routing: wether to multiply soft routing weightsdef __init__(self, dim, n_win7, num_heads8, qk_dimNone, qk_scaleNone,kv_per_win4, kv_downsample_ratio4, kv_downsample_kernelNone, kv_downsample_modeidentity,topk4, param_attentionqkvo, param_routingFalse, diff_routingFalse, soft_routingFalse,side_dwconv3,auto_padTrue):super().__init__()# local attention settingself.dim dimself.n_win n_win # Wh, Wwself.num_heads num_headsself.qk_dim qk_dim or dimassert self.qk_dim % num_heads 0 and self.dim % num_heads 0, qk_dim and dim must be divisible by num_heads!self.scale qk_scale or self.qk_dim ** -0.5################side_dwconv (i.e. LCE in ShuntedTransformer)###########self.lepe nn.Conv2d(dim, dim, kernel_sizeside_dwconv, stride1, paddingside_dwconv // 2,groupsdim) if side_dwconv 0 else \lambda x: torch.zeros_like(x)################ global routing setting #################self.topk topkself.param_routing param_routingself.diff_routing diff_routingself.soft_routing soft_routing# routerassert not (self.param_routing and not self.diff_routing) # cannot be with_paramTrue and diff_routingFalseself.router TopkRouting(qk_dimself.qk_dim,qk_scaleself.scale,topkself.topk,diff_routingself.diff_routing,param_routingself.param_routing)if self.soft_routing: # soft routing, always diffrentiable (if no detach)mul_weight softelif self.diff_routing: # hard differentiable routingmul_weight hardelse: # hard non-differentiable routingmul_weight noneself.kv_gather KVGather(mul_weightmul_weight)# qkv mapping (shared by both global routing and local attention)self.param_attention param_attentionif self.param_attention qkvo:self.qkv QKVLinear(self.dim, self.qk_dim)self.wo nn.Linear(dim, dim)elif self.param_attention qkv:self.qkv QKVLinear(self.dim, self.qk_dim)self.wo nn.Identity()else:raise ValueError(fparam_attention mode {self.param_attention} is not surpported!)self.kv_downsample_mode kv_downsample_modeself.kv_per_win kv_per_winself.kv_downsample_ratio kv_downsample_ratioself.kv_downsample_kenel kv_downsample_kernelif self.kv_downsample_mode ada_avgpool:assert self.kv_per_win is not Noneself.kv_down nn.AdaptiveAvgPool2d(self.kv_per_win)elif self.kv_downsample_mode ada_maxpool:assert self.kv_per_win is not Noneself.kv_down nn.AdaptiveMaxPool2d(self.kv_per_win)elif self.kv_downsample_mode maxpool:assert self.kv_downsample_ratio is not Noneself.kv_down nn.MaxPool2d(self.kv_downsample_ratio) if self.kv_downsample_ratio 1 else nn.Identity()elif self.kv_downsample_mode avgpool:assert self.kv_downsample_ratio is not Noneself.kv_down nn.AvgPool2d(self.kv_downsample_ratio) if self.kv_downsample_ratio 1 else nn.Identity()elif self.kv_downsample_mode identity: # no kv downsamplingself.kv_down nn.Identity()elif self.kv_downsample_mode fracpool:# assert self.kv_downsample_ratio is not None# assert self.kv_downsample_kenel is not None# TODO: fracpool# 1. kernel size should be input size dependent# 2. there is a random factor, need to avoid independent sampling for k and vraise NotImplementedError(fracpool policy is not implemented yet!)elif kv_downsample_mode conv:# TODO: need to consider the case where k ! v so that need two downsample modulesraise NotImplementedError(conv policy is not implemented yet!)else:raise ValueError(fkv_down_sample_mode {self.kv_downsaple_mode} is not surpported!)# softmax for local attentionself.attn_act nn.Softmax(dim-1)self.auto_pad auto_paddef forward(self, x, ret_attn_maskFalse):x: NHWC tensorReturn:NHWC tensorx rearrange(x, n c h w - n h w c)# NOTE: use padding for semantic segmentation###################################################if self.auto_pad:N, H_in, W_in, C x.size()pad_l pad_t 0pad_r (self.n_win - W_in % self.n_win) % self.n_winpad_b (self.n_win - H_in % self.n_win) % self.n_winx F.pad(x, (0, 0, # dim-1pad_l, pad_r, # dim-2pad_t, pad_b)) # dim-3_, H, W, _ x.size() # padded sizeelse:N, H, W, C x.size()assert H % self.n_win 0 and W % self.n_win 0 ##################################################### patchify, (n, p^2, w, w, c), keep 2d window as we need 2d pooling to reduce kv sizex rearrange(x, n (j h) (i w) c - n (j i) h w c, jself.n_win, iself.n_win)#################qkv projection#################### q: (n, p^2, w, w, c_qk)# kv: (n, p^2, w, w, c_qkc_v)# NOTE: separte kv if there were memory leak issue caused by gatherq, kv self.qkv(x)# pixel-wise qkv# q_pix: (n, p^2, w^2, c_qk)# kv_pix: (n, p^2, h_kv*w_kv, c_qkc_v)q_pix rearrange(q, n p2 h w c - n p2 (h w) c)kv_pix self.kv_down(rearrange(kv, n p2 h w c - (n p2) c h w))kv_pix rearrange(kv_pix, (n j i) c h w - n (j i) (h w) c, jself.n_win, iself.n_win)q_win, k_win q.mean([2, 3]), kv[..., 0:self.qk_dim].mean([2, 3]) # window-wise qk, (n, p^2, c_qk), (n, p^2, c_qk)##################side_dwconv(lepe)################### NOTE: call contiguous to avoid gradient warning when using ddplepe self.lepe(rearrange(kv[..., self.qk_dim:], n (j i) h w c - n c (j h) (i w), jself.n_win,iself.n_win).contiguous())lepe rearrange(lepe, n c (j h) (i w) - n (j h) (i w) c, jself.n_win, iself.n_win)############ gather q dependent k/v #################r_weight, r_idx self.router(q_win, k_win) # both are (n, p^2, topk) tensorskv_pix_sel self.kv_gather(r_idxr_idx, r_weightr_weight, kvkv_pix) # (n, p^2, topk, h_kv*w_kv, c_qkc_v)k_pix_sel, v_pix_sel kv_pix_sel.split([self.qk_dim, self.dim], dim-1)# kv_pix_sel: (n, p^2, topk, h_kv*w_kv, c_qk)# v_pix_sel: (n, p^2, topk, h_kv*w_kv, c_v)######### do attention as normal ####################k_pix_sel rearrange(k_pix_sel, n p2 k w2 (m c) - (n p2) m c (k w2),mself.num_heads) # flatten to BMLC, (n*p^2, m, topk*h_kv*w_kv, c_kq//m) transpose here?v_pix_sel rearrange(v_pix_sel, n p2 k w2 (m c) - (n p2) m (k w2) c,mself.num_heads) # flatten to BMLC, (n*p^2, m, topk*h_kv*w_kv, c_v//m)q_pix rearrange(q_pix, n p2 w2 (m c) - (n p2) m w2 c,mself.num_heads) # to BMLC tensor (n*p^2, m, w^2, c_qk//m)# param-free multihead attentionattn_weight (q_pix * self.scale) k_pix_sel # (n*p^2, m, w^2, c) (n*p^2, m, c, topk*h_kv*w_kv) - (n*p^2, m, w^2, topk*h_kv*w_kv)attn_weight self.attn_act(attn_weight)out attn_weight v_pix_sel # (n*p^2, m, w^2, topk*h_kv*w_kv) (n*p^2, m, topk*h_kv*w_kv, c) - (n*p^2, m, w^2, c)out rearrange(out, (n j i) m (h w) c - n (j h) (i w) (m c), jself.n_win, iself.n_win,hH // self.n_win, wW // self.n_win)out out lepe# output linearout self.wo(out)# NOTE: use padding for semantic segmentation# crop padded regionif self.auto_pad and (pad_r 0 or pad_b 0):out out[:, :H_in, :W_in, :].contiguous()if ret_attn_mask:return out, r_weight, r_idx, attn_weightelse:return rearrange(out, n h w c - n c h w) 4.2修改二 我们找到该文件ultralytics/nn/tasks.py在其中添加如下一行代码 from ultralytics.nn.modules.Biformer import BiLevelRoutingAttention as Biformer 添加完之后的效果如下图- 4.3修改三 这里需要注意体现出两种注意力机制的修改方式~ 4.2.1有参数的注意力机制修改 现在我们已经将Biformer文件导入了模型中了下一步我们就需要添加该机制到模型中让我们可以使用它我们在步骤二的文件中ultralytics/nn/tasks.py按快捷键CtrlF可以进行文件搜索。 当然如果你不想用快捷键也可以自己寻找大概在 650行左右有一个方法的名字叫parse_model 我们找到该方法对其进行修改添加如下图所示内容。 这里我们定义了一个字典我们以后在想导入其它的注意力机制就可以重复步骤一和步骤二然后在步骤三这里定义的字典中添加你导入的注意力机制名字即可。  4.2.2无参数的注意力机制修改 无参数的注意力机制直接修改完步骤二就可以直接跳过本步骤的修改直接进行配置注意力机制即可无参数的注意力机制的修改三不用进行任何修改~ 4.4配置注意力机制 恭喜你到这里我们就已经成功的导入了注意力机制离修改模型只差最后一步我们需要找到如下文件进行修改ultralytics/cfg/models/v8/yolov8.yaml,找到这个文件之后初始如下所示 我们可以在某一层中添加Biformer注意力机制具体添加到哪里由你自己决定我这里建议添加到  Neck层也就是我们的特征融合层添加之后的效果如下这里我在三个地方添加了Biformer注意力机制。 OK到此我们就添加了注意力机制到我们的模型里面了下面我来讲一下添加的注意力机制中的参数是如何来的 首先-1这里我们不用管 它代表上一个层的输入输入-1就是让模型自动帮我们算输入的大小数字1代表这里我们的Biformer注意力机制执行一次Biformer代表我们的注意力机制名字本来类的名字不是这个我在前面导入的时候给他另命名了前面有讲到[78]这里是根据Biformer定义的时候来的你只需要输入前两个即可(需要注意的是无参数的注意力机制这里什么都不用填写可以看看你的无参数注意力机制需要什么那种超参数你给予赋值即可不用从模型中获取任何的其它参数)。 当然这两个参数你可以换调成其它的试试效果。 五、Neck部分 持续更新~ 六、检测头 持续更新~ 七、损失函数 当我们想要在YOLOv8中添加算是函数时候我们需要进行以下的操作同时我我们引入Focus的思想时候需要进行如何的操作大家可以按照如下的步骤进行操作即可。 我们提供的代码是最新的Inner实现的各种损失的思想给大家进行尝试。 大家可以用下面的代码块一和代码块二进行操作。 代码块一 class Inner_WIoU_Scale: monotonous: {None: origin v1True: monotonic FM v2False: non-monotonic FM v3}momentum: The momentum of running meaniou_mean 1.monotonous False_momentum 1 - 0.5 ** (1 / 7000)_is_train Truedef __init__(self, iou):self.iou iouself._update(self)classmethoddef _update(cls, self):if cls._is_train: cls.iou_mean (1 - cls._momentum) * cls.iou_mean \cls._momentum * self.iou.detach().mean().item()classmethoddef _scaled_loss(cls, self, gamma1.9, delta3):if isinstance(self.monotonous, bool):if self.monotonous:return (self.iou.detach() / self.iou_mean).sqrt()else:beta self.iou.detach() / self.iou_meanalpha delta * torch.pow(gamma, beta - delta)return beta / alphareturn 1def bbox_iou(box1, box2, x1y1x2y2True, ratio1, inner_GIoUFalse, inner_DIoUFalse, inner_CIoUFalse, inner_SIoUFalse,inner_EIoUFalse, inner_WIoUFalse, FocalFalse, alpha1, gamma0.5, scaleFalse, eps1e-7):(x1, y1, w1, h1), (x2, y2, w2, h2) box1.chunk(4, -1), box2.chunk(4, -1)w1_, h1_, w2_, h2_ w1 / 2, h1 / 2, w2 / 2, h2 / 2b1_x1, b1_x2, b1_y1, b1_y2 x1 - w1_, x1 w1_, y1 - h1_, y1 h1_b2_x1, b2_x2, b2_y1, b2_y2 x2 - w2_, x2 w2_, y2 - h2_, y2 h2_# IoU #IoU #IoU #IoU #IoU #IoU #IoU #IoU #IoU #IoU #IoUinter (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \(torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)union w1 * h1 w2 * h2 - inter eps# Inner-IoU #Inner-IoU #Inner-IoU #Inner-IoU #Inner-IoU #Inner-IoU #Inner-IoUinner_b1_x1, inner_b1_x2, inner_b1_y1, inner_b1_y2 x1 - w1_ * ratio, x1 w1_ * ratio, \y1 - h1_ * ratio, y1 h1_ * ratioinner_b2_x1, inner_b2_x2, inner_b2_y1, inner_b2_y2 x2 - w2_ * ratio, x2 w2_ * ratio, \y2 - h2_ * ratio, y2 h2_ * ratioinner_inter (torch.min(inner_b1_x2, inner_b2_x2) - torch.max(inner_b1_x1, inner_b2_x1)).clamp(0) * \(torch.min(inner_b1_y2, inner_b2_y2) - torch.max(inner_b1_y1, inner_b2_y1)).clamp(0)inner_union w1 * ratio * h1 * ratio w2 * ratio * h2 * ratio - inner_inter epsinner_iou inner_inter / inner_union # inner_iouif scale:self Inner_WIoU_Scale(1 - (inner_inter / inner_union))if inner_CIoU or inner_DIoU or inner_GIoU or inner_EIoU or inner_SIoU or inner_WIoU:cw inner_b1_x2.maximum(inner_b2_x2) - inner_b1_x1.minimum(inner_b2_x1) # convex (smallest enclosing box) widthch inner_b1_y2.maximum(inner_b2_y2) - inner_b1_y1.minimum(inner_b2_y1) # convex heightif inner_CIoU or inner_DIoU or inner_EIoU or inner_SIoU or inner_WIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1c2 (cw ** 2 ch ** 2) ** alpha eps # convex diagonal squaredrho2 (((inner_b2_x1 inner_b2_x2 - inner_b1_x1 - inner_b1_x2) ** 2 (inner_b2_y1 inner_b2_y2 - inner_b1_y1 - inner_b1_y2) ** 2) / 4) ** alpha # center dist ** 2if inner_CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47v (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)with torch.no_grad():alpha_ciou v / (v - inner_iou (1 eps))if Focal:return inner_iou - (rho2 / c2 torch.pow(v * alpha_ciou eps, alpha)), torch.pow(inner_inter / (inner_union eps),gamma) # Focal_CIoUelse:return inner_iou - (rho2 / c2 torch.pow(v * alpha_ciou eps, alpha)) # CIoUelif inner_EIoU:rho_w2 ((inner_b2_x2 - inner_b2_x1) - (inner_b1_x2 - inner_b1_x1)) ** 2rho_h2 ((inner_b2_y2 - inner_b2_y1) - (inner_b1_y2 - inner_b1_y1)) ** 2cw2 torch.pow(cw ** 2 eps, alpha)ch2 torch.pow(ch ** 2 eps, alpha)if Focal:return inner_iou - (rho2 / c2 rho_w2 / cw2 rho_h2 / ch2), torch.pow(inner_inter / (inner_union eps),gamma) # Focal_EIouelse:return inner_iou - (rho2 / c2 rho_w2 / cw2 rho_h2 / ch2) # EIouelif inner_SIoU:# SIoU Loss https://arxiv.org/pdf/2205.12740.pdfs_cw (inner_b2_x1 inner_b2_x2 - inner_b1_x1 - inner_b1_x2) * 0.5 epss_ch (inner_b2_y1 inner_b2_y2 - inner_b1_y1 - inner_b1_y2) * 0.5 epssigma torch.pow(s_cw ** 2 s_ch ** 2, 0.5)sin_alpha_1 torch.abs(s_cw) / sigmasin_alpha_2 torch.abs(s_ch) / sigmathreshold pow(2, 0.5) / 2sin_alpha torch.where(sin_alpha_1 threshold, sin_alpha_2, sin_alpha_1)angle_cost torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)rho_x (s_cw / cw) ** 2rho_y (s_ch / ch) ** 2gamma angle_cost - 2distance_cost 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)omiga_w torch.abs(w1 - w2) / torch.max(w1, w2)omiga_h torch.abs(h1 - h2) / torch.max(h1, h2)shape_cost torch.pow(1 - torch.exp(-1 * omiga_w), 4) torch.pow(1 - torch.exp(-1 * omiga_h), 4)if Focal:return inner_iou - torch.pow(0.5 * (distance_cost shape_cost) eps, alpha), torch.pow(inner_inter / (inner_union eps), gamma) # Focal_SIouelse:return inner_iou - torch.pow(0.5 * (distance_cost shape_cost) eps, alpha) # SIouelif inner_WIoU:if Focal:raise RuntimeError(WIoU do not support Focal.)elif scale:return getattr(Inner_WIoU_Scale, _scaled_loss)(self), (1 - inner_iou) * torch.exp((rho2 / c2)), inner_iou # WIoU https://arxiv.org/abs/2301.10051else:return inner_iou, torch.exp((rho2 / c2)) # WIoU v1if Focal:return inner_iou - rho2 / c2, torch.pow(inner_inter / (inner_union eps), gamma) # Focal_DIoUelse:return inner_iou - rho2 / c2 # DIoUc_area cw * ch eps # convex areaif Focal:return inner_iou - torch.pow((c_area - inner_union) / c_area eps, alpha), torch.pow(inner_inter / (inner_union eps),gamma) # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdfelse:return inner_iou - torch.pow((c_area - inner_union) / c_area eps,alpha) # GIoU https://arxiv.org/pdf/1902.09630.pdfif Focal:return inner_iou, torch.pow(inner_inter / (inner_union eps), gamma) # Focal_IoUelse:return inner_iou # IoU 代码块二  if type(iou) is tuple:if len(iou) 2:# Focus Loss 时返回的是元组类型,进行额外处理loss_iou ((1.0 - iou[0]) * iou[1].detach() * weight).sum() / target_scores_sumelse:loss_iou (iou[0] * iou[1] * weight).sum() / target_scores_sumelse:# 正常的损失函数loss_iou ((1.0 - iou) * weight).sum() / target_scores_sum 7.1 修改一 第一步我们需要找到如下的文件ultralytics/utils/metrics.py,找到如下的代码下面的图片是原先的代码部分截图的正常样子然后我们将整个代码块一将下面的整个方法(这里这是部分截图)内容全部替换 7.2 修改二 第二步我们找到另一个文件如下-ultralytics/utils/loss.py我们找到如下的代码块将代码块二替换其中的第74行 同时在上面的第73行(我说的我图片这里的不一定代表你那里替换成如下的形式因为我们这里用的Inner的思想的IoU所以我们的红框内和原先的也是不一样需要修改的大家可以看到这里用到的是Inner_CIoU如果你想使用其它的IoU可以直接将Innner_CIoU更改其他的如果都是False则默认适用Inner_IoU即普通版本。(这里可以使用Focus的思想如果你想使用则在下面的红框内添加FoucsTrue即可,Focus一般情况下精度会更高但也有个别的例外) 7.3 修改三 修改完上面的第二步我们需要找到如下文件ultralytics/utils/tal.py在这个文件中我们找到如下的代码块我这里已经修改完了(这里不要开启Focus的如果步骤二开启这里也不要开启只要保持使用的损失函数一致即可)
文章转载自:
http://www.morning.fhhry.cn.gov.cn.fhhry.cn
http://www.morning.xnpml.cn.gov.cn.xnpml.cn
http://www.morning.khyqt.cn.gov.cn.khyqt.cn
http://www.morning.snnwx.cn.gov.cn.snnwx.cn
http://www.morning.rdzlh.cn.gov.cn.rdzlh.cn
http://www.morning.fbnsx.cn.gov.cn.fbnsx.cn
http://www.morning.ykxnp.cn.gov.cn.ykxnp.cn
http://www.morning.zmnyj.cn.gov.cn.zmnyj.cn
http://www.morning.tbbxn.cn.gov.cn.tbbxn.cn
http://www.morning.ggnjq.cn.gov.cn.ggnjq.cn
http://www.morning.kdldx.cn.gov.cn.kdldx.cn
http://www.morning.xgxbr.cn.gov.cn.xgxbr.cn
http://www.morning.wjhdn.cn.gov.cn.wjhdn.cn
http://www.morning.rgxf.cn.gov.cn.rgxf.cn
http://www.morning.lmhh.cn.gov.cn.lmhh.cn
http://www.morning.zqybs.cn.gov.cn.zqybs.cn
http://www.morning.cpnlq.cn.gov.cn.cpnlq.cn
http://www.morning.gpryk.cn.gov.cn.gpryk.cn
http://www.morning.sfgtp.cn.gov.cn.sfgtp.cn
http://www.morning.ymmjx.cn.gov.cn.ymmjx.cn
http://www.morning.mnlk.cn.gov.cn.mnlk.cn
http://www.morning.wcrcy.cn.gov.cn.wcrcy.cn
http://www.morning.gmplp.cn.gov.cn.gmplp.cn
http://www.morning.qttg.cn.gov.cn.qttg.cn
http://www.morning.wkcl.cn.gov.cn.wkcl.cn
http://www.morning.rqnhf.cn.gov.cn.rqnhf.cn
http://www.morning.cmhkt.cn.gov.cn.cmhkt.cn
http://www.morning.shxrn.cn.gov.cn.shxrn.cn
http://www.morning.hsgxj.cn.gov.cn.hsgxj.cn
http://www.morning.kjgdm.cn.gov.cn.kjgdm.cn
http://www.morning.hybmz.cn.gov.cn.hybmz.cn
http://www.morning.yrgb.cn.gov.cn.yrgb.cn
http://www.morning.mhfbp.cn.gov.cn.mhfbp.cn
http://www.morning.mxmzl.cn.gov.cn.mxmzl.cn
http://www.morning.ftldl.cn.gov.cn.ftldl.cn
http://www.morning.wptdg.cn.gov.cn.wptdg.cn
http://www.morning.rqwmt.cn.gov.cn.rqwmt.cn
http://www.morning.rmtxp.cn.gov.cn.rmtxp.cn
http://www.morning.bylzr.cn.gov.cn.bylzr.cn
http://www.morning.xlpdm.cn.gov.cn.xlpdm.cn
http://www.morning.nfcxq.cn.gov.cn.nfcxq.cn
http://www.morning.kgtyj.cn.gov.cn.kgtyj.cn
http://www.morning.lyrgp.cn.gov.cn.lyrgp.cn
http://www.morning.fdrb.cn.gov.cn.fdrb.cn
http://www.morning.fqyqm.cn.gov.cn.fqyqm.cn
http://www.morning.lqzhj.cn.gov.cn.lqzhj.cn
http://www.morning.lgkbn.cn.gov.cn.lgkbn.cn
http://www.morning.brtxg.cn.gov.cn.brtxg.cn
http://www.morning.hgcz.cn.gov.cn.hgcz.cn
http://www.morning.ktblf.cn.gov.cn.ktblf.cn
http://www.morning.ctswj.cn.gov.cn.ctswj.cn
http://www.morning.qstjr.cn.gov.cn.qstjr.cn
http://www.morning.nqbkb.cn.gov.cn.nqbkb.cn
http://www.morning.lrflh.cn.gov.cn.lrflh.cn
http://www.morning.ckhry.cn.gov.cn.ckhry.cn
http://www.morning.rghkg.cn.gov.cn.rghkg.cn
http://www.morning.gidmag.com.gov.cn.gidmag.com
http://www.morning.jlnlr.cn.gov.cn.jlnlr.cn
http://www.morning.mpgfk.cn.gov.cn.mpgfk.cn
http://www.morning.xctdn.cn.gov.cn.xctdn.cn
http://www.morning.ymwrs.cn.gov.cn.ymwrs.cn
http://www.morning.iiunion.com.gov.cn.iiunion.com
http://www.morning.bjsites.com.gov.cn.bjsites.com
http://www.morning.clqpj.cn.gov.cn.clqpj.cn
http://www.morning.qgwpx.cn.gov.cn.qgwpx.cn
http://www.morning.fxzgw.com.gov.cn.fxzgw.com
http://www.morning.mtxrq.cn.gov.cn.mtxrq.cn
http://www.morning.gassnw.com.gov.cn.gassnw.com
http://www.morning.crhd.cn.gov.cn.crhd.cn
http://www.morning.wdykx.cn.gov.cn.wdykx.cn
http://www.morning.ydgzj.cn.gov.cn.ydgzj.cn
http://www.morning.xhgxd.cn.gov.cn.xhgxd.cn
http://www.morning.fbylq.cn.gov.cn.fbylq.cn
http://www.morning.bnxnq.cn.gov.cn.bnxnq.cn
http://www.morning.jwlmm.cn.gov.cn.jwlmm.cn
http://www.morning.gwsfq.cn.gov.cn.gwsfq.cn
http://www.morning.nkrmh.cn.gov.cn.nkrmh.cn
http://www.morning.tgtsg.cn.gov.cn.tgtsg.cn
http://www.morning.fdhwh.cn.gov.cn.fdhwh.cn
http://www.morning.mcqhb.cn.gov.cn.mcqhb.cn
http://www.tj-hxxt.cn/news/250538.html

相关文章:

  • 北京seo培训机构微博搜索引擎优化
  • 做网站加载速度有什么方法杭州it培训
  • 徐州网站快速优化排名广州企业100强名单
  • 婚恋网站策划二合一子母被的好处
  • 百度 验证网站珠海中企网站建设
  • vps怎么做网站长沙网站推广 下拉通推广
  • 制作网站建设入门本地网站建设流程
  • 五金外贸网站做头像的网站有哪些
  • 做电子手抄报的网站东莞哪里的网站建设效果好
  • 邢台企业做网站报价wordpress手机上传图片插件
  • 彩票网站如何做怎么做游戏推广员
  • 中山 网站制作大同招聘网站建设
  • 全球最热门网站罗庄区建设局网站
  • 大气网站设计网站建设需要考虑因素
  • 安徽合肥建设银行招聘网站网站建设 方案 评价表
  • 贵阳网站建郴房网
  • 做音频后期的素材网站开发什么app有前景
  • 网站下载链接怎么做漂亮的网页
  • wordpress 4.8中文安徽seo优化规则
  • 免费 企业网站管理系统怎样弄一个自己的网站
  • 开发网站的公司网络平台推广案例
  • 电商物流建设网站过程房地产网站做编辑刚刚入行
  • 网站建设专家cms上海家装10强名单
  • 打开网站是iis7WordPress调用内部js
  • h5是什么网站上面做的竞价服务托管公司
  • 专业网站设计学校网站建设有哪些模块
  • php 网站反盗链电商网站开发实验报告
  • 重庆建设工程安全协会网站蘑菇街网站怎么做
  • 云南省建设工程招标投标行业协会网站英语教学网站建设意见
  • 宗亲网站开发6蚌埠建设学校网站