code
stringlengths
17
6.64M
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...
@DETECTORS.register_module() class DDQRCNN(TwoStageDetector): def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None, **kwargs): batch_input_shape = tuple(img[0].size()[(- 2):]) for img_meta in img_metas: img_meta['batch_inpu...
def padding_to(inputs, max=300): if (max is None): return inputs num_padding = (max - len(inputs)) if (inputs.dim() > 1): padding = inputs.new_zeros(num_padding, *inputs.size()[1:], dtype=inputs.dtype) else: padding = inputs.new_zeros(num_padding, dtype=inputs.dtype) inputs...
def align_tensor(inputs, max_len=None): if (max_len is None): max_len = max([len(item) for item in inputs]) return torch.stack([padding_to(item, max_len) for item in inputs])
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--work-dir', help='the directory to save the file containing evalua...
def replace_ceph_backend(cfg): cfg_pretty_text = cfg.pretty_text replace_strs = "file_client_args = dict(\n backend='petrel',\n path_mapping=dict({\n '.data/INPLACEHOLD/': 's3://openmmlab/datasets/detection/INPLACEHOLD/',\n 'd...
def main(): args = parse_args() assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"' if (args.eval and ...
def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--resume-from', help='the checkpoint file to resume from') ...
def get_device(): 'Returns an available device, cpu, cuda or mlu.' is_device_available = {'cuda': torch.cuda.is_available()} device_list = [k for (k, v) in is_device_available.items() if v] return (device_list[0] if (len(device_list) == 1) else 'cpu')
def replace_ceph_backend(cfg): cfg_pretty_text = cfg.pretty_text replace_strs = "file_client_args = dict(\n backend='petrel',\n path_mapping=dict({\n '.data/INPLACEHOLD/': 's3://openmmlab/datasets/detection/INPLACEHOLD/',\n 'd...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if args.ceph: cfg = replace_ceph_backend(cfg) if (args.cfg_options is not None): for (k, v) in args.cfg_options.items(): if v.startswith('dict'): args.cfg_options[k] = eval(v) cfg.mer...
class HierarchicalContextAggregationLoss(nn.Module): '\n Implementation of Hierarchical Context Aggregation\n\n This loss combines multiple PixelwiseContextual losses with different (alpha, beta) scales.\n Given a descriptor with n-dims and n-losses scales, each loss is given n-dims//n-losses.\n Theor...
class PixelwiseContrastiveLoss(nn.Module): '\n Implementation of "pixel-wise" contrastive loss. Contrastive loss typically compares two whole images.\n L = (Y) * (1/2 * d**2) + (1 - Y) * (1/2 * max(0, margin - d)**2)\n\n In this instance, we instead compare pairs of features within those images.\...
def main(): args = parser.parse_args() device = ops.get_device() ckpt_file = Path(args.model_path, args.model_name).with_suffix('.pt') img_file = Path(args.image_file) img_np = imread(img_file) img_torch = ops.img2torch(img_np, batched=True).to(device) print(f'Image size (np): {img_np.shap...
class SiameseSand(nn.Module): def __init__(self, n_dims): super().__init__() self.n_dims = n_dims self.branch = Sand(self.n_dims) def forward(self, features): (f1, f2) = torch.chunk(features, 2, dim=2) (d1, d2) = (self.branch(f1), self.branch(f2)) out = torch....
class Timer(): 'Context manager to time a piece of code, including GPU synchronization.' def __init__(self, as_ms=False): (self.start, self.end) = (None, None) self.scale = (1000 if as_ms else 1) self.is_gpu = torch.cuda.is_available() def __enter__(self): if self.is_gpu:...
def main(): with Timer() as t: time.sleep(2) print(f'{t.elapsed} secs') with Timer(as_ms=True) as t: time.sleep(0.002) print(f'{t.elapsed} ms')
class HierarchicalContextAggregationLoss(nn.Module): '\n Implementation of Hierarchical Context Aggregation\n\n This loss combines multiple PixelwiseContextual losses with different (alpha, beta) scales.\n Given a descriptor with n-dims and n-losses scales, each loss is given n-dims//n-losses.\n Theor...
class PixelwiseContrastiveLoss(nn.Module): '\n Implementation of "pixel-wise" contrastive loss. Contrastive loss typically compares two whole images.\n L = (Y) * (1/2 * d**2) + (1 - Y) * (1/2 * max(0, margin - d)**2)\n\n In this instance, we instead compare pairs of features within those images.\...
class SSIM(nn.Module): 'Layer to compute the weighted SSIM and L1 loss between a pair of images' def __init__(self, ssim_weight=0.85): super().__init__() self.a = ssim_weight self.b = (1 - ssim_weight) self.pool = nn.AvgPool2d(3, 1) self.refl = nn.ReflectionPad2d(1) ...
@dataclass(eq=False) class BaseModel(nn.Module): '\n Base class for PyTorch networks, expanding nn.Module.\n\n Initialization parameters will be automatically added to the state_dict and checked when loading a checkpoint\n\n Required:\n :method forward: Model forward pass (PyTorch standard)\n\n ...
class ConvBlock(nn.Module): def __init__(self, in_ch, out_ch, k_size, stride=1, padding=None, dilation=1, *, bias=False, batch_norm=True, momentum=0.1, activation=None, drop_rate=None): super().__init__() layers = OrderedDict() padding = (padding or (dilation if (dilation > 1) else (k_siz...
class ResidualBlock(nn.Module): def __init__(self, in_ch, out_ch, stride=1, padding=None, dilation=1, activation=nn.ReLU): super().__init__() self.block1 = ConvBlock(in_ch, out_ch, 3, stride, padding, dilation, activation=activation) self.block2 = ConvBlock(out_ch, out_ch, 3, 1, padding, ...
class SimpleConvBlock(nn.Module): 'Layer to perform a convolution followed by ELU' def __init__(self, in_channels, out_channels): super().__init__() self.conv = Conv3x3(in_channels, out_channels) self.nonlin = nn.ELU(inplace=True) def forward(self, x): return self.nonlin(...
class Conv3x3(nn.Module): 'Layer to pad and convolve input' def __init__(self, in_channels, out_channels, use_refl=True): super().__init__() self.pad = (nn.ReflectionPad2d(1) if use_refl else nn.ZeroPad2d(1)) self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3) def forwa...
@dataclass(eq=False) class DeFeatNet(BaseModel): num_layers: int preres: bool scales: list = range(4) use_skips: bool = True n_dims: int = 3 spp_branches: list = None activation: str = 'relu' im_pad: int = None norm: bool = True def __post_init__(self): super().__post_...
@dataclass(eq=False) class DepthNet(BaseModel): num_layers: int preres: bool = True scales: list = range(4) use_skips: bool = True def __post_init__(self): super().__post_init__() self.enc_ch = np.array([64, 64, 128, 256, 512]) self.dec_ch = np.array([16, 32, 64, 128, 256]...
def discriminator(glove, hidden_size): hypo_input = Input(shape=(None,), dtype='int32') embeds = make_fixed_embeddings(glove, None)(hypo_input) lstm = LSTM(hidden_size, inner_activation='sigmoid')(embeds) output = Dense(1, activation='sigmoid')(lstm) discriminator = Model([hypo_input], output) ...
def adverse_model(discriminator): train_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') def margin_opt(inputs): assert (len(inputs) == 2), ('Margin Output needs 2 inputs, %d given' % len(inputs)) return (K.log(inputs[0]) + K.log((1 - inputs[1])...
def minimize(y_true, y_pred): return K.abs(K.mean(y_pred, axis=(- 1)))
def reinit(ad_model): ad_model.compile(loss=minimize, optimizer='adam')
class FeedLSTM(LSTM): def __init__(self, feed_layer=None, **kwargs): self.feed_layer = feed_layer self.supports_masking = False super(FeedLSTM, self).__init__(**kwargs) def set_state(self, noise): K.set_value(self.states[1], noise) def get_initial_states(self, x): ...
class LstmAttentionLayer(LSTM): def __init__(self, feed_state=False, **kwargs): self.feed_state = feed_state self.supports_masking = False super(LstmAttentionLayer, self).__init__(**kwargs) def get_output_shape_for(self, input_shape): if self.return_sequences: ret...
def train(train, dev, model, model_dir, batch_size): if (not os.path.exists(model_dir)): os.makedirs(model_dir) es = EarlyStopping(patience=2) saver = ModelCheckpoint((model_dir + '/model.weights'), monitor='val_loss', save_best_only=True) csv = CsvHistory((model_dir + '/history.csv')) ret...
def attention_model(hidden_size, glove): prem_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') prem_embeddings = make_fixed_embeddings(glove, None)(prem_input) hypo_embeddings = make_fixed_embeddings(glove, None)(hypo_input) premise_layer = LSTM(output_d...
def attention_bnorm_model(hidden_size, glove): prem_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') prem_embeddings = make_fixed_embeddings(glove, None)(prem_input) hypo_embeddings = make_fixed_embeddings(glove, None)(hypo_input) premise_layer = LSTM(ou...
def make_fixed_embeddings(glove, seq_len): glove_mat = np.array(glove.values()) return Embedding(input_dim=glove_mat.shape[0], output_dim=glove_mat.shape[1], weights=[glove_mat], trainable=False, input_length=seq_len)
class CsvHistory(Callback): def __init__(self, filename): self.file = open(filename, 'a', 0) self.writer = csv.writer(self.file) self.header = True def on_epoch_end(self, epoch, logs={}): if self.header: self.writer.writerow((['epoch'] + logs.keys())) ...
def merge_result_batches(batches): res = list(batches[0]) for i in range(1, len(batches)): for j in range(len(res)): res[j] = np.concatenate([res[j], batches[i][j]]) return res
class HierarchicalSoftmax(Layer): def __init__(self, output_dim, init='glorot_uniform', **kwargs): self.init = initializations.get(init) self.output_dim = output_dim def hshape(n): from math import sqrt, ceil l1 = ceil(sqrt(n)) l2 = ceil((n / l1)) ...
def hs_categorical_crossentropy(y_true, y_pred): y_pred = T.clip(y_pred, _EPSILON, (1.0 - _EPSILON)) return T.nnet.categorical_crossentropy(y_pred, y_true)
def add_path(path): if (path not in sys.path): sys.path.insert(0, path)
def update_config(config_file): exp_config = None with open(config_file) as f: exp_config = edict(yaml.load(f, Loader=yaml.SafeLoader)) for (k, v) in exp_config.items(): if (k in config): if isinstance(v, dict): if (k == 'TRAIN'): ...
def _load_general(data, targets, major_axis): 'Load a list of arrays into a list of arrays specified by slices' for (d_src, d_targets) in zip(data, targets): if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) elif isinstance(d_src, (list, tuple)): for (src, d...
def _load_data(batch, targets, major_axis): 'Load data into sliced arrays' _load_general(batch.data, targets, major_axis)
def _load_label(batch, targets, major_axis): 'Load label into sliced arrays' _load_general(batch.label, targets, major_axis)
def _merge_multi_context(outputs, major_axis): 'Merge outputs that lives on multiple context into one, so that they look\n like living on one context.\n ' rets = [] for (tensors, axis) in zip(outputs, major_axis): if (axis >= 0): rets.append(nd.concatenate(tensors, axis=axis, alw...
class DataParallelExecutorGroup(object): "DataParallelExecutorGroup is a group of executors that lives on a group of devices.\n This is a helper class used to implement data parallelization. Each mini-batch will\n be split and run on the devices.\n\n Parameters\n ----------\n symbol : Symbol\n ...
class Speedometer(object): def __init__(self, batch_size, frequent=50): self.batch_size = batch_size self.frequent = frequent self.init = False self.tic = 0 self.last_count = 0 def __call__(self, param): 'Callback to Show speed.' count = param.nbatch ...
def do_checkpoint(prefix, means, stds): def _callback(iter_no, sym, arg, aux): arg['bbox_pred_weight_test'] = (arg['bbox_pred_weight'].T * mx.nd.array(stds)).T arg['bbox_pred_bias_test'] = ((arg['bbox_pred_bias'] * mx.nd.array(stds)) + mx.nd.array(means)) mx.model.save_checkpoint(prefix, ...
def test_rcnn(cfg, dataset, image_set, root_path, dataset_path, ctx, prefix, epoch, vis, ignore_cache, shuffle, has_rpn, proposal, thresh, logger=None, output_path=None, nms_dets=None, is_docker=False): if (not logger): assert False, 'require a logger' datasets = dataset.split(';') dataset_paths =...
def train_rcnn(cfg, dataset, image_set, root_path, dataset_path, frequent, kvstore, flip, shuffle, resume, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, train_shared, lr, lr_step, proposal, logger=None, output_path=None): mx.random.seed(np.random.randint(10000)) np.random.seed(np.random.randint(1000...