code stringlengths 17 6.64M |
|---|
def train_SN(args):
(data_train, data_dev, data_test) = (load_data(args, 'train'), load_data(args, 'dev'), load_data(args, 'test'))
if args.noise_label:
data_noise = load_data(args, 'test_noise')
else:
data_noise = None
args.label_size = len(data_test.relId2labelId)
args.ner_label_... |
class Trainer(nn.Module):
def __init__(self, options, data_train, data_dev, data_test, data_noise):
super(Trainer, self).__init__()
self.options = options
self.batch_size = options.batch_size
self.save_path = options.save_model_name
self.device = options.gpu
self.n... |
def load_data(args, mode='train'):
data_path = (((args.save_data_path + '.') + mode) + '.data')
if os.path.exists(data_path):
print('Loading {} data from {}...'.format(mode, data_path))
with open(data_path, 'rb') as f:
data = pickle.load(f)
else:
data = Data(args, mode)... |
def train_SN(args):
(data_train, data_dev, data_test) = (load_data(args, 'train'), load_data(args, 'dev'), load_data(args, 'test'))
if args.noise_label:
data_noise = load_data(args, 'test_noise')
else:
data_noise = None
args.label_size = len(data_test.relId2labelId)
args.ner_label_... |
class Trainer(nn.Module):
def __init__(self, options, data_train, data_dev, data_test, data_noise):
super(Trainer, self).__init__()
self.options = options
self.batch_size = options.batch_size
self.save_path = options.save_model_name
self.device = options.gpu
self.n... |
def extract_features(strv):
feat = np.array(([0.0] * 6))
for i in range(6):
tmp = strv[i].split(':')
feat_index = int(tmp[0])
feat_value = float(tmp[1])
feat[(feat_index - 1)] = feat_value
return feat
|
def parse_line(line):
line = line.strip()
line = line.split('|')
decision_info = line[0].split(' ')
timestamp = int(decision_info[0])
offered_ad_id = int(decision_info[1])
click = int(decision_info[2])
user_info = line[1].split(' ')[1:]
user_feat = extract_features(user_info)
ad_in... |
def digit_version(version_str):
digit_version = []
for x in version_str.split('.'):
if x.isdigit():
digit_version.append(int(x))
elif (x.find('rc') != (- 1)):
patch_version = x.split('rc')
digit_version.append((int(patch_version[0]) - 1))
digit_v... |
def init_segmentor(config, checkpoint=None, device='cuda:0'):
'Initialize a segmentor from config file.\n\n Args:\n config (str or :obj:`mmcv.Config`): Config file path or the config\n object.\n checkpoint (str, optional): Checkpoint path. If left as None, the model\n will n... |
class LoadImage():
'A simple pipeline to load image.'
def __call__(self, results):
'Call function to load images into results.\n\n Args:\n results (dict): A result dict contains the file name\n of the image to be read.\n\n Returns:\n dict: ``results`... |
def inference_segmentor(model, img):
'Inference image(s) with the segmentor.\n\n Args:\n model (nn.Module): The loaded segmentor.\n imgs (str/ndarray or list[str/ndarray]): Either image files or loaded\n images.\n\n Returns:\n (list[Tensor]): The segmentation result.\n '
... |
def show_result_pyplot(model, img, result, palette=None, fig_size=(15, 10)):
'Visualize the segmentation results on the image.\n\n Args:\n model (nn.Module): The loaded segmentor.\n img (str or np.ndarray): Image filename or loaded image.\n result (list): The segmentation result.\n ... |
def set_random_seed(seed, deterministic=False):
'Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.... |
def train_segmentor(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None):
'Launch segmentor training.'
logger = get_root_logger(cfg.log_level)
dataset = (dataset if isinstance(dataset, (list, tuple)) else [dataset])
data_loaders = [build_dataloader(ds, cfg.data.samples_pe... |
def cityscapes_classes():
'Cityscapes class names for external use.'
return ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']
|
def ade_classes():
'ADE20K class names for external use.'
return ['wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'hous... |
def voc_classes():
'Pascal VOC class names for external use.'
return ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
|
def cityscapes_palette():
'Cityscapes palette for external use.'
return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60,... |
def ade_palette():
'ADE20K palette for external use.'
return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, ... |
def voc_palette():
'Pascal VOC palette for external use.'
return [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128... |
def get_classes(dataset):
'Get class names of a dataset.'
alias2name = {}
for (name, aliases) in dataset_aliases.items():
for alias in aliases:
alias2name[alias] = name
if mmcv.is_str(dataset):
if (dataset in alias2name):
labels = eval((alias2name[dataset] + '_c... |
def get_palette(dataset):
'Get class palette (RGB) of a dataset.'
alias2name = {}
for (name, aliases) in dataset_aliases.items():
for alias in aliases:
alias2name[alias] = name
if mmcv.is_str(dataset):
if (dataset in alias2name):
labels = eval((alias2name[datase... |
class EvalHook(Hook):
'Evaluation hook.\n\n Attributes:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluation interval (by epochs). Default: 1.\n '
def __init__(self, dataloader, interval=1, **eval_kwargs):
if (not isinstance(dataloader, DataLoader)):
... |
class DistEvalHook(EvalHook):
'Distributed evaluation hook.\n\n Attributes:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluation interval (by epochs). Default: 1.\n tmpdir (str | None): Temporary directory to save the results of all\n processes. Default:... |
def build_pixel_sampler(cfg, **default_args):
'Build pixel sampler for segmentation map.'
return build_from_cfg(cfg, PIXEL_SAMPLERS, default_args)
|
class BasePixelSampler(metaclass=ABCMeta):
'Base class of pixel sampler.'
def __init__(self, **kwargs):
pass
@abstractmethod
def sample(self, seg_logit, seg_label):
'Placeholder for sample function.'
pass
|
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
'Online Hard Example Mining Sampler for segmentation.\n\n Args:\n context (nn.Module): The context of sampler, subclass of\n :obj:`BaseDecodeHead`.\n thresh (float, optional): The threshold for hard example sel... |
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=(- 1)):
if (bucket_size_mb > 0):
bucket_size_bytes = ((bucket_size_mb * 1024) * 1024)
buckets = _take_tensors(tensors, bucket_size_bytes)
else:
buckets = OrderedDict()
for tensor in tensors:
tp = tensor.ty... |
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)):
'Allreduce gradients.\n\n Args:\n params (list[torch.Parameters]): List of parameters of a model\n coalesce (bool, optional): Whether allreduce parameters as a whole.\n Defaults to True.\n bucket_size_mb (int, opt... |
def add_prefix(inputs, prefix):
'Add prefix for dict.\n\n Args:\n inputs (dict): The input dict with str keys.\n prefix (str): The prefix to add.\n\n Returns:\n\n dict: The dict with keys updated with ``prefix``.\n '
outputs = dict()
for (name, value) in inputs.items():
... |
@DATASETS.register_module()
class AMDDataset(CustomDataset):
'Pascal VOC dataset.\n\n Args:\n split (str): Split txt file for Pascal VOC.\n '
CLASSES = ('background', 'foreground')
PALETTE = [[0, 0, 0], [128, 0, 0]]
def __init__(self, split, **kwargs):
super(AMDDataset, self).__i... |
def _concat_dataset(cfg, default_args=None):
'Build :obj:`ConcatDataset by.'
from .dataset_wrappers import ConcatDataset
img_dir = cfg['img_dir']
ann_dir = cfg.get('ann_dir', None)
split = cfg.get('split', None)
num_img_dir = (len(img_dir) if isinstance(img_dir, (list, tuple)) else 1)
if (... |
def build_dataset(cfg, default_args=None):
'Build datasets.'
from .dataset_wrappers import ConcatDataset, RepeatDataset
if isinstance(cfg, (list, tuple)):
dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])
elif (cfg['type'] == 'RepeatDataset'):
dataset = RepeatDatas... |
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, drop_last=False, pin_memory=True, dataloader_type='PoolDataLoader', **kwargs):
"Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed train... |
def worker_init_fn(worker_id, num_workers, rank, seed):
'Worker init func for dataloader.\n\n The seed of each worker equals to num_worker * rank + worker_id + user_seed\n\n Args:\n worker_id (int): Worker id.\n num_workers (int): Number of workers.\n rank (int): The rank of current pro... |
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
'A wrapper of concatenated dataset.\n\n Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but\n concat the group flag for image aspect ratio.\n\n Args:\n datasets (list[:obj:`Dataset`]): A list of datasets.\n '
def __ini... |
@DATASETS.register_module()
class RepeatDataset(object):
'A wrapper of repeated dataset.\n\n The length of repeated dataset will be `times` larger than the original\n dataset. This is useful when the data loading time is long but the dataset\n is small. Using RepeatDataset can reduce the data loading tim... |
@PIPELINES.register_module()
class Compose(object):
'Compose multiple transforms sequentially.\n\n Args:\n transforms (Sequence[dict | callable]): Sequence of transform object or\n config dict to be composed.\n '
def __init__(self, transforms):
assert isinstance(transforms, co... |
def to_tensor(data):
'Convert objects of various python types to :obj:`torch.Tensor`.\n\n Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n :class:`Sequence`, :class:`int` and :class:`float`.\n\n Args:\n data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n ... |
@PIPELINES.register_module()
class ToTensor(object):
'Convert some results to :obj:`torch.Tensor` by given keys.\n\n Args:\n keys (Sequence[str]): Keys that need to be converted to Tensor.\n '
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
'Call func... |
@PIPELINES.register_module()
class ImageToTensor(object):
'Convert image to :obj:`torch.Tensor` by given keys.\n\n The dimension order of input image is (H, W, C). The pipeline will convert\n it to (C, H, W). If only 2 dimension (H, W) is given, the output would be\n (1, H, W).\n\n Args:\n keys... |
@PIPELINES.register_module()
class Transpose(object):
'Transpose some results by given keys.\n\n Args:\n keys (Sequence[str]): Keys of results to be transposed.\n order (Sequence[int]): Order of transpose.\n '
def __init__(self, keys, order):
self.keys = keys
self.order = ... |
@PIPELINES.register_module()
class ToDataContainer(object):
"Convert results to :obj:`mmcv.DataContainer` by given fields.\n\n Args:\n fields (Sequence[dict]): Each field is a dict like\n ``dict(key='xxx', **kwargs)``. The ``key`` in result will\n be converted to :obj:`mmcv.DataCon... |
@PIPELINES.register_module()
class DefaultFormatBundle(object):
'Default formatting bundle.\n\n It simplifies the pipeline of formatting common fields, including "img"\n and "gt_semantic_seg". These fields are formatted as follows.\n\n - img: (1)transpose, (2)to tensor, (3)to DataContainer (stack=True)\n... |
@PIPELINES.register_module()
class Collect(object):
'Collect data from the loader relevant to the specific task.\n\n This is usually the last stage of the data loader pipeline. Typically keys\n is set to some subset of "img", "gt_semantic_seg".\n\n The "img_meta" item is always populated. The contents o... |
@PIPELINES.register_module()
class LoadImageFromFile(object):
'Load an image from file.\n\n Required keys are "img_prefix" and "img_info" (a dict that must contain the\n key "filename"). Added or updated keys are "filename", "img", "img_shape",\n "ori_shape" (same as `img_shape`), "pad_shape" (same as `i... |
@PIPELINES.register_module()
class LoadAnnotations(object):
"Load annotations for semantic segmentation.\n\n Args:\n reduct_zero_label (bool): Whether reduce all label value by 1.\n Usually used for datasets where 0 is background label.\n Default: False.\n file_client_args (... |
@PIPELINES.register_module()
class MultiScaleFlipAug(object):
'Test-time augmentation with multiple scales and flipping.\n\n An example configuration is as followed:\n\n .. code-block::\n\n img_scale=(2048, 1024),\n img_ratios=[0.5, 1.0],\n flip=True,\n transforms=[\n ... |
class BasicBlock(nn.Module):
'Basic block for ResNet.'
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, plugins=None):
super(BasicBlock, self).__init__()
assert (dcn... |
class Bottleneck(nn.Module):
'Bottleneck block for ResNet.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is\n "caffe", the stride-two layer is the first 1x1 conv layer.\n '
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, st... |
@BACKBONES.register_module()
class ResNet(nn.Module):
'ResNet backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n in_channels (int): Number of input image channels. Default" 3.\n stem_channels (int): Number of stem channels. Default: 64.\n base_channel... |
@BACKBONES.register_module()
class ResNetV1c(ResNet):
'ResNetV1c variant described in [1]_.\n\n Compared with default ResNet(ResNetV1b), ResNetV1c replaces the 7x7 conv\n in the input stem with three 3x3 convs.\n\n References:\n .. [1] https://arxiv.org/pdf/1812.01187.pdf\n '
def __init__(... |
@BACKBONES.register_module()
class ResNetV1d(ResNet):
'ResNetV1d variant described in [1]_.\n\n Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in\n the input stem with three 3x3 convs. And in the downsampling block, a 2x2\n avg_pool with stride 2 is added before conv, whose stri... |
def build(cfg, registry, default_args=None):
'Build a module.\n\n Args:\n cfg (dict, list[dict]): The config of modules, is is either a dict\n or a list of configs.\n registry (:obj:`Registry`): A registry the module belongs to.\n default_args (dict, optional): Default arguments... |
def build_backbone(cfg):
'Build backbone.'
return build(cfg, BACKBONES)
|
def build_neck(cfg):
'Build neck.'
return build(cfg, NECKS)
|
def build_head(cfg):
'Build head.'
return build(cfg, HEADS)
|
def build_loss(cfg):
'Build loss.'
return build(cfg, LOSSES)
|
def build_segmentor(cfg, train_cfg=None, test_cfg=None):
'Build segmentor.'
return build(cfg, SEGMENTORS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
|
class BaseDecodeHead(nn.Module, metaclass=ABCMeta):
"Base class for BaseDecodeHead.\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n channels (int): Channels after modules, before conv_seg.\n num_classes (int): Number of classes.\n dropout_ratio (float): Ratio of dropo... |
def get_loss(cfg):
if (cfg.type == 'unflow'):
loss = unFlowLoss(cfg)
else:
raise NotImplementedError(cfg.type)
return loss
|
class CorrelationFunction(Function):
def __init__(self, pad_size=3, kernel_size=3, max_displacement=20, stride1=1, stride2=2, corr_multiply=1):
super(CorrelationFunction, self).__init__()
self.pad_size = pad_size
self.kernel_size = kernel_size
self.max_displacement = max_displacem... |
class Correlation(Module):
def __init__(self, pad_size=0, kernel_size=0, max_displacement=0, stride1=1, stride2=2, corr_multiply=1):
super(Correlation, self).__init__()
self.pad_size = pad_size
self.kernel_size = kernel_size
self.max_displacement = max_displacement
self.st... |
def get_model(cfg):
if (cfg.type == 'pwclite'):
model = PWCLite(cfg)
else:
raise NotImplementedError(cfg.type)
return model
|
def update_dict(orig_dict, new_dict):
for (key, val) in new_dict.items():
if isinstance(val, collections.Mapping):
tmp = update_dict(orig_dict.get(key, {}), val)
orig_dict[key] = tmp
else:
orig_dict[key] = val
return orig_dict
|
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self, i=1, precision=3, names=None):
self.meters = i
self.precision = precision
self.reset(self.meters)
self.names = names
if (names is not None):
assert (self.mete... |
def init_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
|
def weight_parameters(module):
return [param for (name, param) in module.named_parameters() if ('weight' in name)]
|
def bias_parameters(module):
return [param for (name, param) in module.named_parameters() if ('bias' in name)]
|
def load_checkpoint(model_path):
weights = torch.load(model_path)
epoch = None
if ('epoch' in weights):
epoch = weights.pop('epoch')
if ('state_dict' in weights):
state_dict = weights['state_dict']
else:
state_dict = weights
return (epoch, state_dict)
|
def save_checkpoint(save_path, states, file_prefixes, is_best, filename='ckpt.pth.tar'):
def run_one_sample(save_path, state, prefix, is_best, filename):
torch.save(state, (save_path / '{}_{}'.format(prefix, filename)))
if is_best:
shutil.copyfile((save_path / '{}_{}'.format(prefix, f... |
def restore_model(model, pretrained_file):
(epoch, weights) = load_checkpoint(pretrained_file)
model_keys = set(model.state_dict().keys())
weight_keys = set(weights.keys())
weights_not_in_model = sorted(list((weight_keys - model_keys)))
model_not_in_weights = sorted(list((model_keys - weight_keys)... |
class AdamW(Optimizer):
'Implements AdamW algorithm.\n\n It has been proposed in `Fixing Weight Decay Regularization in Adam`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default:... |
def accuracy(pred, target, topk=1, thresh=None):
'Calculate accuracy according to the prediction and target.\n\n Args:\n pred (torch.Tensor): The model prediction, shape (N, num_class, ...)\n target (torch.Tensor): The target of each prediction, shape (N, , ...)\n topk (int | tuple[int], o... |
class Accuracy(nn.Module):
'Accuracy calculation module.'
def __init__(self, topk=(1,), thresh=None):
'Module to calculate the accuracy.\n\n Args:\n topk (tuple, optional): The criterion used to calculate the\n accuracy. Defaults to (1,).\n thresh (float, o... |
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... |
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 losses of PyTorch.\n avg_factor (float... |
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\... |
@NECKS.register_module()
class FPN(nn.Module):
"Feature Pyramid Network.\n\n This is an implementation of - 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 (int): Numbe... |
def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
'Make divisible function.\n\n This function rounds the channel number down to the nearest value that can\n be divisible by the divisor.\n\n Args:\n value (int): The original channel number.\n divisor (int): The divisor to fu... |
class ResLayer(nn.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 firs... |
class SelfAttentionBlock(nn.Module):
'General self-attention block/non-local block.\n\n Please refer to https://arxiv.org/abs/1706.03762 for details about key,\n query and value.\n\n Args:\n key_in_channels (int): Input channels of key feature.\n query_in_channels (int): Input channels of q... |
class Encoding(nn.Module):
'Encoding Layer: a learnable residual encoder.\n\n Input is of shape (batch_size, channels, height, width).\n Output is of shape (batch_size, num_codes, channels).\n\n Args:\n channels: dimension of the features or feature channels\n num_codes: number of code wor... |
class DepthwiseSeparableConvModule(nn.Module):
"Depthwise separable convolution module.\n\n See https://arxiv.org/pdf/1704.04861.pdf for details.\n\n This module can replace a ConvModule with the conv block replaced by two\n conv block: depthwise conv block and pointwise conv block. The depthwise\n co... |
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True):
if warning:
if ((size is not None) and align_corners):
(input_h, input_w) = tuple((int(x) for x in input.shape[2:]))
(output_h, output_w) = tuple((int(x) for x in size))
i... |
class Upsample(nn.Module):
def __init__(self, size=None, scale_factor=None, mode='nearest', align_corners=None):
super(Upsample, self).__init__()
self.size = size
if isinstance(scale_factor, tuple):
self.scale_factor = tuple((float(factor) for factor in scale_factor))
... |
def collect_env():
'Collect the information of the running environments.'
env_info = {}
env_info['sys.platform'] = sys.platform
env_info['Python'] = sys.version.replace('\n', '')
cuda_available = torch.cuda.is_available()
env_info['CUDA available'] = cuda_available
if cuda_available:
... |
class InvertedResidual(nn.Module):
"Inverted residual module.\n\n Args:\n in_channels (int): The input channels of the InvertedResidual block.\n out_channels (int): The output channels of the InvertedResidual block.\n stride (int): Stride of the middle (first) 3x3 convolution.\n exp... |
def get_root_logger(log_file=None, log_level=logging.INFO):
'Get the root logger.\n\n The logger will be initialized if it has not been initialized. By default a\n StreamHandler will be added. If `log_file` is specified, a FileHandler will\n also be added. The name of the root logger is the top-level pac... |
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 _get_config_directory():
'Find the predefined segmentor config directory.'
try:
repo_dpath = dirname(dirname(__file__))
except NameError:
import mmseg
repo_dpath = dirname(dirname(mmseg.__file__))
config_dpath = join(repo_dpath, 'configs')
if (not exists(config_dpath)):... |
def test_config_build_segmentor():
'Test that all segmentation models defined in the configs can be\n initialized.'
config_dpath = _get_config_directory()
print('Found config_dpath = {!r}'.format(config_dpath))
config_fpaths = []
for sub_folder in os.listdir(config_dpath):
if isdir(sub_... |
def test_config_data_pipeline():
'Test whether the data pipeline is valid and can process corner cases.\n\n CommandLine:\n xdoctest -m tests/test_config.py test_config_build_data_pipeline\n '
from mmcv import Config
from mmseg.datasets.pipelines import Compose
import numpy as np
confi... |
def _check_decode_head(decode_head_cfg, decode_head):
if isinstance(decode_head_cfg, list):
assert isinstance(decode_head, nn.ModuleList)
assert (len(decode_head_cfg) == len(decode_head))
num_heads = len(decode_head)
for i in range(num_heads):
_check_decode_head(decode_... |
def test_classes():
assert (list(CityscapesDataset.CLASSES) == get_classes('cityscapes'))
assert (list(PascalVOCDataset.CLASSES) == get_classes('voc') == get_classes('pascal_voc'))
assert (list(ADE20KDataset.CLASSES) == get_classes('ade') == get_classes('ade20k'))
with pytest.raises(ValueError):
... |
def test_palette():
assert (CityscapesDataset.PALETTE == get_palette('cityscapes'))
assert (PascalVOCDataset.PALETTE == get_palette('voc') == get_palette('pascal_voc'))
assert (ADE20KDataset.PALETTE == get_palette('ade') == get_palette('ade20k'))
with pytest.raises(ValueError):
get_palette('un... |
@patch('mmseg.datasets.CustomDataset.load_annotations', MagicMock)
@patch('mmseg.datasets.CustomDataset.__getitem__', MagicMock(side_effect=(lambda idx: idx)))
def test_dataset_wrapper():
dataset_a = CustomDataset(img_dir=MagicMock(), pipeline=[])
len_a = 10
dataset_a.img_infos = MagicMock()
dataset_a... |
def test_custom_dataset():
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (512, 1024)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict(type='Resize', img_scale=(128, 256), ratio_range=(0.5, 2.0)), dict(type='Ran... |
@DATASETS.register_module()
class ToyDataset(object):
def __init__(self, cnt=0):
self.cnt = cnt
def __item__(self, idx):
return idx
def __len__(self):
return 100
|
def test_build_dataset():
cfg = dict(type='ToyDataset')
dataset = build_dataset(cfg)
assert isinstance(dataset, ToyDataset)
assert (dataset.cnt == 0)
dataset = build_dataset(cfg, default_args=dict(cnt=1))
assert isinstance(dataset, ToyDataset)
assert (dataset.cnt == 1)
data_root = osp.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.