目录

  • 1. Configure
  • 2. Backbone
    • 解析
      • a. fast_pathway
      • b. slow_pathway
      • c. 3d-Resnet-50结构细节(Slow/Fast pathway公用)
      • 总结
    • 代码部分
  • 3. Head+Loss
    • 解析
    • 代码部分

1. Configure

model = dict(type='Recognizer3D',backbone=dict(type='ResNet3dSlowFast',pretrained=None,resample_rate=8,  # tauspeed_ratio=8,  # alphachannel_ratio=8,  # beta_invslow_pathway=dict(type='resnet3d',depth=50,pretrained=None,lateral=True,conv1_kernel=(1, 7, 7),dilations=(1, 1, 1, 1),conv1_stride_t=1,pool1_stride_t=1,inflate=(0, 0, 1, 1),norm_eval=False),fast_pathway=dict(type='resnet3d',depth=50,pretrained=None,lateral=False,base_channels=8,conv1_kernel=(5, 7, 7),conv1_stride_t=1,pool1_stride_t=1,norm_eval=False)),cls_head=dict(type='SlowFastHead',in_channels=2304,  # 2048+256num_classes=400,spatial_type='avg',dropout_ratio=0.5),# model training and testing settingstrain_cfg=None,test_cfg=dict(average_clips='prob'))

2. Backbone

代码路径: mmaction2/mmaction/models/backbones/resnet3d_slowfast.py

解析

a. fast_pathway

  • x_fast

    • nn.functional.interpolate(x, mode='nearest', scale_factor=(1.0 / (self.resample_rate // self.speed_ratio), 1.0, 1.0))
      说明: Fast pathway在时间维度进行密集采样,空间维度不变,默认时间维度采样率1.0。
      shape: (N,C(3),T,H,W) -> (N,C(3),T,H,W)

      nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None
      )
      input: torch.tensor # 输入tensor
      size: int|tuple(int) # 输出tensor shape
      scale_factor: float|tuple(float) # [注意] 上/下采样只适用input.shape[2:]维度,如果非序列,对所有维度进行插值
      mode: 'nearest'| 'linear'| 'bilinear'| 'bicubic'| 'trilinear'| 'area' # 插值方式
      e.g.
      x = torch.rand((32,3,8,224,224))
      y = nn.functional.interpolate(x, scale_factor=(4.0, 2.0, 2.0))
      y.shape
      >> (32,3,32,448,448)
      y = nn.functional.interpolate(x, scale_factor=0.5)
      y.shape
      >> (32,3,4,112,112)
      
    • self.fast_path.conv1:
      Type: ConvModule
      说明: conv3d(8, kernel=(5,7,7), stride=(1,2,2)) + BN3d +ReLU 时序+空间特征提取 + 空间降采样 1/4
      shape: (N,C(3),T,H,W) -> (N,C_fast(8),T,H/2,W/2)

      ConvModule(self.in_channels,self.base_channels,kernel_size=self.conv1_kernel,stride=(self.conv1_stride_t, self.conv1_stride_s,self.conv1_stride_s),padding=tuple([(k - 1) // 2 for k in _triple(self.conv1_kernel)]),bias=False,conv_cfg=self.conv_cfg,norm_cfg=self.norm_cfg,act_cfg=self.act_cfg
      )
      
    • self.fast_path.maxpool
      Type: nn.MaxPool3d
      说明: MaxPool3d(kernel_size=(1, 3, 3), stride=(1,2,2)) 进一步空间降采样 1/4
      shape: (N,C_fast(8),T,H/2,W/2) -> (N,C_fast(8),T,H/4,W/4)

      nn.MaxPool3d(kernel_size=(1, 3, 3),stride=(self.pool1_stride_t, self.pool1_stride_s,self.pool1_stride_s),padding=(0, 1, 1)
      )
      
  • x_fast_lateral
    Type: ConvModule
    说明: ConvModule(8, 16, kernel_size=(5, 1, 1), stride=(8, 1, 1)) 时序特征提取 channel升维2倍, temporal维度降维1/8;从第一层conv得到的feature,接入一层时间维度卷积,给后续slow pathway的第一层conv特征进行特征融合。
    shape: (N,C_fast(8),T,H/4,W/4) -> (N,2*C_fast(8),T/8,H/4,W/4)

b. slow_pathway

  • x_slow

    • nn.functional.interpolate(x, mode='nearest', scale_factor=(1.0 / self.resample_rate, 1.0, 1.0))
      说明: Slow pathway在时间维度进行稀疏采样,空间维度不变,默认时间维度采样率1/8。
      shape (N,C(3),T,H,W) -> (N,C(3),T/8,H,W)
    • self.slow_path.conv1: ConvModule同上
      说明: conv3d(64, kernel=(1,7,7), stride=(1,2,2)) + BN3d +ReLU 空间特征提取 + 空间降采样 1/4
      shape: (N,C,T/8,H,W) -> (N,C,T/8,H/2,W/2)
    • self.slow_path.maxpool 略(同fast_path)
      shape: (N,C(3),T/8,H/2,W/2) -> (N,C_slow(64),T/8,H/4,W/4)
  • torch.cat((x_slow, x_fast_lateral)
    说明: 双流第一层卷积的slow分支和fast分支特征融合。
    shape: concat((N,C_slow(64),T/8,H/4,W/4), (N,2*C_fast(8),T/8,H/4,W/4)) -> (N,C_slow + 2*C_fast,T/8,H/4,W/4))
  • self.slow_path.res_layers
    说明: 仅slow分支作3d-Resnet-50结构(具体见下c部分),fast分支无后续特征提取

c. 3d-Resnet-50结构细节(Slow/Fast pathway公用)

  • resnet3d 多个Bottleneck3d串行组合,每个Bottleneck3d看做一个stage

    • Bottleneck3d conv_module不同stage的数量列表 = (3,4,6,3),conv_tride列表 = (1,2,2,2)

      • self.conv1 conv_module(3, 64, kernel=(3,7,7)): 对时间+空间维度进行降尺度卷积,第一层3d卷积的感受野设置较大。Q:是否丢失细节过多,考虑3d focus-conv
      • self.maxpool nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1,2,2), padding=(0, 1, 1))空间维度进行pooling。pooling是否可以改成strided-conv
      • self.pool2 nn.MaxPool3d(kernel_size=(2, 1, 1), stride=(2, 1, 1))时序维度进行pooling。
      • self.res_layers 特征提取基础block通过多个conv_module串行组合得到
        • conv_module x + 3*(conv + norm + act)(x) 最小组合

          • conv nn.Conv3d(in_channels, out_channels, kernel_size = (kt, kh, kw), stride, padding)
            特征图从二维变成三维,卷积参数增加了时间维度
          • norm nn.BatchNorm3d()
            Q: BatchNorm2d/BatchNorm3d参数量是多少?
            A: 每个channel需要存储4个参数,mean for moving-average(不用学习),variance for moving-average(不用学习),gamma(需学习),beta(需学习),因此参数量为num_channel*4
          • act nn.ReLU()

总结

  • Fast pathway采样密集,进行temporal特征提取,无3D-Resnet特征提取部分,参数量非常小;Slow pathway采样稀疏,进行spatial特征提取,有3D-Resnet特征提取部分,参数量较大
  • Slow pathway在模型开始和模型结尾都会融合Fast pathway特征,增加slow pathway对temporal特征的表达能力

代码部分

# Copyright (c) OpenMMLab. All rights reserved.
import warningsimport torch
import torch.nn as nn
from mmcv.cnn import ConvModule, kaiming_init
from mmcv.runner import _load_checkpoint, load_checkpoint
from mmcv.utils import print_logfrom ...utils import get_root_logger
from ..builder import BACKBONES
from .resnet3d import ResNet3dtry:from mmdet.models import BACKBONES as MMDET_BACKBONESmmdet_imported = True
except (ImportError, ModuleNotFoundError):mmdet_imported = Falseclass ResNet3dPathway(ResNet3d):"""A pathway of Slowfast based on ResNet3d.Args:*args (arguments): Arguments same as :class:``ResNet3d``.lateral (bool): Determines whether to enable the lateral connectionfrom another pathway. Default: False.speed_ratio (int): Speed ratio indicating the ratio between timedimension of the fast and slow pathway, corresponding to the``alpha`` in the paper. Default: 8.channel_ratio (int): Reduce the channel number of fast pathwayby ``channel_ratio``, corresponding to ``beta`` in the paper.Default: 8.fusion_kernel (int): The kernel size of lateral fusion.Default: 5.**kwargs (keyword arguments): Keywords arguments for ResNet3d."""def __init__(self,*args,lateral=False,lateral_norm=False,speed_ratio=8,channel_ratio=8,fusion_kernel=5,**kwargs):self.lateral = lateralself.lateral_norm = lateral_normself.speed_ratio = speed_ratioself.channel_ratio = channel_ratioself.fusion_kernel = fusion_kernelsuper().__init__(*args, **kwargs)self.inplanes = self.base_channelsif self.lateral:self.conv1_lateral = ConvModule(self.inplanes // self.channel_ratio,# https://arxiv.org/abs/1812.03982, the# third type of lateral connection has out_channel:# 2 * \beta * Cself.inplanes * 2 // self.channel_ratio,kernel_size=(fusion_kernel, 1, 1),stride=(self.speed_ratio, 1, 1),padding=((fusion_kernel - 1) // 2, 0, 0),bias=False,conv_cfg=self.conv_cfg,norm_cfg=self.norm_cfg if self.lateral_norm else None,act_cfg=self.act_cfg if self.lateral_norm else None)self.lateral_connections = []for i in range(len(self.stage_blocks)):planes = self.base_channels * 2**iself.inplanes = planes * self.block.expansionif lateral and i != self.num_stages - 1:# no lateral connection needed in final stagelateral_name = f'layer{(i + 1)}_lateral'setattr(self, lateral_name,ConvModule(self.inplanes // self.channel_ratio,self.inplanes * 2 // self.channel_ratio,kernel_size=(fusion_kernel, 1, 1),stride=(self.speed_ratio, 1, 1),padding=((fusion_kernel - 1) // 2, 0, 0),bias=False,conv_cfg=self.conv_cfg,norm_cfg=self.norm_cfg if self.lateral_norm else None,act_cfg=self.act_cfg if self.lateral_norm else None))self.lateral_connections.append(lateral_name)def make_res_layer(self,block,inplanes,planes,blocks,spatial_stride=1,temporal_stride=1,dilation=1,style='pytorch',inflate=1,inflate_style='3x1x1',non_local=0,non_local_cfg=dict(),conv_cfg=None,norm_cfg=None,act_cfg=None,with_cp=False):"""Build residual layer for Slowfast.Args:block (nn.Module): Residual module to be built.inplanes (int): Number of channels for the inputfeature in each block.planes (int): Number of channels for the outputfeature in each block.blocks (int): Number of residual blocks.spatial_stride (int | Sequence[int]): Spatial stridesin residual and conv layers. Default: 1.temporal_stride (int | Sequence[int]): Temporal strides inresidual and conv layers. Default: 1.dilation (int): Spacing between kernel elements. Default: 1.style (str): ``pytorch`` or ``caffe``. If set to ``pytorch``,the stride-two layer is the 3x3 conv layer,otherwise the stride-two layer is the first 1x1 conv layer.Default: ``pytorch``.inflate (int | Sequence[int]): Determine whether to inflatefor each block. Default: 1.inflate_style (str): ``3x1x1`` or ``3x3x3``. which determinesthe kernel sizes and padding strides for conv1 andconv2 in each block. Default: ``3x1x1``.non_local (int | Sequence[int]): Determine whether to applynon-local module in the corresponding block of each stages.Default: 0.non_local_cfg (dict): Config for non-local module.Default: ``dict()``.conv_cfg (dict | None): Config for conv layers. Default: None.norm_cfg (dict | None): Config for norm layers. Default: None.act_cfg (dict | None): Config for activate layers. Default: None.with_cp (bool): Use checkpoint or not. Using checkpoint will savesome memory while slowing down the training speed.Default: False.Returns:nn.Module: A residual layer for the given config."""inflate = inflate if not isinstance(inflate,int) else (inflate, ) * blocksnon_local = non_local if not isinstance(non_local, int) else (non_local, ) * blocksassert len(inflate) == blocks and len(non_local) == blocksif self.lateral:lateral_inplanes = inplanes * 2 // self.channel_ratioelse:lateral_inplanes = 0if (spatial_stride != 1or (inplanes + lateral_inplanes) != planes * block.expansion):downsample = ConvModule(inplanes + lateral_inplanes,planes * block.expansion,kernel_size=1,stride=(temporal_stride, spatial_stride, spatial_stride),bias=False,conv_cfg=conv_cfg,norm_cfg=norm_cfg,act_cfg=None)else:downsample = Nonelayers = []layers.append(block(inplanes + lateral_inplanes,planes,spatial_stride,temporal_stride,dilation,downsample,style=style,inflate=(inflate[0] == 1),inflate_style=inflate_style,non_local=(non_local[0] == 1),non_local_cfg=non_local_cfg,conv_cfg=conv_cfg,norm_cfg=norm_cfg,act_cfg=act_cfg,with_cp=with_cp))inplanes = planes * block.expansionfor i in range(1, blocks):layers.append(block(inplanes,planes,1,1,dilation,style=style,inflate=(inflate[i] == 1),inflate_style=inflate_style,non_local=(non_local[i] == 1),non_local_cfg=non_local_cfg,conv_cfg=conv_cfg,norm_cfg=norm_cfg,act_cfg=act_cfg,with_cp=with_cp))return nn.Sequential(*layers)def inflate_weights(self, logger):"""Inflate the resnet2d parameters to resnet3d pathway.The differences between resnet3d and resnet2d mainly lie in an extraaxis of conv kernel. To utilize the pretrained parameters in 2d model,the weight of conv2d models should be inflated to fit in the shapes ofthe 3d counterpart. For pathway the ``lateral_connection`` part shouldnot be inflated from 2d weights.Args:logger (logging.Logger): The logger used to printdebugging information."""state_dict_r2d = _load_checkpoint(self.pretrained)if 'state_dict' in state_dict_r2d:state_dict_r2d = state_dict_r2d['state_dict']inflated_param_names = []for name, module in self.named_modules():if 'lateral' in name:continueif isinstance(module, ConvModule):# we use a ConvModule to wrap conv+bn+relu layers, thus the# name mapping is neededif 'downsample' in name:# layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0original_conv_name = name + '.0'# layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1original_bn_name = name + '.1'else:# layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n}original_conv_name = name# layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n}original_bn_name = name.replace('conv', 'bn')if original_conv_name + '.weight' not in state_dict_r2d:logger.warning(f'Module not exist in the state_dict_r2d'f': {original_conv_name}')else:self._inflate_conv_params(module.conv, state_dict_r2d,original_conv_name,inflated_param_names)if original_bn_name + '.weight' not in state_dict_r2d:logger.warning(f'Module not exist in the state_dict_r2d'f': {original_bn_name}')else:self._inflate_bn_params(module.bn, state_dict_r2d,original_bn_name,inflated_param_names)# check if any parameters in the 2d checkpoint are not loadedremaining_names = set(state_dict_r2d.keys()) - set(inflated_param_names)if remaining_names:logger.info(f'These parameters in the 2d checkpoint are not loaded'f': {remaining_names}')def _inflate_conv_params(self, conv3d, state_dict_2d, module_name_2d,inflated_param_names):"""Inflate a conv module from 2d to 3d.The differences of conv modules betweene 2d and 3d in Pathwaymainly lie in the inplanes due to lateral connections. To fit theshapes of the lateral connection counterpart, it will expandparameters by concatting conv2d parameters and extra zero paddings.Args:conv3d (nn.Module): The destination conv3d module.state_dict_2d (OrderedDict): The state dict of pretrained 2d model.module_name_2d (str): The name of corresponding conv module in the2d model.inflated_param_names (list[str]): List of parameters that have beeninflated."""weight_2d_name = module_name_2d + '.weight'conv2d_weight = state_dict_2d[weight_2d_name]old_shape = conv2d_weight.shapenew_shape = conv3d.weight.data.shapekernel_t = new_shape[2]if new_shape[1] != old_shape[1]:if new_shape[1] < old_shape[1]:warnings.warn(f'The parameter of {module_name_2d} is not''loaded due to incompatible shapes. ')return# Inplanes may be different due to lateral connectionsnew_channels = new_shape[1] - old_shape[1]pad_shape = old_shapepad_shape = pad_shape[:1] + (new_channels, ) + pad_shape[2:]# Expand parameters by concat extra channelsconv2d_weight = torch.cat((conv2d_weight,torch.zeros(pad_shape).type_as(conv2d_weight).to(conv2d_weight.device)),dim=1)new_weight = conv2d_weight.data.unsqueeze(2).expand_as(conv3d.weight) / kernel_tconv3d.weight.data.copy_(new_weight)inflated_param_names.append(weight_2d_name)if getattr(conv3d, 'bias') is not None:bias_2d_name = module_name_2d + '.bias'conv3d.bias.data.copy_(state_dict_2d[bias_2d_name])inflated_param_names.append(bias_2d_name)def _freeze_stages(self):"""Prevent all the parameters from being optimized before`self.frozen_stages`."""if self.frozen_stages >= 0:self.conv1.eval()for param in self.conv1.parameters():param.requires_grad = Falsefor i in range(1, self.frozen_stages + 1):m = getattr(self, f'layer{i}')m.eval()for param in m.parameters():param.requires_grad = Falseif i != len(self.res_layers) and self.lateral:# No fusion needed in the final stagelateral_name = self.lateral_connections[i - 1]conv_lateral = getattr(self, lateral_name)conv_lateral.eval()for param in conv_lateral.parameters():param.requires_grad = Falsedef init_weights(self, pretrained=None):"""Initiate the parameters either from existing checkpoint or fromscratch."""if pretrained:self.pretrained = pretrained# Override the init_weights of i3dsuper().init_weights()for module_name in self.lateral_connections:layer = getattr(self, module_name)for m in layer.modules():if isinstance(m, (nn.Conv3d, nn.Conv2d)):kaiming_init(m)pathway_cfg = {'resnet3d': ResNet3dPathway,# TODO: BNInceptionPathway
}def build_pathway(cfg, *args, **kwargs):"""Build pathway.Args:cfg (None or dict): cfg should contain:- type (str): identify conv layer type.Returns:nn.Module: Created pathway."""if not (isinstance(cfg, dict) and 'type' in cfg):raise TypeError('cfg must be a dict containing the key "type"')cfg_ = cfg.copy()pathway_type = cfg_.pop('type')if pathway_type not in pathway_cfg:raise KeyError(f'Unrecognized pathway type {pathway_type}')pathway_cls = pathway_cfg[pathway_type]pathway = pathway_cls(*args, **kwargs, **cfg_)return pathway@BACKBONES.register_module()
class ResNet3dSlowFast(nn.Module):"""Slowfast backbone.This module is proposed in `SlowFast Networks for Video Recognition<https://arxiv.org/abs/1812.03982>`_Args:pretrained (str): The file path to a pretrained model.resample_rate (int): A large temporal stride ``resample_rate``on input frames. The actual resample rate is calculated bymultipling the ``interval`` in ``SampleFrames`` in thepipeline with ``resample_rate``, equivalent to the :math:`\\tau`in the paper, i.e. it processes only one out of``resample_rate * interval`` frames. Default: 8.speed_ratio (int): Speed ratio indicating the ratio between timedimension of the fast and slow pathway, corresponding to the:math:`\\alpha` in the paper. Default: 8.channel_ratio (int): Reduce the channel number of fast pathwayby ``channel_ratio``, corresponding to :math:`\\beta` in the paper.Default: 8.slow_pathway (dict): Configuration of slow branch, should containnecessary arguments for building the specific type of pathwayand:type (str): type of backbone the pathway bases on.lateral (bool): determine whether to build lateral connectionfor the pathway.Default:.. code-block:: Pythondict(type='ResNetPathway',lateral=True, depth=50, pretrained=None,conv1_kernel=(1, 7, 7), dilations=(1, 1, 1, 1),conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1))fast_pathway (dict): Configuration of fast branch, similar to`slow_pathway`. Default:.. code-block:: Pythondict(type='ResNetPathway',lateral=False, depth=50, pretrained=None, base_channels=8,conv1_kernel=(5, 7, 7), conv1_stride_t=1, pool1_stride_t=1)"""def __init__(self,pretrained,resample_rate=8,speed_ratio=8,channel_ratio=8,slow_pathway=dict(type='resnet3d',depth=50,pretrained=None,lateral=True,conv1_kernel=(1, 7, 7),dilations=(1, 1, 1, 1),conv1_stride_t=1,pool1_stride_t=1,inflate=(0, 0, 1, 1)),fast_pathway=dict(type='resnet3d',depth=50,pretrained=None,lateral=False,base_channels=8,conv1_kernel=(5, 7, 7),conv1_stride_t=1,pool1_stride_t=1)):super().__init__()self.pretrained = pretrainedself.resample_rate = resample_rateself.speed_ratio = speed_ratioself.channel_ratio = channel_ratioif slow_pathway['lateral']:slow_pathway['speed_ratio'] = speed_ratioslow_pathway['channel_ratio'] = channel_ratioself.slow_path = build_pathway(slow_pathway)self.fast_path = build_pathway(fast_pathway)def init_weights(self, pretrained=None):"""Initiate the parameters either from existing checkpoint or fromscratch."""if pretrained:self.pretrained = pretrainedif isinstance(self.pretrained, str):logger = get_root_logger()msg = f'load model from: {self.pretrained}'print_log(msg, logger=logger)# Directly load 3D model.load_checkpoint(self, self.pretrained, strict=True, logger=logger)elif self.pretrained is None:# Init two branch separately.self.fast_path.init_weights()self.slow_path.init_weights()else:raise TypeError('pretrained must be a str or None')def forward(self, x):"""Defines the computation performed at every call.Args:x (torch.Tensor): The input data.Returns:tuple[torch.Tensor]: The feature of the input samples extractedby the backbone."""x_slow = nn.functional.interpolate(x,mode='nearest',scale_factor=(1.0 / self.resample_rate, 1.0, 1.0))x_slow = self.slow_path.conv1(x_slow)x_slow = self.slow_path.maxpool(x_slow)x_fast = nn.functional.interpolate(x,mode='nearest',scale_factor=(1.0 / (self.resample_rate // self.speed_ratio), 1.0,1.0))x_fast = self.fast_path.conv1(x_fast)x_fast = self.fast_path.maxpool(x_fast)if self.slow_path.lateral:x_fast_lateral = self.slow_path.conv1_lateral(x_fast)x_slow = torch.cat((x_slow, x_fast_lateral), dim=1)for i, layer_name in enumerate(self.slow_path.res_layers):res_layer = getattr(self.slow_path, layer_name)x_slow = res_layer(x_slow)res_layer_fast = getattr(self.fast_path, layer_name)x_fast = res_layer_fast(x_fast)if (i != len(self.slow_path.res_layers) - 1and self.slow_path.lateral):# No fusion needed in the final stagelateral_name = self.slow_path.lateral_connections[i]conv_lateral = getattr(self.slow_path, lateral_name)x_fast_lateral = conv_lateral(x_fast)x_slow = torch.cat((x_slow, x_fast_lateral), dim=1)out = (x_slow, x_fast)return outif mmdet_imported:MMDET_BACKBONES.register_module()(ResNet3dSlowFast)

3. Head+Loss

代码路径:mmaction2/mmaction/models/heads/slowfast_head.py

解析

  • Head

    • nn.AdaptiveAvgPool3d((1,1,1)) x_fast和x_slow共用,三维版global average pooling
      输入shape:[N,channelfast,T,H,W],[(N,channelslow,T,H,W)][N, channel_{fast}, T, H, W], [(N, channel_{slow}, T, H, W)][N,channelfast​,T,H,W],[(N,channelslow​,T,H,W)]
      输出shape:[N,channelfast,1,1,1],[(N,channelslow,1,1,1)][N, channel_{fast}, 1, 1, 1], [(N, channel_{slow}, 1, 1, 1)][N,channelfast​,1,1,1],[(N,channelslow​,1,1,1)]
    • cat + dropout + view(x.size(0), -1)
      输入shape:[N,channelfast,1,1,1],[(N,channelslow,1,1,1)][N, channel_{fast}, 1, 1, 1], [(N, channel_{slow}, 1, 1, 1)][N,channelfast​,1,1,1],[(N,channelslow​,1,1,1)]
      输出shape:[N,channelfast+channelslow)][N, channel_{fast}+channel_{slow})][N,channelfast​+channelslow​)]
    • nn.Linear(in_channels, num_classes)
      输入shape:[N,channelfast+channelslow)][N, channel_{fast}+channel_{slow})][N,channelfast​+channelslow​)]
      输出shape:[N,class_num][N, class\_num][N,class_num]
  • Loss: CrossEntropyLoss

