code
stringlengths
101
5.91M
def _parse_prolog_expression(tree): _features = [] for line in tree.splitlines(): if (':-' in line): _rhs = line.split(':-')[1] for _portion in _rhs.split(' '): if ('(' in _portion): _features += [_portion.split('(')[0]] return _features
def main(argv=sys.argv[1:]): p = argparse.ArgumentParser() p.add_argument('input_files', nargs='+') p.add_argument('-o', '--output') args = p.parse_args(argv) assert args.output, 'must specify -o' output_filename = args.output outfp = bgzf.open(output_filename, 'wb') print('output file w...
def add_jpeg_decoding(input_width, input_height, input_depth, input_mean, input_std): jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32) decoded_image_4d = tf...
def knn(x: torch.Tensor, y: torch.Tensor, k: int, batch_x: Optional[torch.Tensor]=None, batch_y: Optional[torch.Tensor]=None, cosine: bool=False, num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor: if ((x.numel() == 0) or (y.numel() == 0)): return torch.empty(2, 0, dtype=torch.long, device=...
def write_file(num_of_users): f = open('./darknet/data/train.txt', 'w') for user in range(num_of_users): f.write('data/dog.jpg\n') f.close()
def index_in_saturation(A, proof=True): r = A.rank() if (r == 0): return ZZ.one() if (r < A.nrows()): A = A.hermite_form(proof=proof, include_zero_rows=False) if A.is_square(): return abs(A.determinant(proof=proof)) A = A.transpose() A = A.hermite_form(proof=proof, includ...
def main(): args = parse_arguments() args.output_dir.mkdir(exist_ok=True) for subdir in ('train', 'valid', 'test'): (args.output_dir / subdir).mkdir(exist_ok=True) assert (args.n_jobs >= 1), '`n_jobs` must be a positive integer.' setup_loggers(filename=(args.output_dir / Path(__file__).with_...
def ken_lm_abs_score_bpe_strings_dense(handle, bpe_merge_symbol, strings, labels): return get_tf_mod().ken_lm_abs_score_bpe_strings_dense(handle=handle, bpe_merge_symbol=bpe_merge_symbol, strings=strings, labels=labels)
class SennaVocab(EmbeddedVocab): embeddings_url = ' words_url = ' n_dim = 50 def __init__(self, unk='UNKNOWN'): super(SennaVocab, self).__init__(unk=unk) def gen_word_list(cls, fname): with open(fname) as f: for line in f: (yield line.rstrip('\n\r')) d...
def tf_efficientnet_es(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet_edge('tf_efficientnet_es', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs) return model
class ZoomWidget(): def __init__(self, viz): self.viz = viz self.fov = 18.837 self.fov_default = 18.837 _utils.scoped_by_object_id def __call__(self, show=True): viz = self.viz if show: imgui.text('FOV') imgui.same_line(viz.label_w) ...
def direct_mask_generation(rep_mask, direct, attn_self, name=None): assert (direct in ['forward', 'backward']) with tf.name_scope((name or 'direct_mask_generation')): rep_shape = get_shape_list(rep_mask, 2) (bs, sl) = rep_shape rep_mask_epd1 = tf.expand_dims(rep_mask, 1) rep_mask...
class MLflowCallback(TrainerCallback): def __init__(self): if (not is_mlflow_available()): raise RuntimeError('MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.') import mlflow self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH ...
class CupyFrontend(): def argument(cupy_ndarray: 'cp.ndarray'): return cuda.CUdeviceptr(int(cupy_ndarray.data.ptr))
def attention_decoder(decoder_inputs, initial_state, attention_states, cell, output_size=None, num_heads=1, loop_function=None, dtype=None, scope=None, initial_state_attention=False): if (not decoder_inputs): raise ValueError('Must provide at least 1 input to attention decoder.') if (num_heads < 1): ...
class VGG(nn.Module): def __init__(self, args, conv3x3=common.default_conv, conv1x1=None): super(VGG, self).__init__() norm = common.default_norm bias = (not args.no_bias) configs = {'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'B': [64, 64, 'M', 128, 128, '...
class CrossEntropyLoss2d(nn.Module): def __init__(self, weight=None): super().__init__() self.loss = nn.NLLLoss2d(weight) def forward(self, outputs, targets): return self.loss(F.log_softmax(outputs, 1), targets)
class THNNFunctionBackend(FunctionBackend): def __reduce__(self): return (_get_thnn_function_backend, ()) def __deepcopy__(self, memo): memo[id(self)] = self return self def __copy__(self): return self
def mean_std_per_layer(convs): res = {} for i in tqdm(range(len(convs))): df = pd.DataFrame() w = convs[i][1].weight w = w.view(w.shape[0], (- 1)).detach().numpy() df['mean'] = w.mean((- 1)) df['std'] = w.std((- 1)) df['range'] = (w.max((- 1)) - w.min((- 1))) ...
class FileTypes(enum.Enum): T1 = 1 T2 = 2 GT = 3 MASK = 4 AGE = 5 GPA = 6 GENDER = 7
def get_idx_and_Y(df, task, split): train_idx = df[(df[split] == 'Train')].index valid_idx = df[(df[split] == 'Test')].index test_idx = df[(df[split] == 'Ext')].index def _apply_float(x): if (type(x) == float): return x else: x = x.replace(',', '.') re...
class BaseResults(): def __init__(self): self.strategy_names = [] self.dataset_names = [] self.cv = None def save_predictions(self, strategy_name, dataset_name, y_true, y_pred, y_proba, index, cv_fold, train_or_test): raise NotImplementedError() def load_predictions(self, cv_...
def make_conv_out_spatial_dims(in_spatial_dims: Sequence[Dim], *, filter_size: Union[(Sequence[Union[(int, Dim)]], int, Dim)], padding: str, strides: Union[(Sequence[int], int)]=1, dilation_rate: Union[(Sequence[int], int)]=1, description_prefix: Optional[str]=None) -> Sequence[Dim]: nd = len(in_spatial_dims) i...
class AtomicOpsPlan(BenchmarkPlan): def __init__(self, arch: str): super().__init__('atomic_ops', arch, basic_repeat_times=10) atomic_ops = AtomicOps() atomic_ops.remove(['atomic_sub', 'atomic_and', 'atomic_xor', 'atomic_max']) self.create_plan(atomic_ops, Container(), DataType(), Da...
_test() def test_hardware_axpy_double_pump_vec2(): return test_hardware_axpy_double_pump(veclen=2)
class CocoDistEvalRecallHook(DistEvalHook): def __init__(self, dataset, proposal_nums=(100, 300, 1000), iou_thrs=np.arange(0.5, 0.96, 0.05)): super(CocoDistEvalRecallHook, self).__init__(dataset) self.proposal_nums = np.array(proposal_nums, dtype=np.int32) self.iou_thrs = np.array(iou_thrs, ...
class FreeModuleTensor(ModuleElementWithMutability): _fmodule: FiniteRankFreeModule def __init__(self, fmodule: FiniteRankFreeModule, tensor_type, name: Optional[str]=None, latex_name: Optional[str]=None, sym=None, antisym=None, parent=None): if (parent is None): parent = fmodule.tensor_modu...
def create_learner(seed: int, observations: jnp.ndarray, actions: jnp.ndarray, value_def, actor_lr: float=0.0003, value_lr: float=0.0003, critic_lr: float=0.0003, value_tx=None, hidden_dims: Sequence[int]=(256, 256), discount: float=0.99, tau: float=0.005, expectile: float=0.8, temperature: float=0.1, dropout_rate: Opt...
def parse_args(): parser = argparse.ArgumentParser(description='OpenSelfSup extract features of a model') parser.add_argument('config', help='test config file path') parser.add_argument('--checkpoint', default=None, help='checkpoint file') parser.add_argument('--pretrained', default='random', help='pret...
def collect_env_info(): has_gpu = torch.cuda.is_available() torch_version = torch.__version__ from torch.utils.cpp_extension import CUDA_HOME has_rocm = False if (tuple(map(int, torch_version.split('.')[:2])) >= (1, 5)): from torch.utils.cpp_extension import ROCM_HOME if ((getattr(to...
def main(): global LstmCellTypes print('Benchmarking LSTMs.') better_exchook.install() print('Args:', ' '.join(sys.argv)) arg_parser = ArgumentParser() arg_parser.add_argument('cfg', nargs='*', help=('opt=value, opt in %r' % sorted(base_settings.keys()))) arg_parser.add_argument('--no-cpu', ...
def init_train_step_run_ctx(*, train_flag: Union[(bool, Tensor)]=True, step: Union[(int, Tensor)]=0, epoch: Union[(int, Tensor)]=1): global _run_ctx _run_ctx = RunCtx(stage='train_step', train_flag=train_flag, step=step, epoch=epoch)
def reject_location_related_install_options(requirements, options): def format_options(option_names): return ['--{}'.format(name.replace('_', '-')) for name in option_names] offenders = [] for requirement in requirements: install_options = requirement.install_options location_options...
_start_docstrings('\n MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n ', MMBT_START_DOCSTRING, MMBT_INPUTS_DOCSTRING) class MMBTForClassification(nn.Module): def __init__(self, config, transformer, encoder): super().__init__() sel...
def _simplify_operator(element: Union[(SparsePauliOp, OpTreeOperator)]) -> Union[(SparsePauliOp, OpTreeOperator)]: if isinstance(element, OpTreeOperator): operator = element.operator input_type = 'leaf' else: operator = element input_type = 'operator' pauli_list = [] coef...
def RNNTanhCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None): hy = torch.tanh((F.linear(input, w_ih, b_ih) + F.linear(hidden, w_hh, b_hh))) return hy
def register_Ns3UplinkLteGlobalPathlossDatabase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::UplinkLteGlobalPathlossDatabase const &', 'arg0')]) cls.add_method('UpdatePathloss', 'void', [param('std::string', 'context'), param('ns3::Ptr< ns3::SpectrumPhy >', 'txPhy'), p...
def infer_dim_tags(*, name, batch_dim_axis=NotSpecified, time_dim_axis=NotSpecified, feature_dim_axis=NotSpecified, dim_tags: Optional[Sequence[Dim]]=None, shape: Optional[Sequence[Optional[int]]]=None, sparse_dim: Optional[Dim]=None, dim=NotSpecified, size_placeholder=None, auto_create_placeholders=False, batch=None, ...
class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, no_norm=False, activation='relu'): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, bias=False) self.multihead_attn = nn.MultiheadAttentio...
def aggregate_meanpool(features, agg_transform_size, adj_with_self_loops_indices, degrees, num_nodes, num_features, name): with tf.name_scope(name): (self_indices, neighbours_indices) = adj_with_self_loops_indices fc_weights = tf.get_variable(f'{name}-fc_weights', shape=[num_features, agg_transform_...
_loss def distribution_focal_loss(pred, label): dis_left = label.long() dis_right = (dis_left + 1) weight_left = (dis_right.float() - label) weight_right = (label - dis_left.float()) loss = ((F.cross_entropy(pred, dis_left, reduction='none') * weight_left) + (F.cross_entropy(pred, dis_right, reducti...
def eval_epoch(args, model, test_dataloader, device, n_gpu): if hasattr(model, 'module'): model = model.module.to(device) else: model = model.to(device) multi_sentence_ = False (cut_off_points_, sentence_num_, pair_num_) = ([], (- 1), (- 1)) if (hasattr(test_dataloader.dataset, 'mult...
def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'): assert os.path.isdir(directory), 'dataset is not exists!{}'.format(directory) return sorted([os.path.join(root, f) for (root, _, files) in os.walk(directory) for f in files if re.match((('([\\w]+\\.(?:' + ext) + '))'), f)])
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val * n) self.count += n self.avg = ((self.sum /...
def test_wrap_bare_list(): data = [1, 2, 3, 4, 5] index = ak.index.Index64(data) other_data = np.asarray(index) assert (other_data.tolist() == data)
class CUBDataset(ConfounderDataset): def __init__(self, root_dir, target_name, confounder_names, augment_data=False, model_type=None): self.root_dir = root_dir self.target_name = target_name self.confounder_names = confounder_names self.model_type = model_type self.augment_da...
.flaky def test_exponential_distribution(): q_max = 100.0 sample = stellar_mass.schechter_smf_mass(0, 0, 1, size=1000, m_min=1e-10, m_max=q_max, resolution=1000) (d, p_value) = scipy.stats.kstest(sample, 'truncexpon', args=(q_max,)) assert (p_value >= 0.01)
def get_op_args(declaration, argmap): call_args_override = declaration.get('call_args') if call_args_override: keys = call_args_override else: keys = [param['name'] for param in declaration['arguments']] if is_tensor_method(declaration): keys = [k for k in keys if (k != 'self')] ...
class SingleDeconv3DBlock(nn.Module): def __init__(self, in_planes, out_planes): super().__init__() self.block = nn.ConvTranspose3d(in_planes, out_planes, kernel_size=2, stride=2, padding=0, output_padding=0) def forward(self, x): return self.block(x)
def move_to_cuda(sample): if (len(sample) == 0): return {} def _move_to_cuda(maybe_tensor): if torch.is_tensor(maybe_tensor): return maybe_tensor.cuda() elif isinstance(maybe_tensor, dict): return {key: _move_to_cuda(value) for (key, value) in maybe_tensor.items()...
class BatchNormBatchStat(BatchNorm2d): def forward(self, input): if self.training: return super().forward(input) return F.batch_norm(input, None, None, self.weight, self.bias, True, 1.0, self.eps)
class MMBTForClassification(): def __init__(self, *args, **kwargs): requires_pytorch(self)
_dispatch def dct(x, type=2, n=None, axis=(- 1), norm=None, overwrite_x=False, workers=None, orthogonalize=None): return (Dispatchable(x, np.ndarray),)
def get_hip_file_path(filepath, is_pytorch_extension=False): if ((not is_pytorch_extension) and (not is_out_of_place(filepath))): return filepath (dirpath, filename) = os.path.split(filepath) (root, ext) = os.path.splitext(filename) if (ext == '.cu'): ext = '.hip' orig_filename = fil...
def pointnet_fp_module(xyz1, xyz2, points1, points2, mlp, is_training, bn_decay, scope, bn=True): with tf.variable_scope(scope) as sc: (dist, idx) = three_nn(xyz1, xyz2) dist = tf.maximum(dist, 1e-10) norm = tf.reduce_sum((1.0 / dist), axis=2, keep_dims=True) norm = tf.tile(norm, [1,...
def create_mounts(mode, base_log_dir, sync_interval=180, local_input_dir_to_mount_point_dict=None): if (mode == 'sss'): code_mounts = SSS_CODE_MOUNTS non_code_mounts = SSS_NON_CODE_MOUNTS else: code_mounts = CODE_MOUNTS non_code_mounts = NON_CODE_MOUNTS if (local_input_dir_to...
def normalize_obs(obs, mean, std): if (mean is not None): return np.divide((obs - mean), std) else: return obs
class Explore_Decoder_Graph_Explorative(): def __init__(self, DISCOURSE_SENTENCE_MODEL, MAX_SPLIT_PAIR_SIZE, RESTRICTED_DROP_REL, ALLOWED_DROP_MOD, probability_tables, METHOD_FEATURE_EXTRACT): self.DISCOURSE_SENTENCE_MODEL = DISCOURSE_SENTENCE_MODEL self.MAX_SPLIT_PAIR_SIZE = MAX_SPLIT_PAIR_SIZE ...
def create_r_action(action): def r_action(tn, t): token_hit = tn def fn(world, n): if (n > MAX_FUNC_CALL): (token_hit, n, False) try: world.state_transition(action) except: return (token_hit, n, False) el...
class xDeepFM(BaseModel): def __init__(self, linear_feature_columns, dnn_feature_columns, dnn_hidden_units=(256, 256), cin_layer_size=(256, 128), cin_split_half=True, cin_activation='relu', l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_dnn=0, l2_reg_cin=0, init_std=0.0001, seed=1024, dnn_dropout=0, dnn_activa...
def create_train_parser(base_parser: argparse.ArgumentParser) -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description='Run Training on the TAPE datasets', parents=[base_parser]) parser.add_argument('task', choices=list(registry.task_name_mapping.keys()), help='TAPE Task to train/eval on') p...
_numpy_output(check_dtype=True) def test_ufunc_negative_f(A: dace.float32[10]): return np.negative(A)
def return_emb2(k, j): config = Config() outfile = ((config.emb + config.data) + '2') hf = h5py.File((outfile + '.h5'), 'r') kk = k if ((k % 32) != 0): k = (k - (k % 32)) n1 = hf.get(('dataset_' + str(k))) n1 = np.array(n1) if (((kk % 32) + j) > 32): n2 = hf.get(('dataset...
def get_parallel_factor(k, lamada, sequence, phyche_value): theta = [] l = len(sequence) for i in range(1, (lamada + 1)): temp_sum = 0.0 for j in range(0, (((l - k) - i) + 1)): nucleotide1 = sequence[j:(j + k)] nucleotide2 = sequence[(j + i):((j + i) + k)] ...
def remove_specific_requirements(reqs): rtd = ('READTHEDOCS' in os.environ) excluded = {'fasttext': rtd} updated_reqs = [] for req in reqs: without_version = req.split('==')[0] if (not excluded.get(without_version, False)): updated_reqs.append(req) return updated_reqs
def _vggface2_nonmates(): np.random.seed(42) return VGGFace2('/proj/janus6/vggface2').take_per_subject(1)
def F0_close(x, y): e = (y - x) L = (((((- x) * e) + (((1 / 6) * ((x ** 2) - 2)) * (e ** 2))) - ((1 / 180) * (((x ** 4) + (2 * (x ** 2))) - 8))) + np.log(((2 * e) / np.sqrt(np.pi)))) return (L - (x ** 2))
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1): super().__init__() assert ((dim % num_heads) == 0), f'dim {dim} should be divided by num_heads {num_heads}.' self.dim = dim self.num_heads = num_...
def test_combine_workspace_deepcopied(workspace_factory): ws = workspace_factory() new_ws = ws.rename(channels={channel: f'renamed_{channel}' for channel in ws.channels}) new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0]['bounds'] = [[0.0, 1.0]] new_ws['observations'][0]...
def test_unflatten_raises_for_invalid_shape() -> None: x_old = tf.random.uniform([2, 3, 4, 5]) (flat_x_old, unflatten) = flatten_leading_dims(x_old) with pytest.raises(TF_DEBUGGING_ERROR_TYPES): unflatten(x_old)
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, args, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[Mixup]=None, saver=None, start_steps=None, lr_schedule_values=No...
def extract_nums(s): s = s.replace(',', '') nums = re.findall('[+-]? *(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?', s) return_list = [] for i in range(len(nums)): try: return_list.append(eval(nums[i].strip().lstrip(' 0'))) except: pass return return_list
def _find_nn(syn: pd.DataFrame, ori: pd.DataFrame, n_jobs: int, n_neighbors: int) -> np.ndarray: nn = MixedTypeKNeighbors(n_jobs=n_jobs, n_neighbors=n_neighbors) if (syn.ndim == 1): syn = syn.to_frame() if (ori.ndim == 1): ori = ori.to_frame() nn.fit(syn) return cast(np.ndarray, nn.k...
def get_pitch_classes(fifths: int) -> List[int]: if (fifths >= 0): return [0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6] return [0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6]
def export_gt_depths_kitti(): parser = argparse.ArgumentParser(description='export_gt_depth') parser.add_argument('--data_path', type=str, help='path to the root of the KITTI data', required=True) parser.add_argument('--split', type=str, help='which split to export gt from', default='eigen', choices=['eigen...
class SchemeHomset_toric_variety(SchemeHomset_generic): def __init__(self, X, Y, category=None, check=True, base=ZZ): SchemeHomset_generic.__init__(self, X, Y, category=category, check=check, base=base) from sage.schemes.toric.variety import is_ToricVariety if (is_ToricVariety(X) and is_Tori...
class GoogleNet(Network): def setup(self): self.feed('data').conv(7, 7, 64, 2, 2, name='conv1_7x7_s2').max_pool(3, 3, 2, 2, name='pool1_3x3_s2').lrn(2, 2e-05, 0.75, name='pool1_norm1').conv(1, 1, 64, 1, 1, name='conv2_3x3_reduce').conv(3, 3, 192, 1, 1, name='conv2_3x3').lrn(2, 2e-05, 0.75, name='conv2_norm2...
def residual_model(input_shape): inputs = Input(shape=input_shape) y = Conv2D(7, 8)(inputs) x = BatchNormalization()(y) x = Activation('relu')(x) outputs = Add()([x, y]) model = keras.Model(inputs=inputs, outputs=outputs) return model
def init_random_state(seed=0): import torch import random random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def train_one_epoch(epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir=None, amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None): if (args.mixup_off_epoch and (epoch >= args.mixup_off_epoch)): if (args.prefetcher and loader.mixup_enabled): ...
class BasicBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, ker...
class TestSumPricesTabular(unittest.TestCase): def setUp(self): return super().setUp() def test_dataset_corrupted(self): with self.assertRaises(RuntimeError, msg=M.DATASET_NOT_FOUND): SumPricesRegression(root='./dummy_dir') def tearDown(self): return super().tearDown()
def freeze_bn_stats(mod): if (type(mod) in set([ConvBnReLU1d, ConvBnReLU2d, ConvBnReLU3d, ConvBn1d, ConvBn2d, ConvBn3d])): mod.freeze_bn_stats()
class RandomHorizontalFlipVideo(): def __init__(self, p=0.5): self.p = p def __call__(self, clip): if (random.random() < self.p): clip = F.hflip(clip) return clip def __repr__(self) -> str: return f'{self.__class__.__name__}(p={self.p})'
class resblock(nn.Module): def __init__(self, in_channels, out_channels): super(resblock, self).__init__() self.conv1 = mfm(in_channels, out_channels, kernel_size=3, stride=1, padding=1) self.conv2 = mfm(in_channels, out_channels, kernel_size=3, stride=1, padding=1) self.add = Add() ...
def interleave_datasets(datasets, probabilities=None, probabilities_handle=None, seed=None, stopping_strategy='all_exhausted'): iterable_datasets = [] for dataset in datasets: if (not isinstance(dataset, IterableDataset)): iterable_datasets.append(dataset.to_iterable_dataset()) else:...
def test_explicit_broadcasting(): nparray = np.arange(((2 * 3) * 5)).reshape(2, 3, 5) lsarray = ak.highlevel.Array(nparray.tolist(), check_valid=True) rgarray = ak.highlevel.Array(nparray, check_valid=True) assert (to_list((rgarray + np.array([[[100]], [[200]]]))) == to_list((nparray + np.array([[[100]]...
class PointPillar(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() def forward(self, batch_dict): for cur_module in self.module_list: if...
def deleteContext(broker, ctxObj): broker = broker.rsplit('/', 1)[0] print(broker) headers = {'Accept': 'application/ld+json', 'Content-Type': 'application/json'} response = requests.delete(((broker + '/ngsi-ld/v1/entities/') + ctxObj['id']), headers=headers) if (response.status_code != 200): ...
.run_in_serial _utils.test(arch=ti.cuda) def test_memory_allocate(): HUGE_SIZE = ((1024 ** 2) * 128) x = ti.field(ti.i32, shape=(HUGE_SIZE,)) for i in range(10): x[i] = i
def test_pipeline_with_step_that_it_is_pipeline(): (X, y) = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=5000, random_state=0) clf = LogisticRegression(solver='lbfgs') rus = RandomUnderSampler(ran...
class SmoothBivariateSpline(BivariateSpline): def __init__(self, x, y, z, w=None, bbox=([None] * 4), kx=3, ky=3, s=None, eps=None): (xb, xe, yb, ye) = bbox (nx, tx, ny, ty, c, fp, wrk1, ier) = dfitpack.surfit_smth(x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1) if (ier > 10): ...
def main(H, vis): quanitzer_and_generator_state_dict = retrieve_autoencoder_components_state_dicts(H, ['quantize', 'generator'], remove_component_from_key=True) embedding_weight = quanitzer_and_generator_state_dict.pop('embedding.weight') embedding_weight = embedding_weight.cuda() generator = Generator(...
class SRWLOptT(SRWLOpt): def __init__(self, _nx=1, _ny=1, _rx=0.001, _ry=0.001, _arTr=None, _extTr=0, _Fx=1e+23, _Fy=1e+23, _x=0, _y=0, _ne=1, _eStart=0, _eFin=0, _alloc_base=[0]): self.arTr = _arTr if ((_arTr is None) or ((len(_arTr) != (((_ne * _nx) * _ny) * 2)) and (((_ne * _nx) * _ny) > 0))): ...
class ImageEncoder(nn.Module): def __init__(self, size_image, num_output_length, if_tanh=False): super(ImageEncoder, self).__init__() self.if_tanh = if_tanh self.conv1 = nn.Sequential(nn.Conv2d(3, 16, 5, stride=2, padding=2), nn.ReLU(inplace=True)) self.conv2 = nn.Sequential(nn.Conv2...
def slerp(z_A, z_B, t, eps=1e-20): cos_val = (z_A * z_B).sum(dim=1, keepdim=True) temp_z_A = z_A.pow(2).sum(dim=1, keepdim=True).sqrt() temp_z_B = z_B.pow(2).sum(dim=1, keepdim=True).sqrt() cos_val = (cos_val / z_A.pow(2).sum(dim=1, keepdim=True).sqrt()) cos_val = (cos_val / z_B.pow(2).sum(dim=1, ke...
_model def regnetx_064(pretrained=False, **kwargs): return _regnet('regnetx_064', pretrained, **kwargs)
def get_image_list(image_dir, count=0): image_path_list = [] for image_name in os.listdir(image_dir): if is_image_file(image_name): image_path_list.append(os.path.join(image_dir, image_name)) end = (count if (count > 0) else len(image_path_list)) return image_path_list[0:end]
_SEG_HEADS_REGISTRY.register() class M2FPHead(nn.Module): _version = 2 def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): version = local_metadata.get('version', None) if ((version is None) or (version < 2)): scratc...
class DeterministicGuard(): def __init__(self, deterministic): self.deterministic = deterministic def __enter__(self): self.deterministic_restore = torch.are_deterministic_algorithms_enabled() torch.use_deterministic_algorithms(self.deterministic) def __exit__(self, exception_type, e...