code stringlengths 17 6.64M |
|---|
@LOSSES.register_module()
class KnowledgeDistillationKLDivLoss(nn.Module):
"Loss function for knowledge distilling using KL divergence.\n\n Args:\n reduction (str): Options are `'none'`, `'mean'` and `'sum'`.\n loss_weight (float): Loss weight of current loss.\n T (int): Temperature for di... |
@weighted_loss
def mse_loss(pred, target):
'Warpper of mse loss.'
return F.mse_loss(pred, target, reduction='none')
|
@LOSSES.register_module()
class MSELoss(nn.Module):
'MSELoss.\n\n Args:\n reduction (str, optional): The method that reduces the loss to a\n scalar. Options are "none", "mean" and "sum".\n loss_weight (float, optional): The weight of the loss. Defaults to 1.0\n '
def __init__(s... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
'Smooth L1 loss.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n beta (float, optional): The threshold in the piecewise func... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
'L1 loss.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n\n Returns:\n torch.Tensor: Calculated loss\n '
if (target.numel() == 0):
... |
@LOSSES.register_module()
class SmoothL1Loss(nn.Module):
'Smooth L1 loss.\n\n Args:\n beta (float, optional): The threshold in the piecewise function.\n Defaults to 1.0.\n reduction (str, optional): The method to reduce the loss.\n Options are "none", "mean" and "sum". Defau... |
@LOSSES.register_module()
class L1Loss(nn.Module):
'L1 loss.\n\n Args:\n reduction (str, optional): The method to reduce the loss.\n Options are "none", "mean" and "sum".\n loss_weight (float, optional): The weight of loss.\n '
def __init__(self, reduction='mean', loss_weight=1... |
def reduce_loss(loss, reduction):
'Reduce loss as specified.\n\n Args:\n loss (Tensor): Elementwise loss tensor.\n reduction (str): Options are "none", "mean" and "sum".\n\n Return:\n Tensor: Reduced loss tensor.\n '
reduction_enum = F._Reduction.get_enum(reduction)
if (reduc... |
@mmcv.jit(derivate=True, coderize=True)
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
'Apply element-wise weight and reduce loss.\n\n Args:\n loss (Tensor): Element-wise loss.\n weight (Tensor): Element-wise weights.\n reduction (str): Same as built-in losse... |
def weighted_loss(loss_func):
"Create a weighted version of a given loss function.\n\n To use this decorator, the loss function must have the signature like\n `loss_func(pred, target, **kwargs)`. The function only needs to compute\n element-wise loss without any reduction. This decorator will add weight\... |
@mmcv.jit(derivate=True, coderize=True)
def varifocal_loss(pred, target, weight=None, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', avg_factor=None):
'`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, C), C is the\n ... |
@LOSSES.register_module()
class VarifocalLoss(nn.Module):
def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0):
'`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_\n\n Args:\n use_sigmoid (bool, optional): Whether the predic... |
@NECKS.register_module()
class BFP(BaseModule):
"BFP (Balanced Feature Pyramids)\n\n BFP takes multi-level features as inputs and gather them into a single one,\n then refine the gathered feature and scatter the refined results to\n multi-level features. This module is used in Libra R-CNN (CVPR 2019), se... |
@NECKS.register_module()
class ChannelMapper(BaseModule):
"Channel Mapper to reduce/increase channels of backbone features.\n\n This is used to reduce/increase channels of backbone features.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (int): Number o... |
class Bottleneck(nn.Module):
'Bottleneck block for DilatedEncoder used in `YOLOF.\n\n <https://arxiv.org/abs/2103.09460>`.\n\n The Bottleneck contains three ConvLayers and one residual connection.\n\n Args:\n in_channels (int): The number of input channels.\n mid_channels (int): The number ... |
@NECKS.register_module()
class DilatedEncoder(nn.Module):
'Dilated Encoder for YOLOF <https://arxiv.org/abs/2103.09460>`.\n\n This module contains two types of components:\n - the original FPN lateral convolution layer and fpn convolution layer,\n which are 1x1 conv + 3x3 conv\n - th... |
class Transition(BaseModule):
'Base class for transition.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n '
def __init__(self, in_channels, out_channels, init_cfg=None):
super().__init__(init_cfg)
self.in_channels... |
class UpInterpolationConv(Transition):
'A transition used for up-sampling.\n\n Up-sample the input by interpolation then refines the feature by\n a convolution layer.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n scale_fac... |
class LastConv(Transition):
'A transition used for refining the output of the last stage.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n num_inputs (int): Number of inputs of the FPN features.\n kernel_size (int): Kernel s... |
@NECKS.register_module()
class FPG(BaseModule):
"FPG.\n\n Implementation of `Feature Pyramid Grids (FPG)\n <https://arxiv.org/abs/2004.03580>`_.\n This implementation only gives the basic structure stated in the paper.\n But users can implement different type of transitions to fully explore the\n t... |
@NECKS.register_module()
class FPN(BaseModule):
"Feature Pyramid Network.\n\n This is an implementation of paper `Feature Pyramid Networks for Object\n Detection <https://arxiv.org/abs/1612.03144>`_.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (in... |
@NECKS.register_module()
class HRFPN(BaseModule):
'HRFPN (High Resolution Feature Pyramids)\n\n paper: `High-Resolution Representations for Labeling Pixels and Regions\n <https://arxiv.org/abs/1904.04514>`_.\n\n Args:\n in_channels (list): number of channels for each branch.\n out_channels ... |
@NECKS.register_module()
class NASFPN(BaseModule):
'NAS-FPN.\n\n Implementation of `NAS-FPN: Learning Scalable Feature Pyramid Architecture\n for Object Detection <https://arxiv.org/abs/1904.07392>`_\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (in... |
@NECKS.register_module()
class NASFCOS_FPN(BaseModule):
'FPN structure in NASFPN.\n\n Implementation of paper `NAS-FCOS: Fast Neural Architecture Search for\n Object Detection <https://arxiv.org/abs/1906.04423>`_\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out... |
@NECKS.register_module()
class PAFPN(FPN):
"Path Aggregation Network for Instance Segmentation.\n\n This is an implementation of the `PAFPN in Path Aggregation Network\n <https://arxiv.org/abs/1803.01534>`_.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_chan... |
class ASPP(BaseModule):
'ASPP (Atrous Spatial Pyramid Pooling)\n\n This is an implementation of the ASPP module used in DetectoRS\n (https://arxiv.org/pdf/2006.02334.pdf)\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of channels produced by this modul... |
@NECKS.register_module()
class RFP(FPN):
'RFP (Recursive Feature Pyramid)\n\n This is an implementation of RFP in `DetectoRS\n <https://arxiv.org/pdf/2006.02334.pdf>`_. Different from standard FPN, the\n input of RFP should be multi level features along with origin input image\n of backbone.\n\n Ar... |
class DetectionBlock(BaseModule):
"Detection block in YOLO neck.\n\n Let out_channels = n, the DetectionBlock contains:\n Six ConvLayers, 1 Conv2D Layer and 1 YoloLayer.\n The first 6 ConvLayers are formed the following way:\n 1x1xn, 3x3x2n, 1x1xn, 3x3x2n, 1x1xn, 3x3x2n.\n The Conv2D layer is 1... |
@NECKS.register_module()
class YOLOV3Neck(BaseModule):
"The neck of YOLOV3.\n\n It can be treated as a simplified version of FPN. It\n will take the result from Darknet backbone and do some upsampling and\n concatenation. It will finally output the detection result.\n\n Note:\n The input feats ... |
@NECKS.register_module()
class YOLOXPAFPN(BaseModule):
"Path Aggregation Network used in YOLOX.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (int): Number of output channels (used at each scale)\n num_csp_blocks (int): Number of bottlenecks in CSP... |
@PLUGIN_LAYERS.register_module()
class DropBlock(nn.Module):
'Randomly drop some regions of feature maps.\n\n Please refer to the method proposed in `DropBlock\n <https://arxiv.org/abs/1810.12890>`_ for details.\n\n Args:\n drop_prob (float): The probability of dropping each block.\n bloc... |
class BaseRoIHead(BaseModule, metaclass=ABCMeta):
'Base class for RoIHeads.'
def __init__(self, bbox_roi_extractor=None, bbox_head=None, mask_roi_extractor=None, mask_head=None, shared_head=None, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None):
super(BaseRoIHead, self).__init__(init_cf... |
@HEADS.register_module()
class ConvFCBBoxHead(BBoxHead):
'More general bbox head, with shared conv and fc layers and two optional\n separated branches.\n\n .. code-block:: none\n\n /-> cls convs -> cls fcs -> cls\n shared convs -> shared fcs\n ... |
@HEADS.register_module()
class Shared2FCBBoxHead(ConvFCBBoxHead):
def __init__(self, fc_out_channels=1024, *args, **kwargs):
super(Shared2FCBBoxHead, self).__init__(*args, num_shared_convs=0, num_shared_fcs=2, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, fc_out_channels=fc_out_channels... |
@HEADS.register_module()
class Shared4Conv1FCBBoxHead(ConvFCBBoxHead):
def __init__(self, fc_out_channels=1024, *args, **kwargs):
super(Shared4Conv1FCBBoxHead, self).__init__(*args, num_shared_convs=4, num_shared_fcs=1, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, fc_out_channels=fc_ou... |
class BasicResBlock(BaseModule):
'Basic residual block.\n\n This block is a little different from the block in the ResNet backbone.\n The kernel size of conv1 is 1 in this block while 3 in ResNet BasicBlock.\n\n Args:\n in_channels (int): Channels of the input feature map.\n out_channels (i... |
@HEADS.register_module()
class DoubleConvFCBBoxHead(BBoxHead):
'Bbox head used in Double-Head R-CNN\n\n .. code-block:: none\n\n /-> cls\n /-> shared convs ->\n \\-> reg\n roi features\n ... |
@HEADS.register_module()
class SCNetBBoxHead(ConvFCBBoxHead):
'BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us\n to get intermediate shared feature.\n '
def _forward_shared(self, x):
'Forward function ... |
@HEADS.register_module()
class DoubleHeadRoIHead(StandardRoIHead):
'RoI head for Double Head RCNN.\n\n https://arxiv.org/abs/1904.06493\n '
def __init__(self, reg_roi_scale_factor, **kwargs):
super(DoubleHeadRoIHead, self).__init__(**kwargs)
self.reg_roi_scale_factor = reg_roi_scale_fac... |
@HEADS.register_module()
class CoarseMaskHead(FCNMaskHead):
'Coarse mask head used in PointRend.\n\n Compared with standard ``FCNMaskHead``, ``CoarseMaskHead`` will downsample\n the input feature map instead of upsample it.\n\n Args:\n num_convs (int): Number of conv layers in the head. Default: 0... |
@HEADS.register_module()
class DynamicMaskHead(FCNMaskHead):
'Dynamic Mask Head for\n `Instances as Queries <http://arxiv.org/abs/2105.01928>`_\n\n Args:\n num_convs (int): Number of convolution layer.\n Defaults to 4.\n roi_feat_size (int): The output size of RoI extractor,\n ... |
@HEADS.register_module()
class FeatureRelayHead(BaseModule):
'Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n in_channels (int, optional): number of input channels. Default: 256.\n conv_out_channels (int, optional): number of output channels before\n ... |
@HEADS.register_module()
class FusedSemanticHead(BaseModule):
'Multi-level fused semantic segmentation head.\n\n .. code-block:: none\n\n in_1 -> 1x1 conv ---\n |\n in_2 -> 1x1 conv -- |\n ||\n in_3 -> 1x1 conv - ||\n ... |
@HEADS.register_module()
class GlobalContextHead(BaseModule):
'Global context head used in `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n num_convs (int, optional): number of convolutional layer in GlbCtxHead.\n Default: 4.\n in_channels (int, optional): number of input chann... |
@HEADS.register_module()
class HTCMaskHead(FCNMaskHead):
def __init__(self, with_conv_res=True, *args, **kwargs):
super(HTCMaskHead, self).__init__(*args, **kwargs)
self.with_conv_res = with_conv_res
if self.with_conv_res:
self.conv_res = ConvModule(self.conv_out_channels, sel... |
@HEADS.register_module()
class SCNetMaskHead(FCNMaskHead):
'Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n conv_to_res (bool, optional): if True, change the conv layers to\n ``SimplifiedBasicBlock``.\n '
def __init__(self, conv_to_res=True, **kwargs):
s... |
@HEADS.register_module()
class SCNetSemanticHead(FusedSemanticHead):
'Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n conv_to_res (bool, optional): if True, change the conv layers to\n ``SimplifiedBasicBlock``.\n '
def __init__(self, conv_to_res=True, **kwargs):... |
@HEADS.register_module()
class PISARoIHead(StandardRoIHead):
'The RoI head for `Prime Sample Attention in Object Detection\n <https://arxiv.org/abs/1904.04821>`_.'
def forward_train(self, x, img_metas, proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None):
"Forward function fo... |
@SHARED_HEADS.register_module()
class ResLayer(BaseModule):
def __init__(self, depth, stage=3, stride=2, dilation=1, style='pytorch', norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, with_cp=False, dcn=None, pretrained=None, init_cfg=None):
super(ResLayer, self).__init__(init_cfg)
se... |
@HEADS.register_module()
class PanopticFPNHead(BaseSemanticHead):
'PanopticFPNHead used in Panoptic FPN.\n\n In this head, the number of output channels is ``num_stuff_classes\n + 1``, including all stuff classes and one thing class. The stuff\n classes will be reset from ``0`` to ``num_stuff_classes - 1... |
class BasePanopticFusionHead(BaseModule, metaclass=ABCMeta):
'Base class for panoptic heads.'
def __init__(self, num_things_classes=80, num_stuff_classes=53, test_cfg=None, loss_panoptic=None, init_cfg=None, **kwargs):
super(BasePanopticFusionHead, self).__init__(init_cfg)
self.num_things_cla... |
def adaptive_avg_pool2d(input, output_size):
'Handle empty batch dimension to adaptive_avg_pool2d.\n\n Args:\n input (tensor): 4D tensor.\n output_size (int, tuple[int,int]): the target output size.\n '
if ((input.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))):
if... |
class AdaptiveAvgPool2d(nn.AdaptiveAvgPool2d):
'Handle empty batch dimension to AdaptiveAvgPool2d.'
def forward(self, x):
if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))):
output_size = self.output_size
if isinstance(output_size, int):
ou... |
def build_transformer(cfg, default_args=None):
'Builder for Transformer.'
return build_from_cfg(cfg, TRANSFORMER, default_args)
|
def build_linear_layer(cfg, *args, **kwargs):
'Build linear layer.\n Args:\n cfg (None or dict): The linear layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate an linear layer.\n args (argument list): Arguments passed to... |
class ConvUpsample(BaseModule):
'ConvUpsample performs 2x upsampling after Conv.\n\n There are several `ConvModule` layers. In the first few layers, upsampling\n will be applied after each layer of convolution. The number of upsampling\n must be no more than the number of ConvModule layers.\n\n Args:\... |
class DarknetBottleneck(BaseModule):
"The basic bottleneck block used in Darknet.\n\n Each ResBlock consists of two ConvModules and the input is added to the\n final output. Each ConvModule is composed of Conv, BN, and LeakyReLU.\n The first convLayer has filter size of 1x1 and the second one has the\n ... |
class CSPLayer(BaseModule):
"Cross Stage Partial Layer.\n\n Args:\n in_channels (int): The input channels of the CSP layer.\n out_channels (int): The output channels of the CSP layer.\n expand_ratio (float): Ratio to adjust the number of channels of the\n hidden layer. Default: ... |
class InvertedResidual(BaseModule):
"Inverted Residual Block.\n\n Args:\n in_channels (int): The input channels of this Module.\n out_channels (int): The output channels of this Module.\n mid_channels (int): The input channels of the depthwise convolution.\n kernel_size (int): The k... |
def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
'Make divisible function.\n\n This function rounds the channel number to the nearest value that can be\n divisible by the divisor. It is taken from the original tf repo. It ensures\n that all layers have a channel number that is divisible... |
@LINEAR_LAYERS.register_module(name='NormedLinear')
class NormedLinear(nn.Linear):
'Normalized Linear Layer.\n\n Args:\n tempeature (float, optional): Tempeature term. Default to 20.\n power (int, optional): Power term. Default to 1.0.\n eps (float, optional): The minimal value of divisor ... |
@CONV_LAYERS.register_module(name='NormedConv2d')
class NormedConv2d(nn.Conv2d):
'Normalized Conv2d Layer.\n\n Args:\n tempeature (float, optional): Tempeature term. Default to 20.\n power (int, optional): Power term. Default to 1.0.\n eps (float, optional): The minimal value of divisor to... |
def preprocess_panoptic_gt(gt_labels, gt_masks, gt_semantic_seg, num_things, num_stuff):
'Preprocess the ground truth for a image.\n\n Args:\n gt_labels (Tensor): Ground truth labels of each bbox,\n with shape (num_gts, ).\n gt_masks (BitmapMasks): Ground truth masks of each instances\... |
class ResLayer(Sequential):
"ResLayer to build ResNet style backbone.\n\n Args:\n block (nn.Module): block used to build ResLayer.\n inplanes (int): inplanes of block.\n planes (int): planes of block.\n num_blocks (int): number of blocks.\n stride (int): stride of the first b... |
class SimplifiedBasicBlock(BaseModule):
'Simplified version of original basic residual block. This is used in\n `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n - Norm layer is now optional\n - Last ReLU in forward function is removed\n '
expansion = 1
def __init__(self, inplanes, planes, str... |
class SELayer(BaseModule):
"Squeeze-and-Excitation Module.\n\n Args:\n channels (int): The input (and output) channels of the SE layer.\n ratio (int): Squeeze ratio in SELayer, the intermediate channel will be\n ``int(channels/ratio)``. Default: 16.\n conv_cfg (None or dict): Co... |
class DyReLU(BaseModule):
"Dynamic ReLU (DyReLU) module.\n\n See `Dynamic ReLU <https://arxiv.org/abs/2003.10027>`_ for details.\n Current implementation is specialized for task-aware attention in DyHead.\n HSigmoid arguments in default act_cfg follow DyHead official code.\n https://github.com/microso... |
def collect_env():
'Collect the information of the running environments.'
env_info = collect_base_env()
env_info['MMDetection'] = ((mmdet.__version__ + '+') + get_git_hash()[:7])
return env_info
|
def get_root_logger(log_file=None, log_level=logging.INFO):
'Get root logger.\n\n Args:\n log_file (str, optional): File path of log. Defaults to None.\n log_level (int, optional): The level of logger.\n Defaults to logging.INFO.\n\n Returns:\n :obj:`logging.Logger`: The obta... |
def find_latest_checkpoint(path, suffix='pth'):
'Find the latest checkpoint from the working directory.\n\n Args:\n path(str): The path to find checkpoints.\n suffix(str): File extension.\n Defaults to pth.\n\n Returns:\n latest_path(str | None): File path of the latest check... |
def setup_multi_processes(cfg):
'Setup multi-processing environment variables.'
if (platform.system() != 'Windows'):
mp_start_method = cfg.get('mp_start_method', 'fork')
current_method = mp.get_start_method(allow_none=True)
if ((current_method is not None) and (current_method != mp_sta... |
class NiceRepr():
'Inherit from this class and define ``__nice__`` to "nicely" print your\n objects.\n\n Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function\n Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``.\n If the inheriting class has a ``__len__``, metho... |
def ensure_rng(rng=None):
'Coerces input into a random number generator.\n\n If the input is None, then a global random state is returned.\n\n If the input is a numeric value, then that is used as a seed to construct a\n random state. Otherwise the input is returned as-is.\n\n Adapted from [1]_.\n\n ... |
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif (x.find('rc') != (- 1)):
patch_version = x.split('rc')
version_info.append(int(patch_version[0]))
version_inf... |
def _activation_summary(x):
'Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\n Args:\n x: Tensor\n Returns:\n nothing\n '
tensor_name = re.sub(('%s_[0-9]*/' % TOWER_NAME), ''... |
def _variable_on_cpu(name, shape, initializer):
'Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n '
with tf.device('/cpu:0'):
dtype = (tf.float16 if FLA... |
def _variable_with_weight_decay(name, shape, stddev, wd):
'Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list o... |
def distorted_inputs():
'Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n '
if (not FLAGS.data_di... |
def inputs(eval_data):
'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] ... |
def inference(images):
'Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n\n Returns:\n Logits.\n '
with tf.variable_scope('conv1') as scope:
kernel = _variable_with_weight_decay('weights', shape=[5, 5, 3, 64], stddev=0.05, wd=0.0)
con... |
def loss(logits, labels):
'Add L2Loss to all the trainable variables.\n\n Add summary for "Loss" and "Loss/avg".\n Args:\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor\n of shape [batch_size]\n\n Returns:\n Loss tensor of type float.\n '
... |
def _add_loss_summaries(total_loss):
'Add summaries for losses in CIFAR-10 model.\n\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n\n Args:\n total_loss: Total loss from loss().\n Returns:\n loss_averages_op: op for generating moving... |
def train(total_loss, global_step):
'Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed... |
def maybe_download_and_extract():
"Download and extract the tarball from Alex's website."
dest_directory = FLAGS.data_dir
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not... |
def read_cifar10(filename_queue):
'Reads and parses examples from CIFAR10 data files.\n\n Recommendation: if you want N-way read parallelism, call this function\n N times. This will give you N independent Readers reading different\n files & positions within those files, which will give better mixing of\n exa... |
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle):
'Construct a queued batch of images and labels.\n\n Args:\n image: 3-D Tensor of [height, width, 3] of type.float32.\n label: 1-D Tensor of type.int32\n min_queue_examples: int32, minimum number of samples to ret... |
def distorted_inputs(data_dir, batch_size):
'Construct distorted input for CIFAR training using the Reader ops.\n\n Args:\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\... |
def inputs(eval_data, data_dir, batch_size):
'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n ima... |
def conv_variable(weight_shape):
w = weight_shape[0]
h = weight_shape[1]
input_channels = weight_shape[2]
output_channels = weight_shape[3]
d = (1.0 / np.sqrt(((input_channels * w) * h)))
bias_shape = [output_channels]
weight = tf.Variable(tf.random_uniform(weight_shape, minval=(- d), maxv... |
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')
|
def maxpool2d(x, k=2):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
|
def IPE_r1(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FLAGS):
img_pair = tf.concat([F1F2, F2F3, F3F4, F4F5, F5F6], 0)
(w_1_1, b_1_1) = conv_variable([10, 10, (FLAGS.col_dim * 2), 4])
h_1_1 = tf.nn.relu((conv2d(img_pair, w_1_1, 1) + b_1_1))
(w_1_2, b_1_2) = conv_variable([10, 10, 4, 4])
h_1_2 = tf... |
def IPE_r2(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FLAGS):
fil_num = FLAGS.fil_num
img_pair = tf.concat([F1F2, F2F3, F3F4, F4F5, F5F6], 0)
h_3_2_x_y = tf.concat([img_pair, x_cor, y_cor], 3)
(w_4_1, b_4_1) = conv_variable([3, 3, 10, fil_num])
h_4_1 = tf.nn.relu((conv2d(h_3_2_x_y, w_4_1, 1) + b_... |
def VE(F1, F2, F3, F4, F5, F6, x_cor, y_cor, FLAGS):
F1F2 = tf.concat([F1, F2], 3)
F2F3 = tf.concat([F2, F3], 3)
F3F4 = tf.concat([F3, F4], 3)
F4F5 = tf.concat([F4, F5], 3)
F5F6 = tf.concat([F5, F6], 3)
(pair1, pair2, pair3, pair4, pair5) = IPE_r2(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FL... |
def core_r1(S, FLAGS, idx):
fil_num = 64
M = tf.unstack(S, FLAGS.No, 1)
SD_in = tf.reshape(S, [(- 1), FLAGS.Ds])
with tf.variable_scope(('self-dynamics' + str(idx))):
w1 = tf.get_variable('w1', shape=[FLAGS.Ds, fil_num])
b1 = tf.get_variable('b1', shape=[fil_num])
h1 = tf.nn.re... |
def core_r2(S, FLAGS, idx):
fil_num = 64
M = tf.unstack(S, FLAGS.No, 1)
M_self = np.zeros(FLAGS.No, dtype=object)
for i in range(FLAGS.No):
with tf.variable_scope(((('self-dynamics' + str(idx)) + '_') + str((i + 1)))):
w1 = tf.get_variable('w1', shape=[FLAGS.Ds, fil_num])
... |
def DP(S1, S2, S3, S4, FLAGS):
Sc1 = core_r1(S1, FLAGS, 4)
Sc3 = core_r1(S3, FLAGS, 2)
Sc4 = core_r1(S4, FLAGS, 1)
fil_num = 64
S = tf.concat([Sc1, Sc3, Sc4], 2)
S = tf.reshape(S, [(- 1), (FLAGS.Ds * 3)])
with tf.variable_scope('DP'):
w1 = tf.get_variable('w1', shape=[(FLAGS.Ds * 3... |
def SD(output_dp, FLAGS):
input_sd = tf.reshape(output_dp, [(- 1), FLAGS.Ds])
w1 = tf.Variable(tf.truncated_normal([FLAGS.Ds, 4], stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(tf.zeros([4]), dtype=tf.float32)
h1 = (tf.matmul(input_sd, w1) + b1)
h1 = tf.reshape(h1, [(- 1), FLAGS.No, 4])
retur... |
class Data():
def __init__(self, args):
kwargs = {}
if (not args.cpu):
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = True
else:
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = False
self.loader_train = N... |
class Benchmark(srdata.SRData):
def __init__(self, args, train=True):
super(Benchmark, self).__init__(args, train, benchmark=True)
def _scan(self):
list_hr = []
list_lr = [[] for _ in self.scale]
for entry in os.scandir(self.dir_hr):
filename = os.path.splitext(en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.