代码部分

# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import normal_initfrom ..builder import HEADS
from .base import BaseHead@HEADS.register_module()
class SlowFastHead(BaseHead):"""The classification head for SlowFast.Args:num_classes (int): Number of classes to be classified.in_channels (int): Number of channels in input feature.loss_cls (dict): Config for building loss.Default: dict(type='CrossEntropyLoss').spatial_type (str): Pooling type in spatial dimension. Default: 'avg'.dropout_ratio (float): Probability of dropout layer. Default: 0.8.init_std (float): Std value for Initiation. Default: 0.01.kwargs (dict, optional): Any keyword argument to be used to initializethe head."""def __init__(self,num_classes,in_channels,loss_cls=dict(type='CrossEntropyLoss'),spatial_type='avg',dropout_ratio=0.8,init_std=0.01,**kwargs):super().__init__(num_classes, in_channels, loss_cls, **kwargs)self.spatial_type = spatial_typeself.dropout_ratio = dropout_ratioself.init_std = init_stdif self.dropout_ratio != 0:self.dropout = nn.Dropout(p=self.dropout_ratio)else:self.dropout = Noneself.fc_cls = nn.Linear(in_channels, num_classes)if self.spatial_type == 'avg':self.avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))else:self.avg_pool = Nonedef init_weights(self):"""Initiate the parameters from scratch."""normal_init(self.fc_cls, std=self.init_std)def forward(self, x):"""Defines the computation performed at every call.Args:x (torch.Tensor): The input data.Returns:torch.Tensor: The classification scores for input samples."""# ([N, channel_fast, T, H, W], [(N, channel_slow, T, H, W)])x_fast, x_slow = x# ([N, channel_fast, 1, 1, 1], [N, channel_slow, 1, 1, 1])x_fast = self.avg_pool(x_fast)x_slow = self.avg_pool(x_slow)# [N, channel_fast + channel_slow, 1, 1, 1]x = torch.cat((x_slow, x_fast), dim=1)if self.dropout is not None:x = self.dropout(x)# [N x C]x = x.view(x.size(0), -1)# [N x num_classes]cls_score = self.fc_cls(x)return cls_score

