code
stringlengths
101
5.91M
def parse_args(): parser = argparse.ArgumentParser(description='Video Pose Network') parser.add_argument('--dataset', default='ntu60', type=str, choices=['ntu60', 'ntu120', 'smarthomes', 'nucla'], help='training dataset') parser.add_argument('--epochs', default=250, type=int, help='max mumber of epochs for ...
def get_open_fds(): import subprocess import os pid = os.getpid() procs = subprocess.check_output(['lsof', '-w', '-Ff', '-p', str(pid)]) procs = procs.decode('utf-8') procs = procs.split('\n') procs = list(filter((lambda s: (s and (s[0] == 'f') and s[1:].isdigit())), procs)) return procs
def test_orthogonal_procrustes_ndim_too_large(): np.random.seed(1234) A = np.random.randn(3, 4, 5) B = np.random.randn(3, 4, 5) assert_raises(ValueError, orthogonal_procrustes, A, B)
def test_sanity_compute_3(simpledf: dd.DataFrame) -> None: config = {'hist.bins': 20, 'bar.bars': 15} cfg = Config.from_dict(config=config) itmdt = compute_missing(simpledf, col1='d', cfg=cfg) render_missing(itmdt, cfg)
class FfmpegFormat(Format): def _can_read(self, request): if (request.mode[1] not in 'I?'): return False if (request.filename in [('<video%i>' % i) for i in range(10)]): return True if (request.extension in self.extensions): return True def _can_write(...
class CutoffTimeBasedStragglerHandling(StragglerHandlingFunction): def __init__(self, round_start_time=None, straggler_cutoff_time=np.inf, minimum_reporting=1, **kwargs): self.round_start_time = round_start_time self.straggler_cutoff_time = straggler_cutoff_time self.minimum_reporting = mini...
class TranslationUnitSaveError(Exception): ERROR_UNKNOWN = 1 ERROR_TRANSLATION_ERRORS = 2 ERROR_INVALID_TU = 3 def __init__(self, enumeration, message): assert isinstance(enumeration, int) if ((enumeration < 1) or (enumeration > 3)): raise Exception(('Encountered undefined Tr...
_utils.test(require=ti.extension.sparse) def test_pointer2(): x = ti.field(ti.f32) s = ti.field(ti.i32) n = 128 ti.root.pointer(ti.i, n).dense(ti.i, n).place(x) ti.root.place(s) def activate(): for i in range((n * n)): x[i] = i def func(): for i in x: ...
def test_default_parameters_BlockBootstrap() -> None: cv = BlockBootstrap() assert (cv.n_resamplings == 30) assert (cv.length is None) assert (cv.n_blocks is None) assert (not cv.overlapping) assert (cv.random_state is None)
class InceptionV3(nn.Module): def __init__(self, num_classes=10): super().__init__() self.Conv2d_1a_3x3 = BasicConv2d(3, 32, kernel_size=3, padding=1) self.Conv2d_2a_3x3 = BasicConv2d(32, 32, kernel_size=3, padding=1) self.Conv2d_2b_3x3 = BasicConv2d(32, 64, kernel_size=3, padding=1)...
class DatasetEvaluator(): def reset(self): pass def process(self, input, output): pass def evaluate(self): pass
def threeway_split(n, k_validate, k_test, exclude=[]): full = generate_indices(n, exclude) (model_building, test) = generate_distinct_sets(full, k_test) (rest, validate) = generate_distinct_sets(model_building, k_validate) return (rest, validate, test)
def train(model, device, train_loader, criterion, optimizer, scheduler, epoch, iter_meter, experiment): model.train() data_len = len(train_loader.dataset) with experiment.train(): for (batch_idx, _data) in enumerate(train_loader): (spectrograms, labels, input_lengths, label_lengths) = _d...
def test_entered_for_loop_full_loop_not_entered(simple_module, tracer_mock): adapter = BranchCoverageInstrumentation(tracer_mock) transformer = InstrumentationTransformer(tracer_mock, [adapter]) simple_module.full_for_loop.__code__ = transformer.instrument_module(simple_module.full_for_loop.__code__) tr...
class SimpleProgressBar(BaseProgressBar): def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000): super().__init__(iterable, epoch, prefix) self.log_interval = log_interval self.i = None self.size = None def __iter__(self): self.size = len(self.iterable)...
.parametrize('observation_shape', [(4,), ((4,), (8,))]) .parametrize('action_size', [2]) .parametrize('length', [100]) .parametrize('partial_length', [10]) .parametrize('batch_size', [32]) .parametrize('picker', [None, BasicTransitionPicker()]) .parametrize('slicer', [None, BasicTrajectorySlicer()]) def test_replay_buf...
def parse_match_from_known_labels(graph_parse, known_labels): assert isinstance(graph_parse, GraphParse) match_dict = {} point_key_dict = {} offset = graph_parse.image_segment_parse.diagram_image_segment.offset for (idx, d) in enumerate(known_labels): label = d['label'] x = (d['x'] -...
def make_module(mod, _module_class, _compilation_unit): if isinstance(mod, ScriptModule): return mod elif torch._jit_internal.module_has_exports(mod): infer_methods_stubs_fn = torch.jit._recursive.make_stubs_from_exported_methods return torch.jit._recursive.create_script_module(mod, infe...
class HeavyTorsoHopper(RoboschoolXMLModifierMixin, ModifiableRoboschoolHopper): def __init__(self): self.density = 1500 with self.modify_xml('hopper.xml') as tree: for elem in tree.iterfind('worldbody/body/geom'): elem.set('density', str(self.density)) RoboschoolF...
def view_policy(task, world_params, policy_fn, max_time_steps, number_of_resets, env_wrappers=np.array([]), env_wrappers_args=np.array([])): actual_skip_frame = world_params['skip_frame'] env = get_world(task.get_task_name(), task.get_task_params(), world_params, enable_visualization=True, env_wrappers=env_wrap...
def find_entry(entries, time_point, start_time): if (time_point is None): return entries[(- 1)] s = utils.time_to_seconds(time_point) last = None for entry in entries: timestamp = entry['timestamp'] elasp = (timestamp - start_time) if (elasp > s): return entry...
def test_execute_filter_method(app, schema_url): schema = oas_loaders.from_uri(schema_url, method='POST') execute(schema) assert_incoming_requests_num(app, 0)
class DmaNode(): def __init__(self, reg): self.datasize = int(reg['DMA data size(B)']) self.cycle = int(reg['Asic Cycle']) self.direction = reg['Direction']
class NoCost(CostFunction): def get_parameters(self): return [] def log_likelihood(self, states, costs): return T.zeros_like(costs) def evaluate(self, states): raise Exception('Cannot evaluate NoCost function') def is_cost_function(self): return False
_params.config def training_cfg(): optimizer = 'adam' learning_rate = 0.001 gradient_clipping = 'norm' gradient_clipping_bounds = 1 use_memory_saving_gradients = False
class DenseModel(nn.Module): def __init__(self, num_channels=3, train_enc=False, load_weight=1): super(DenseModel, self).__init__() self.dense = models.densenet161(pretrained=bool(load_weight)).features for param in self.dense.parameters(): param.requires_grad = train_enc ...
_tokenizers class GPTSanJapaneseTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = GPTSanJapaneseTokenizer test_rust_tokenizer = False from_pretrained_kwargs = {'do_clean_text': False, 'add_prefix_space': False} def setUp(self): super().setUp() vocab_tokens = ['...
def make_setuptools_egg_info_args(setup_py_path, egg_info_dir, no_user_config): args = make_setuptools_shim_args(setup_py_path, no_user_config=no_user_config) args += ['egg_info'] if egg_info_dir: args += ['--egg-base', egg_info_dir] return args
class Ngrams(object): def __init__(self, n_max=5, split_on=None): self.max_ngrams = n_max self.split_on = split_on def apply(self, s): text = get_text(s.words, s.char_offsets) if self.split_on: (words, char_offsets) = retokenize(s, self.split_on) else: ...
def VGG16_rpn_frozen_features(model): return build_generic_detection_model(model, VGG16.add_VGG16_conv5_body, freeze_conv_body=True)
class CIFAR100(CIFAR10): base_folder = 'cifar-100-python' url = ' filename = 'cifar-100-python.tar.gz' tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85' train_list = [['train', '16019d7e3df5f24257cddd939b257f8d']] test_list = [['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc']] meta = {'filename': 'met...
def solve_ineq_univar(ineq): ineqvar = ineq.variables() if (len(ineqvar) != 1): raise NotImplementedError(('The command solve_ineq_univar accepts univariate inequalities only. Your variables are ' + ineqvar)) ineq0 = ineq._maxima_() ineq0.parent().eval('if solve_rat_ineq_loaded#true then (solve_...
def register_Ns3TypeIdValue_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) cls.add_constructor([param('ns3::TypeId const &', 'value')]) cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) c...
class GCClearReferencesSlot(GCDependentSlot): def slot_code(self, scope): if scope.needs_tp_clear(): return GCDependentSlot.slot_code(self, scope) return '0'
class ASPPModule(nn.ModuleList): def __init__(self, dilations, in_channels, channels, conv_cfg, norm_cfg, act_cfg): super(ASPPModule, self).__init__() self.dilations = dilations self.in_channels = in_channels self.channels = channels self.conv_cfg = conv_cfg self.norm...
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'): if (block_type == 'block35'): branch_0 = conv2d_bn(x, 32, 1) branch_1 = conv2d_bn(x, 32, 1) branch_1 = conv2d_bn(branch_1, 32, 3) branch_2 = conv2d_bn(x, 32, 1) branch_2 = conv2d_bn(branch_2, 48, ...
def init_weights(net, init_type='normal'): if (init_type == 'normal'): net.apply(weights_init_normal) elif (init_type == 'xavier'): net.apply(weights_init_xavier) elif (init_type == 'kaiming'): net.apply(weights_init_kaiming) elif (init_type == 'orthogonal'): net.apply(we...
class SymmetricFunctionAlgebra_generic(CombinatorialFreeModule): def __init__(self, Sym, basis_name=None, prefix=None, graded=True): R = Sym.base_ring() from sage.categories.commutative_rings import CommutativeRings if (R not in CommutativeRings()): raise TypeError('argument R mu...
def advance(): for i in range(NV): acc = ((- pos.grad[i]) / (rho * (dx ** 2))) vel[i] += (dt * (acc + gravity)) vel[i] *= ti.exp(((- dt) * damping)) for i in range(NV): disp = (pos[i] - ball_pos) disp2 = disp.norm_sqr() if (disp2 <= (ball_radius ** 2)): ...
class DeltaNetBase(torch.nn.Module): def __init__(self, in_channels, conv_channels, mlp_depth, num_neighbors, grad_regularizer, grad_kernel_width, centralize_first=True): super().__init__() self.k = num_neighbors self.grad_regularizer = grad_regularizer self.grad_kernel_width = grad_...
def test_BitMaskedArray_NumpyArray(): a = ak.contents.bitmaskedarray.BitMaskedArray(ak.index.Index(np.packbits(np.array([1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1], dtype=np.uint8))), ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6])), valid_when=True, le...
def make_roi_box_predictor(cfg, in_channels): func = registry.ROI_BOX_PREDICTOR[cfg.MODEL.ROI_BOX_HEAD.PREDICTOR] return func(cfg, in_channels)
class PoolFormerBlock(nn.Module): def __init__(self, dim, pool_size=3, dpr=0.0, layer_scale_init_value=1e-05): super().__init__() self.norm1 = nn.GroupNorm(1, dim) self.token_mixer = Pooling(pool_size) self.norm2 = nn.GroupNorm(1, dim) self.drop_path = (DropPath(dpr) if (dpr ...
def _is_clashed(chunk1: tuple, chunk2: tuple, allow_level: int=NESTED): if (allow_level == FLAT): return _is_overlapping(chunk1, chunk2) elif (allow_level == NESTED): return (_is_overlapping(chunk1, chunk2) and (not _is_nested(chunk1, chunk2))) else: return False
def Phenotyping_dataset(args=None): dataset = Dataset(name='Phenotyping', path='preprocess/MIMIC_Datasets/Diagnosis/vec_diagnosis.p', max_length=20000, args=args) y = np.array(dataset.train_data.y) dataset.pos_weight = list(((len(y) / y.sum(0)) - 1)) dataset.trainer_type = 'Multi_Label' dataset.save...
def is_backend_raw_tensor_dim_tag_independent() -> bool: return _backend.global_backend.is_backend_raw_tensor_dim_tag_independent
class Measure(): def __call__(self, states, actions, next_states, next_state_means, next_state_vars, model): raise NotImplementedError
class SawyerCoffeePullEnv(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, 0.05) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.05), 0.75, 0.0) obj_high = (0.05, 0.8, 0.0) goal_low = ((- 0.1), 0.6, (- 0.001)) goal_high = (0.1, 0.7, 0.0) super().__init__...
def cyclic_graph(): classifier = HierarchicalClassifier() classifier.hierarchy_ = nx.DiGraph([('a', 'b'), ('b', 'c'), ('c', 'a')]) classifier.logger_ = logging.getLogger('HC') return classifier
class L2Norm(Component): kind = 'l2' def __init__(self, scale=1.0, context={}): super().__init__(context=context) self.scale = scale def __call__(self, mbtr, data=None): with np.errstate(divide='ignore'): mbtr /= np.linalg.norm(mbtr, axis=1, keepdims=True, ord=2) ...
class SYESRX4NetS(nn.Module): def __init__(self, channels): super(SYESRX4NetS, self).__init__() img_range = 255.0 rgb_mean = (0.4488, 0.4371, 0.404) self.img_range = img_range self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) self.headpre = AdditionFusionS(PrePyrami...
_level_function() def from_rdataframe(rdf, columns, *, keep_order=False, offsets_type='int64', with_name=None, highlevel=True, behavior=None, attrs=None): return _impl(rdf, columns, highlevel, behavior, with_name, offsets_type, keep_order)
def adjust_max(start, stop, start_value, stop_value, name=None): with ops.name_scope(name, 'AdjustMax', [start, stop, name]) as name: global_step = tf.train.get_global_step() if (global_step is not None): start = tf.convert_to_tensor(start, dtype=tf.int64) stop = tf.convert_t...
.skipif((get_model_url_base_from_env() is None), reason='models are tested only when NNABLA_MODELS_URL_BASE is specified as an envvar') .parametrize('model_class, up_to_list', [('ResNet18', ['classifier', 'pool', 'lastconv', 'lastconv+relu']), ('ResNet34', ['classifier', 'pool', 'lastconv', 'lastconv+relu']), ('ResNet5...
def _not_email(val: Any, split: bool, errtype: str, processtype: str) -> Any: if (processtype == 'coerce'): if split: return ((np.nan, np.nan, 0) if (errtype == 'null') else (np.nan, np.nan, 1)) return ((np.nan, 0) if (errtype == 'null') else (np.nan, 1)) elif (processtype == 'ignore...
def gumbel_softmax(logits, temperature, device): s = gumbel.sample(logits.shape).to(device).squeeze(2) y = (logits + s) return F.softmax((y / temperature), dim=(- 1))
class BratReader(object): def __init__(self, dir, ext=EXT, score=SCORE): self.dir = dir self.ext = ext self.len = (len(ext) + 1) self.score = score def __iter__(self): for (doc_id, fh) in self.files(): (mentions, norms) = self.read(fh) for (annot_i...
class MultiHeadAttention(nn.Module): def __init__(self, attention, num_heads, hidden_size, key_size='default', value_size='default', out_size='default'): key_size = ((hidden_size // num_heads) if (key_size == 'default') else key_size) value_size = ((hidden_size // num_heads) if (value_size == 'defau...
def get_concat_2level_model(): mel = AugmentMelSTFT(n_mels=128, sr=32000, win_length=800, hopsize=320, n_fft=1024, freqm=48, timem=192, htk=False, fmin=0.0, fmax=None, norm=1, fmin_aug_range=10, fmax_aug_range=2000) net = get_model_passt(arch='passt_s_swa_p16_128_ap476') model = PasstBasicWrapper(mel=mel, n...
class BigBirdPegasusOnnxConfig(OnnxSeq2SeqConfigWithPast): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task in ['default', 'seq2seq-lm']): common_inputs = OrderedDict([('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}...
def test_flatten_leading_dims() -> None: x_old = tf.random.uniform([2, 3, 4, 5]) (flat_x_old, unflatten) = flatten_leading_dims(x_old) npt.assert_array_equal(tf.shape(flat_x_old), [24, 5]) x_new = unflatten(flat_x_old) npt.assert_array_equal(x_old, x_new)
class SYNTHIADataSetDepth(BaseDataset): def __init__(self, root, list_path, set='all', num_classes=16, max_iters=None, crop_size=(321, 321), mean=(128, 128, 128), use_depth=False, depth_processing='GASDA', cfg=None, joint_transform=None): super().__init__(root, list_path, set, max_iters, crop_size, None, me...
class TestFFTFreq(): _if_array_api_backend('numpy.array_api') _if_array_api_backend('cupy') _api_compatible def test_definition(self, xp): device = SCIPY_DEVICE try: x = xp.asarray([0, 1, 2, 3, 4, (- 4), (- 3), (- 2), (- 1)], dtype=xp.float64, device=device) x2 = ...
def ordered_yaml_load(yaml_path, Loader=yaml.Loader, object_pairs_hook=OrderedDict): class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor(yaml.resolver....
class ModulatedDeformConvFunction(Function): def forward(ctx, input, offset, mask, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1): ctx.stride = stride ctx.padding = padding ctx.dilation = dilation ctx.groups = groups ctx.deformable_groups =...
def main(argv): logging.basicConfig() logging.getLogger('pybindgen.typehandlers').setLevel(logging.DEBUG) (module_abs_src_path, target, extension_name, output_cc_file_name) = argv[1:] module_name = os.path.basename(module_abs_src_path) out = MyMultiSectionFactory(output_cc_file_name) sys.path.in...
_decorator(0) def get_friends(html): cont = public.get_left(html) soup = BeautifulSoup(cont, 'lxml') return int(soup.find_all('strong')[0].get_text())
class ImageCaptioningPyTorchModel(): def __init__(self, model_path, infos_path, cnn_model='resnet101', device='cuda'): with open(infos_path, 'rb') as f: infos = utils.pickle_load(f) opt = infos['opt'] opt.model = model_path opt.cnn_model = cnn_model opt.device = d...
class distill(): def __init__(self, args, model, teacher): self.args = args self.student = model self.teacher = teacher self.student_layers = self.sampled_layer(args.arch, self.student) self.teacher_layers = self.sampled_layer(args.teacher_arch, self.teacher) def kwar...
class TestNormalizeCell(): class ConcreteMetric(AbstractMetric): def evaluate_single_no_special_case(self, target, prediction): return 42.0 def abstract_metric_instance(self): return self.ConcreteMetric() def test_evaluate_single_special_case_empty_lists(self, abstract_metric_ins...
.parametrize('input_dim, output_dim, hidden_sizes', plain_settings) def test_softplus_std_network_output_values(input_dim, output_dim, hidden_sizes): init_std = 2.0 module = GaussianMLPModule(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, init_std=init_std, hidden_nonlinearity=None, std_...
_function() def body_contains_fortune(x): return (POSITIVE if ('fortune' in x.body) else ABSTAIN)
def build_pixel_sampler(cfg, **default_args): return build_from_cfg(cfg, PIXEL_SAMPLERS, default_args)
def _move_date_to_end(d: datetime.datetime) -> datetime.datetime: if (d.time() == datetime.time.min): return ((d + datetime.timedelta(days=1)) - datetime.timedelta(minutes=1)) else: return d
class PolyLrUpdaterHook(LrUpdaterHook): def __init__(self, power=1.0, min_lr=0.0, **kwargs): self.power = power self.min_lr = min_lr super(PolyLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, trainer, base_lr): if self.by_epoch: progress = trainer.epoch ...
def _train_vae(vae_trainer, replay_buffer, epoch, batches=50, oracle_data=False): batch_sampler = replay_buffer.random_vae_training_data if oracle_data: batch_sampler = None vae_trainer.train_epoch(epoch, sample_batch=batch_sampler, batches=batches, from_rl=True)
class UpBlock3D(nn.Module): def __init__(self, in_channels: int, prev_output_channel: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, out...
def PoincareHomologyThreeSphere(): return UniqueSimplicialComplex([[1, 2, 4, 9], [1, 2, 4, 15], [1, 2, 6, 14], [1, 2, 6, 15], [1, 2, 9, 14], [1, 3, 4, 12], [1, 3, 4, 15], [1, 3, 7, 10], [1, 3, 7, 12], [1, 3, 10, 15], [1, 4, 9, 12], [1, 5, 6, 13], [1, 5, 6, 14], [1, 5, 8, 11], [1, 5, 8, 13], [1, 5, 11, 14], [1, 6, 1...
class Connector(object): def AllianceStatusStream(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/grpc.Connector/AllianceStatusStream', ...
class V1LayerParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _V1LAYERPARAMETER
def prepare_attention(attention_states, kd_states, attention_option, num_units, reuse=False): with variable_scope.variable_scope('attn_keys', reuse=reuse) as scope: attention_keys = layers.linear(attention_states, num_units, biases_initializer=None, scope=scope) if (kd_states is not None): ...
def test_consensus_score(): a = [[True, True, False, False], [False, False, True, True]] b = a[::(- 1)] assert (consensus_score((a, a), (a, a)) == 1) assert (consensus_score((a, a), (b, b)) == 1) assert (consensus_score((a, b), (a, b)) == 1) assert (consensus_score((a, b), (b, a)) == 1) asse...
def warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type='smilarity', return_trans_inv=False): if (reference_pts is None): if ((crop_size[0] == 96) and (crop_size[1] == 112)): reference_pts = REFERENCE_FACIAL_POINTS else: default_square ...
_array_function class TestVerifyMatchingSignatures(object): def test_verify_matching_signatures(self): verify_matching_signatures((lambda x: 0), (lambda x: 0)) verify_matching_signatures((lambda x=None: 0), (lambda x=None: 0)) verify_matching_signatures((lambda x=1: 0), (lambda x=None: 0)) ...
def clean_by_unp(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame: if (output_format not in {'compact', 'standard'}): raise ValueError(f'output_format {output_format} is invalid. It needs to b...
class EncoderInterface(nn.Module): def __init__(self): super(EncoderInterface, self).__init__() def count_parameters(self) -> int: return sum([p.numel for p in self.parameters()]) def update_dropout(self, dropout_p: float) -> None: for (name, child) in self.named_children(): ...
def video2img(video_path): start = time.time() video_id = os.path.splitext(os.path.basename(video_path))[0] target_dir = os.path.join('data/videos', video_id, 'images') if (not os.path.exists(target_dir)): os.makedirs(target_dir) cap = cv2.VideoCapture(video_path) if (not cap.isOpened())...
class ECAPA_TDNN(nn.Module): def __init__(self, input_size: int=80, output_size: int=1536, C: int=1024, **kwargs): super().__init__() self._indim = input_size self._outdim = output_size self.conv1 = nn.Conv1d(input_size, C, kernel_size=5, stride=1, padding=2) self.relu = nn.R...
def main(n, dim, lamb, norm): two_norm = (norm / math.sqrt(dim)) delta = (1.0 / n) alphas = np.linspace(0.001, 0.5, 1000) sgd = (lambda a: sgd_get_epsilon_expected(a, n, dim, delta, (2.0 * two_norm), 1.0)) cov = (lambda a: covar_get_epsilon(a, n, dim, two_norm)) out = (lambda a: output_pert_linr...
.parametrize('shapes', [((4, 84, 84), 3136)]) .parametrize('filters', [[(32, 8, 4), (64, 4, 2), (64, 3, 1)]]) .parametrize('feature_size', [512]) .parametrize('batch_size', [32]) .parametrize('use_batch_norm', [False, True]) .parametrize('dropout_rate', [None, 0.2]) .parametrize('activation', [torch.nn.ReLU()]) def tes...
def register_Ns3ObjectFactoryValue_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, i...
def set_value(dic, keys_chain, value): node = dic for key in keys_chain[:(- 1)]: if (key in node): node = node[key] else: node[key] = {} node = node[key] node[keys_chain[(- 1)]] = value
def split_testing_frames(): testing_frames_root = os.path.join(DATA_ROOT, 'testing', 'frames') testing_frame_mask_root = os.path.join(DATA_ROOT, 'testing', 'test_frame_mask') testing_pixel_mask_root = os.path.join(DATA_ROOT, 'testing', 'test_pixel_mask') img_root = os.path.join(BIN_ROOT, 'test', 'image'...
def su3dabc(v: Tensor) -> Tensor: vT = tf.transpose(v) a00 = (d007 * vT[7]) a03 = (d035 * vT[5]) a04 = (d046 * vT[6]) a05 = (d035 * vT[3]) a06 = (d046 * vT[4]) a07 = (d007 * vT[0]) a11 = (d117 * vT[7]) a13 = (d136 * vT[6]) a14 = (d145 * vT[5]) a15 = (d145 * vT[4]) a16 = (...
def __getattr__(name): return _sub_module_deprecation(sub_package='sparse.linalg', module='isolve', private_modules=['_isolve'], all=__all__, attribute=name)
class _LifeSpan(): def __init__(self): self.begin_func_idx = (- 1) self.end_func_idx = (- 1) def needed_at(self, func_idx): needed = (self.begin_func_idx <= func_idx) needed &= (self.end_func_idx >= func_idx) return needed
class Partition5(nn.Module): LAYER_SCOPES = ['VisionTransformer/ModuleList[blocks]/Block[15]/LayerNorm[norm1]', 'VisionTransformer/ModuleList[blocks]/Block[15]/Attention[attn]/Linear[qkv]', 'VisionTransformer/ModuleList[blocks]/Block[15]/Attention[attn]/Dropout[attn_drop]', 'VisionTransformer/ModuleList[blocks]/Blo...
def main(): if (CONFIG['exp']['model'] not in ('binarygan', 'gan')): raise ValueError('Unrecognizable model name') print('Start experiment: {}'.format(CONFIG['exp']['exp_name'])) x_train = load_data() with tf.Session(config=CONFIG['tensorflow']) as sess: if (CONFIG['exp']['model'] == 'ga...
.parametrize('precision_level', ['32b', '64b']) def test_set_precision_by_string_wins(precision_level): conflicting_precision = ('32b' if (precision_level == '64b') else '64b') pyhf.set_backend(pyhf.tensor.numpy_backend(precision=conflicting_precision), precision=precision_level) assert (pyhf.tensorlib.prec...
def inception_v3_parameters(weight_decay=4e-05, stddev=0.1, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): with scopes.arg_scope([ops.conv2d, ops.fc], weight_decay=weight_decay): with scopes.arg_scope([ops.conv2d], stddev=stddev, activation=tf.nn.relu, batch_norm_params={'decay': batch_norm_decay, 'eps...