【代码解析】mmaction2: SlowFast相关推荐

  1. 动作识别0-10:mmaction2(SlowFast)-源码无死角解析(6)-模型构建总览

    以下链接是个人关于mmaction2(SlowFast-动作识别) 所有见解,如有错误欢迎大家指出,我会第一时间纠正.有兴趣的朋友可以加微信:17575010159 相互讨论技术.若是帮助到了你什么, ...

  2. 【mmaction2 slowfast 行为分析(商用级别)】总目录

    B站讲解视频 01[mmaction2 slowfast 行为分析(商用级别)]项目下载 02[mmaction2 slowfast 行为分析(商用级别)]项目demo搭建 03[mmaction2 ...

  3. matrix_multiply代码解析

    matrix_multiply代码解析 关于matrix_multiply 程序执行代码里两个矩阵的乘法,并将相乘结果打印在屏幕上. 示例的主要目的是展现怎么实现一个自定义CPU计算任务. 参考:ht ...

  4. CornerNet代码解析——损失函数

    CornerNet代码解析--损失函数 文章目录 CornerNet代码解析--损失函数 前言 总体损失 1.Heatmap的损失 2.Embedding的损失 3.Offset的损失 前言 今天要解 ...

  5. 视觉SLAM开源算法ORB-SLAM3 原理与代码解析

    来源:深蓝学院,文稿整理者:何常鑫,审核&修改:刘国庆 本文总结于上交感知与导航研究所科研助理--刘国庆关于[视觉SLAM开源算法ORB-SLAM3 原理与代码解析]的公开课. ORB-SLA ...

  6. java获取object属性值_java反射获取一个object属性值代码解析

    有些时候你明明知道这个object里面是什么,但是因为种种原因,你不能将它转化成一个对象,只是想单纯地提取出这个object里的一些东西,这个时候就需要用反射了. 假如你这个类是这样的: privat ...

  7. python中的doc_基于Python获取docx/doc文件内容代码解析

    这篇文章主要介绍了基于Python获取docx/doc文件内容代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 整体思路: 下载文件并修改后缀 ...

  8. mongoose框架示例代码解析(一)

    mongoose框架示例代码解析(一) 参考: Mongoose Networking Library Documentation(Server) Mongoose Networking Librar ...

  9. ViBe算法原理和代码解析

    ViBe - a powerful technique for background detection and subtraction in video sequences 算法官网:http:// ...

  10. 【Android 逆向】使用 Python 代码解析 ELF 文件 ( PyCharm 中进行断点调试 | ELFFile 实例对象分析 )

    文章目录 一.PyCharm 中进行断点调试 二.ELFFile 实例对象分析 一.PyCharm 中进行断点调试 在上一篇博客 [Android 逆向]使用 Python 代码解析 ELF 文件 ( ...

最新文章

  1. Docker:容器的四种网络类型 [十三]
  2. 《京东技术解密》——海量订单处理
  3. c语言 10以内加法,求助 给小学生出题,自己选加减乘除 做10题 10以内的数 然后统计分...
  4. c语言中的switch语句中的break和continue的作用
  5. Java学习路线总结,搬砖工逆袭Java架构师
  6. Python入门学习—列表(FishC)
  7. R-CNN算法优化策略
  8. Dreamweaver/Flash CS4安装后打开时提示此产品的许可已停止工作
  9. 中国科学院大学2013年数学分析高等代数考研试题
  10. JS简单总结(前端ES6和JQ)
  11. Win10家庭版将中文用户名修改为英文用户名
  12. 客户消费积分管理系统编写笔记
  13. SEO优化之浅谈蜘蛛日志
  14. 关于飞思卡尔的芯片固件库问题,为什么5.3没有8位芯片固件选择MC9S08DZ60芯片
  15. matplotlib给某一个点添加注释
  16. 语音信号处理疑惑与解答
  17. 百度云服务器ping不通,云主机ping的通三节点,但是ping不通百度
  18. 转移到ios下载安卓_转移到iOS app-转移到iOS(从Android转到iOS)苹果官方版_5577安卓网...
  19. P1401 矩阵连乘问题
  20. 【笔试】备战秋招,每日一题|20230415携程研发岗笔试

热门文章

  1. WIN8 Prolific USB-to-Serial Comm Port : 该设备无法启动。 (代码 10)
  2. win10安装PL2303_Prolific_DriverInstaller_v1.5.0驱动
  3. dnf如何快速拾取物品_dnf一键捡物品的方法步骤技巧
  4. Java 面试问题总结(详细) —— MySql 模块(MySQL高级)(建议收藏)
  5. RL(十三)深度Q网络(DQN)
  6. c语言习题:华氏度摄氏度比照表
  7. Linux操作系统应用实例_Discuz安装
  8. 题目错题记录表mysql设计_基于Web2.0的跨平台电子错题本功能的设计与实现
  9. 创建分区表,以及将数据写入分区表
  10. python传递指针_python值传递和指针传递