code
stringlengths
101
5.91M
class ResNet12(nn.Module): def __init__(self, drop_ratio=0.1, with_drop=False): super(ResNet12, self).__init__() self.drop_layers = with_drop self.inplanes = 3 self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout(drop_ratio, inplace=inp) self.layer1 =...
def main(): assert_and_infer_cfg(args) prep_experiment(args, parser) writer = None (_, val_loaders, _, _, extra_val_loaders) = datasets.setup_loaders(args) (criterion, criterion_val) = loss.get_loss(args) criterion_aux = loss.get_loss_aux(args) net = network.get_net(args, criterion, criterio...
def remove_zero_length_instances_from_file(filepath): new_filepath = (filepath[:filepath.rfind('.tsv')] + '_nozerolens.tsv') new_f = open(new_filepath, 'w') first_line = True counter = 0 with open(filepath, 'r') as f: for line in f: if first_line: new_f.write(line...
def batch_run(m, dl, device, flatten=False, method='predict', input_type='first', no_grad=True, **kwargs): method = getattr(m, method) l_result = [] for batch in dl: if (input_type == 'first'): x = batch[0] if no_grad: with torch.no_grad(): if flatten:...
class BNInception_gsm(nn.Module): def __init__(self, model_path='model_zoo/bninception/bn_inception_gsm.yaml', num_classes=101, weight_url=' num_segments=16): super(BNInception_gsm, self).__init__() manifest = yaml.load(open(model_path)) layers = manifest['layers'] self._channel_dict...
def test_ast_resolver_chain(): import taichi as ti ti.init() node = ast.parse('ti.lang.ops.atomic_add', mode='eval').body assert ASTResolver.resolve_to(node, ti.atomic_add, locals())
def get_rank(): if is_xla(): return xm.get_ordinal() if (not dist.is_available()): return 0 if (not dist.is_nccl_available()): return 0 if (not dist.is_initialized()): return 0 return dist.get_rank()
_module() class PyGPointNextEncoder(nn.Module): def __init__(self, block, blocks, in_channels=6, width=32, strides=[4, 4, 4, 4], nsample=[16, 16, 16, 16], radius=0.1, radius_scaling=2, nsample_scaling=1, aggr_args={'feature_type': 'dp_fj', 'reduction': 'max'}, group_args={'NAME': 'ballquery'}, norm_args={'norm': 'b...
def strip_span(span, tokens): start = 0 while (start < len(span)): token = tokens[span[start]] if (not re.search('^(in|of|at|-|,)$', token)): break start += 1 end = (len(span) - 1) while (end > start): token = tokens[span[end]] if (not re.search('^(in|...
def get_train_data(labels, tr_num, val_num, seed): np.random.seed(seed) labels_vec = labels.argmax(1) labels_num = (labels_vec.max() + 1) idx_train = [] idx_val = [] for label_idx in range(labels_num): pos0 = np.argwhere((labels_vec == label_idx)).flatten() pos0 = np.random.permu...
class CHomP(): def __repr__(self): return 'CHomP interface' def __call__(self, program, complex, subcomplex=None, **kwds): from sage.misc.temporary_file import tmp_filename from sage.topology.cubical_complex import CubicalComplex, cubical_complexes from sage.topology.simplicial_c...
def p_adic_LLL_bound_one_prime(prime, B0, M, M_logp, m0, c3, prec=106): if any(((g.valuation(prime) != 0) for g in (M + [m0]))): raise ValueError('There is an element with non zero valuation') K = prime.ring() w = K.number_of_roots_of_unity() p = prime.smallest_integer() f = prime.residue_cl...
def from_json_tester(algo: LearnableBase[(ImplBase, LearnableConfig)], observation_shape: Shape, action_size: int) -> None: algo.create_impl(observation_shape, action_size) adapter_factory = FileAdapterFactory('test_data') logger = D3RLPyLogger(adapter_factory, experiment_name='test') save_config(algo, ...
class AutoModelForSequenceClassification(): def __init__(self): raise EnvironmentError('AutoModelForSequenceClassification is designed to be instantiated using the `AutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForSequenceClassification.from_config(config)` ...
def drop_mask(shape, keep_prob): if isinstance(shape, (tuple, list)): shape = tf.stack(shape) ones = tf.ones(shape) return dropout(ones, keep_prob)
def test_case122(): url = (brokerIp + '/ngsi-ld/v1/subscriptions/') headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'} r = requests.post(url, data=json.dumps(ld_data.subdata121), headers=headers) print(r.content) pr...
def test_count_ops(): (x, y) = symbols('x, y') assert (count_ops((x + y)) == 1) assert (count_ops(((x + y), (x * y))) == 2) assert (count_ops([[(x ** y)], [((x + y) - 1)]]) == 3) assert (count_ops((x + y), (x * y)) == 2)
def get_robust_regression(device: torch.device) -> GetterReturnType: N = 10 K = 10 X = torch.rand(N, (K + 1), device=device) Y = torch.rand(N, 1, device=device) nu_alpha = torch.randn(1, 1, device=device) nu_beta = torch.rand(1, 1, device=device) nu = dist.Gamma(nu_alpha, nu_beta) sigma_...
class RiemannianStructure(Singleton): chart = RealDiffChart name = 'Riemannian' scalar_field_algebra = DiffScalarFieldAlgebra homset = DifferentiableManifoldHomset def subcategory(self, cat): return cat
class InactiveLeaf(): def new_nominal_attribute_observer(): return None def new_numeric_attribute_observer(): return None def update_attribute_observers(self, X, y, weight, tree): pass
def __getattr__(name): if (name in {'HalvingGridSearchCV', 'HalvingRandomSearchCV'}): raise ImportError(f'''{name} is experimental and the API might change without any deprecation cycle. To use it, you need to explicitly import enable_halving_search_cv: from sklearn.experimental import enable_halving_search...
def get_memory_usage(assignments): ret = 0 for cur in assignments: ret += _get_max_size(cur) return ret
class TestFactor(unittest.TestCase): def setUp(self): if skip: raise unittest.SkipTest('PyTorch not installed') attrs = ['a', 'b', 'c'] shape = [2, 3, 4] domain = Domain(attrs, shape) values = torch.rand(*shape) self.factor = Factor(domain, values) def...
def arc_length(arc): angle_a = cartesian_angle(arc.circle.center, arc.a) angle_b = cartesian_angle(arc.circle.center, arc.b) angle = signed_distance_between_cartesian_angles(angle_a, angle_b) return (angle * arc.circle.radius)
(wait_incrementing_start=(5 * 1000), wait_incrementing_increment=(5 * 1000), stop_max_attempt_number=5) def get_slurm_job_state(job_id: int) -> str: try: scontrol_output = subprocess.check_output(f'scontrol show job {job_id}', stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as...
def register_Ns3QuicClient_methods(root_module, cls): cls.add_constructor([param('ns3::QuicClient const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_method('SetRemote', 'void', [param('ns3::Address', 'ip'), param('uint16_t', 'port')]) c...
def color_crossings(n, c): if (n in seen): return seen.add(n) if (n in color_dict): color_dict[n] = c return for a in getattr(n, 'args', []): color_crossings(a, c) for a in getattr(n, 'fields', []): color_crossings(a, c) for nam in ('body', 'tuple_value'):...
.parametrize('dtype, storage_format', [(ti.f32, 'col_major'), (ti.f32, 'row_major'), (ti.f64, 'col_major'), (ti.f64, 'row_major')]) _utils.test(arch=ti.cpu) def test_build_sparse_matrix_frome_ndarray(dtype, storage_format): n = 8 triplets = ti.Vector.ndarray(n=3, dtype=ti.f32, shape=n) A = ti.linalg.SparseM...
def create_latex_accuracy_singletable(df, outname, title): df = df.copy() df['redshift'] = df['model_name_noseed'].apply((lambda x: re.search('(?<=R\\_)[A-Za-z]+', x).group())) metric = 'accuracy' list_keys = ['-2', '0', '+2', 'all'] for k in list_keys: df[k] = (((('$' + df[f'{k}_{metric}_me...
def top_k(source: Tensor, *, axis: Union[(Dim, Sequence[Dim])], k: Optional[Union[(int, Tensor)]]=None, k_dim: Optional[Dim]=None, sorted: bool=True) -> Tuple[(Tensor, Union[(Tensor, Sequence[Tensor])], Dim)]: if (k is None): assert k_dim, 'top_k: either provide `k` or `k_dim`' k = (k_dim.dimension ...
def adjust_gamma(image, gamma=1.0): invGamma = (1.0 / gamma) table = np.array([(((i / 255.0) ** invGamma) * 255) for i in np.arange(0, 256)]).astype('uint8') return cv2.LUT(image, table)
def test_optimal_control_with_custom_preconditioner(geometry, config_ocp): mesh = geometry.mesh dx = geometry.dx v_elem = VectorElement('CG', mesh.ufl_cell(), 2) p_elem = FiniteElement('CG', mesh.ufl_cell(), 1) V = FunctionSpace(mesh, (v_elem * p_elem)) W = VectorFunctionSpace(mesh, 'CG', 1) ...
class E2E_TrainingRestorer(object): def __init__(self, opts, model, optimizer): if exists(f'{opts.output_dir}/log/args.json'): restore_opts = json.load(open(f'{opts.output_dir}/log/args.json', 'r')) with open(join(opts.output_dir, 'log', 'restore_args.json'), 'w') as writer: ...
_kwargs(**{'device': 'hpu'}) _fl_task(model='unet_model', data_loader='val_loader', device='device') def validate(unet_model, val_loader, device): print(f''' TASK VALIDATE GOT DEVICE {device} ''') unet_model.eval() unet_model.to(device) val_loader = tqdm.tqdm(val_loader, desc='validate') val_score ...
class CompositionalAttention(CompositionalAttentionBase): def __init__(self, state_size: int, n_heads: int, n_rules: int, qk_dim: int, dot: bool=False, dropout: float=0.1, input_size: Optional[torch.Tensor]=None): super().__init__(state_size, n_heads, n_rules, qk_dim, dot, dropout) self.query_net = ...
class CamRender(Render): def __init__(self, width=1600, height=1200, name='Cam Renderer', program_files=['simple.fs', 'simple.vs'], color_size=1, ms_rate=1): Render.__init__(self, width, height, name, program_files, color_size, ms_rate=ms_rate) self.camera = None glutDisplayFunc(self.display...
def _repo_path(repo, version): if (not version): return _dev_repo_path(repo) return ('%%s' % (_main_repo_path(repo), version))
def getLabelIdxMapping(path): import csv raw = dict() toNYU40 = dict() toEigen = dict() toRIO27 = dict() toRIO7 = dict() with open(path, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in spamreader: if (not row[0].is...
def test_Data_copy_compatible_to_dims_match_priority(): feat_dim = Dim(2, name='feature') in_dim = feat_dim.copy(match_priority=1) assert ((in_dim == feat_dim) and (in_dim.match_priority > feat_dim.match_priority) and (in_dim is not feat_dim)) raw_np = numpy.arange(0, (2 * 2), dtype=numpy.float32).resha...
def _color_wrap(*colors): def wrapped(inp): return ''.join((list(colors) + [inp, colorama.Style.RESET_ALL])) return wrapped
class PolicyWithPacking(Policy): def __init__(self, solver='ECOS'): Policy.__init__(self, solver) def scale_factors_array(self, scale_factors, job_ids, m, n): scale_factors_array = np.zeros((m, n)) for i in range(m): scale_factor = None for single_job_id in job_id...
def create_plot_window(vis, xlabel, ylabel, title, win, env, trace_name): if (not isinstance(trace_name, list)): trace_name = [trace_name] vis.line(X=np.array([1]), Y=np.array([np.nan]), win=win, env=env, name=trace_name[0], opts=dict(xlabel=xlabel, ylabel=ylabel, title=title)) for name in trace_nam...
def conv_relu_layer(input_layer, filter_shape, stride): filter = create_variables(name='conv_relu', shape=filter_shape) conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME') output = tf.nn.relu(conv_layer) return output
def _df(model, data, labels, attack_args): max_iter = attack_args.get('max_iter', 100) eps = attack_args.get('eps', 0.01) nb_grads = attack_args.get('nb_grads', 10) attacker = DeepFool(classifier=model, max_iter=max_iter, epsilon=eps, nb_grads=nb_grads) return attacker.generate(data, labels)
class Agent(object): def __init__(self, action_shape): self.action_shape = action_shape def act(self, obs): arm = np.random.normal(0.0, 0.1, size=((self.action_shape[0] - 1),)) gripper = [1.0] return np.concatenate([arm, gripper], axis=(- 1))
def read_msg() -> Optional[Dict]: msg = json.loads(sys.stdin.readline().strip()) if ('terminate' in (msg.get('type'), msg.get('event'))): return None if (msg.get('event') not in ('download', 'upload')): logger.critical('Received unexpected message') sys.exit(1) return msg
class TestMultipleInputsMultipleOutputsKerasMCTQExporter(TestKerasMCTQExport): def get_input_shape(self): return [(30, 30, 3), (28, 28, 3)] def get_tpc(self): tp = generate_test_tp_model({'weights_n_bits': 2}) return generate_keras_tpc(name='test_conv2d_2bit_fq_weight', tp_model=tp) ...
class RewardFunction(object): def __init__(self, rew_map=None, default=0): if (rew_map is None): rew_map = {REWARD: 1.0, REWARD2: 2.0, REWARD3: 4.0, REWARD4: 8.0, LAVA: (- 100.0)} self.default = default self.rew_map = rew_map def __call__(self, gridspec, s, a, ns): va...
def test_reallocations(capture, msg): pytest.gc_collect() with capture: create_and_destroy(1) assert (msg(capture) == '\n noisy new\n noisy placement new\n NoisyAlloc(int 1)\n ---\n ~NoisyAlloc()\n noisy delete\n ') with capture: create_and_de...
class Chunker(): def __init__(self, path: str, start_offset: int, end_offset: int): self.path = path self.start_offset = start_offset self.end_offset = end_offset def __enter__(self) -> ChunkLineIterator: self.fd = open(self.path, 'r', encoding='utf-8') return ChunkLineIt...
def get_df(L_to_minmax, L_to_num_stages, L_to_best_objective): def list_keys(x): return list(x.keys()) assert (list_keys(L_to_num_stages) == list_keys(L_to_best_objective) == list_keys(L_to_minmax)) records = [dict(L=L, stages=stages, objective=objective) for (L, stages, objective) in zip(L_to_num_s...
class Adagrad(Optimizer): def __init__(self, params, lr=0.01, lr_decay=0, weight_decay=0, initial_accumulator_value=0, eps=1e-10): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= lr_decay)): raise ValueError('Invalid lr_decay val...
class Config(object, metaclass=ModelConfigMeta): filename = 'config.json' _default_transform = Identity() transform: TransformBase = None dim: Optional[int] = None def __init__(self, transform: TransformBase=None, **kwargs): super().__init__() if (transform is None): self...
def test(): array = ak.Array([[3.14]]) first_slice = ak.Array([True, None])[:1] second_slice = 0 with pytest.raises(ValueError): array[(first_slice, second_slice)]
def _ssim(X, Y, data_range, win, size_average=True, K=(0.01, 0.03)): (K1, K2) = K compensation = 1.0 C1 = ((K1 * data_range) ** 2) C2 = ((K2 * data_range) ** 2) win = win.to(X.device, dtype=X.dtype) mu1 = gaussian_filter(X, win) mu2 = gaussian_filter(Y, win) mu1_sq = mu1.pow(2) mu2_s...
def test_Or(): assert (Or() == false) assert (Or(True) == true) assert (Or(False) == false) assert (Or(True, True) == true) assert (Or(True, False) == true) assert (Or(False, False) == false) assert (Or(True, False, False) == true)
def _replace_none(dictionary: Dict[(str, Any)]) -> Dict[(str, Any)]: for key in dictionary.keys(): if (dictionary[key] == 'None'): dictionary[key] = None elif isinstance(dictionary[key], pyhocon.config_tree.ConfigTree): dictionary[key] = _replace_none(dictionary[key]) ret...
def _savePngJson(hInPklResultsFile, hOutJsonPackedFile): from PIL import Image import StringIO dataFPickle = pickle.load(hInPklResultsFile) statusStr = '' dataLen = len(dataFPickle) for (i, x) in enumerate(dataFPickle): x['uv_shape'] = x['uv'].shape x['uv_data'] = _encodePngData(...
class MultilingualDatasetManager(object): def __init__(self, args, lang_pairs, langs, dicts, sampling_method): super().__init__() self.args = args self.seed = args.seed self.lang_pairs = lang_pairs self.langs = langs self.dicts = dicts self.lang_dict = self.cr...
def box_sphere_intersections(z, d, lb, ub, trust_radius, entire_line=False, extra_info=False): (ta_b, tb_b, intersect_b) = box_intersections(z, d, lb, ub, entire_line) (ta_s, tb_s, intersect_s) = sphere_intersections(z, d, trust_radius, entire_line) ta = np.maximum(ta_b, ta_s) tb = np.minimum(tb_b, tb_s...
def train_epoch(model, dataloader, criterion, optimizer, epoch_i): model.train() criterion.train() time_meters = defaultdict(AverageMeter) loss_meters = defaultdict(AverageMeter) tictoc = time.time() for (idx, batch) in tqdm(enumerate(dataloader), desc='Training Iteration', total=len(dataloader)...
def wheel_version(wheel_data): version_text = wheel_data['Wheel-Version'] if (version_text is None): raise UnsupportedWheel('WHEEL is missing Wheel-Version') version = version_text.strip() try: return tuple(map(int, version.split('.'))) except ValueError: raise UnsupportedWhe...
class DenseFlatIndexer(DenseIndexer): def __init__(self, buffer_size: int=50000): super(DenseFlatIndexer, self).__init__(buffer_size=buffer_size) def init_index(self, vector_sz: int): self.index = faiss.IndexFlatIP(vector_sz) def index_data(self, data: List[Tuple[(object, np.array)]]): ...
def main(): (examples, label_list) = get_data(task=args.task, train_num_per_class=args.train_num_per_class, dev_num_per_class=args.dev_num_per_class, imbalance_rate=args.imbalance_rate, data_seed=args.data_seed) if (args.task in ['sst-2', 'sst-5']): classifier = Classifier(label_list=label_list, ren=Tru...
def is_available() -> bool: if (not hasattr(torch._C, '_cuda_getDeviceCount')): return False return (torch._C._cuda_getDeviceCount() > 0)
_fwd(cast_inputs=torch.float32) def ml_soft_nms(dets, scores, labels, sigma=0.5, overlap_thresh=0.3, score_thresh=0.001, method='linear', topk=0): assert (method in SOFT_NMS_METHODS), 'Unknown soft_nms method: {}'.format(method) return _C.ml_soft_nms(dets, scores, labels, sigma, overlap_thresh, score_thresh, SO...
class TimeBinBSM(BSM): def __init__(self, name, timeline, phase_error=0, detectors=None): super().__init__(name, timeline, phase_error, detectors) self.encoding = 'time_bin' self.encoding_type = time_bin self.last_res = [(- 1), (- 1)] assert (len(self.detectors) == 2) def...
def _wrapper_count_operators(model: nn.Module, inputs: list, mode: str, **kwargs) -> typing.DefaultDict[(str, float)]: supported_ops = {k: (lambda *args, **kwargs: {}) for k in _IGNORED_OPS} supported_ops.update(kwargs.pop('supported_ops', {})) kwargs['supported_ops'] = supported_ops assert (len(inputs)...
def tokenize(corpus, remove_list=remove_items): for text in corpus: doc = nlp.tokenizer(text) tokens = [str(token.lemma_).lower() for token in doc if (token.is_alpha and (token.text.lower() not in remove_list) and (len(token.text) > 1))] (yield tokens)
class Mask(Transform): def __init__(self, mask_key: str, mask_value: int=0, masking_value: float=0.0, loop_axis=None, entries=(defs.KEY_IMAGES, defs.KEY_LABELS)) -> None: super().__init__() self.mask_key = mask_key self.mask_value = mask_value self.masking_value = masking_value ...
.parametrize('cls_name', ['Pickleable', 'PickleableNew']) def test_roundtrip(cls_name): cls = getattr(m, cls_name) p = cls('test_value') p.setExtra1(15) p.setExtra2(48) data = pickle.dumps(p, 2) p2 = pickle.loads(data) assert (p2.value() == p.value()) assert (p2.extra1() == p.extra1()) ...
def transform_pt_cluewsc(example, label_normalize_dict=None, is_test=False): if is_test: example['label_length'] = 2 text = example['text'] span1_text = example['target']['span1_text'] span2_text = example['target']['span2_text'] example['sentence1'] = (((text + span2_text) +...
def register_Ns3ServiceFlow_methods(root_module, cls): cls.add_constructor([param('ns3::Tlv', 'tlv')]) cls.add_constructor([]) cls.add_constructor([param('ns3::ServiceFlow::Direction', 'direction')]) cls.add_constructor([param('ns3::ServiceFlow const &', 'sf')]) cls.add_constructor([param('uint32_t'...
.pure def test_cast_float_to_int(sdfg_name): sdfg = dace.SDFG(sdfg_name) sdfg.add_array('X', [2, 4], dace.float32) sdfg.add_array('__return', [2, 4], dace.int32) state = sdfg.add_state() access_X = state.add_access('X') access_result = state.add_access('__return') op_node = donnx.ONNXCast('C...
def sort_params(model, hook): hooks = [] if ('GP' in model.lat_dist.name): h1 = model.lat_dist.nu.register_hook(hook) h2 = model.lat_dist._scale.register_hook(hook) hooks.append(h1) hooks.append(h2) else: for prm in model.lat_dist.parameters(): h = prm.reg...
class Visualization(object): def __init__(self, seq_info, update_ms): self.view_ls = list(seq_info.keys()) key0 = self.view_ls[0] image_shape = seq_info[key0]['image_size'][::(- 1)] aspect_ratio = (float(image_shape[1]) / image_shape[0]) image_shape = (1024, int((aspect_ratio...
() class DiscreteBCQConfig(LearnableConfig): learning_rate: float = 6.25e-05 optim_factory: OptimizerFactory = make_optimizer_field() encoder_factory: EncoderFactory = make_encoder_field() q_func_factory: QFunctionFactory = make_q_func_field() batch_size: int = 32 gamma: float = 0.99 n_criti...
def mapfission_sdfg(): sdfg = dace.SDFG('mapfission') sdfg.add_array('A', [4], dace.float64) sdfg.add_array('B', [2], dace.float64) sdfg.add_scalar('scal', dace.float64, transient=True) sdfg.add_scalar('s1', dace.float64, transient=True) sdfg.add_transient('s2', [2], dace.float64) sdfg.add_t...
class TestPyTorchHelper(unittest.TestCase): def setUp(self): self.helper = PyTorchHelper() def test_increment_average(self): model = {'layer1': np.array([1, 2, 3])} model_next = {'layer1': np.array([4, 5, 6])} a = 10 W = 20 result = self.helper.increment_average(m...
('random_crop') def random_crop(cfg, **kwargs): size = (kwargs['input_size'] if (kwargs['input_size'] != None) else cfg.INPUT_SIZE) return transforms.RandomCrop(size, padding=cfg.TRANSFORMS.PROCESS_DETAIL.RANDOM_CROP.PADDING)
def filter_invalid_unicode_from_table(table): if (not hasattr(table, 'table_id')): table.table_id = 0 for (row_index, row) in table.iterrows(): for (col_index, cell) in enumerate(row): (cell, is_invalid) = filter_invalid_unicode(cell) if is_invalid: loggin...
class SlateCascadeDoublyRobust(BaseSlateOffPolicyEstimator): len_list: int n_unique_action: int estimator_name: str = 'cascade-dr' def __post_init__(self): check_scalar(self.n_unique_action, 'n_unique_action', int, min_val=1) def _estimate_round_rewards(self, action: np.ndarray, reward: np.n...
class HubModel(): def __init__(self, local_dir: str, metadata: Optional[Union[(HubMetadata, str)]]=None, model_card: Optional[Union[(HubModelCardHelper, ModelCard, str)]]=None): self._local_dir = local_dir self._model_path = f'{self._local_dir}/model.pt' self._adata_path = f'{self._local_dir...
class GraphBuilderTest(test_util.TensorFlowTestCase): def setUp(self): initial_task_context = os.path.join(FLAGS.test_srcdir, 'syntaxnet/testdata/context.pbtxt') self._task_context = os.path.join(FLAGS.test_tmpdir, 'context.pbtxt') with open(initial_task_context, 'r') as fin: wit...
def _pick_key_for_choices(letters_to_try: T.List[str], sub: T.Optional[int], is_unused: T.Callable[([str, T.Optional[int]], bool)], next_unused_sub: T.Callable[([str], int)]) -> GeneratedKey: assert letters_to_try, 'letters_to_try should not be empty' for letter in letters_to_try: if is_unused(letter, s...
def data_loading(dataset): current_path = op.dirname(op.abspath(__file__)) if (dataset == 'telco'): data_house_prices_path = op.join(current_path, 'telco_churn.csv') data = pd.read_csv(data_telco) else: raise ValueError('Dataset not found. Check the docstring for available values') ...
.parametrize('length,max_seq_length,eos_token_id', [(5, None, None), (2, 6, (- 1)), (0, 6, (- 1))]) def test_len(tokenized_line: TokenizedLine, length: int): assert (len(tokenized_line) == length) assert (len(tokenized_line.tokens) == length)
class Swish(nn.Module): def __init__(self): super(Swish, self).__init__() def forward(self, inputs: Tensor) -> Tensor: return (inputs * inputs.sigmoid())
def get_raw2scannetv2_label_map(): lines = [line.rstrip() for line in open('scannetv2-labels.combined.tsv')] lines_0 = lines[0].split('\t') print(lines_0) print(len(lines)) lines = lines[1:] raw2scannet = {} for i in range(len(lines)): label_classes_set = set(g_label_names) e...
class Classifier(): def __init__(self): arch = 'resnet50' model_file = ('%s_places365.pth.tar' % arch) if (not os.access(model_file, os.W_OK)): weight_url = (' + model_file) os.system(('wget ' + weight_url)) model = models.__dict__[arch](num_classes=365) ...
def simple_condition2(fib: dace.int32, F: dace.int32, i: dace.int32, N: dace.int32): return ((fib < F) and (i < N))
class ToPILImage(object): def __init__(self, mode=None): self.mode = mode def __call__(self, pic): return F.to_pil_image(pic, self.mode) def __repr__(self): format_string = (self.__class__.__name__ + '(') if (self.mode is not None): format_string += 'mode={0}'.for...
(frozen=True) class RunGroup(Field): metric_groups: List[str] = field(default_factory=list) subgroups: List[str] = field(default_factory=list) sub_splits: Optional[List[str]] = None subgroup_display_mode: str = BY_METRIC subgroup_metric_groups_hidden: List[str] = field(default_factory=list) envi...
class ModelParallelTransformerEncoderLayer(TransformerEncoderLayer): def build_fc1(self, input_dim, output_dim): return ColumnParallelLinear(input_dim, output_dim, gather_output=False) def build_fc2(self, input_dim, output_dim): return RowParallelLinear(input_dim, output_dim, input_is_parallel=T...
class DistributedCutoutTuner(): def __init__(self, tuner: ct.CutoutTuner) -> None: self._tuner = tuner def optimize(self, measurements: int=30, **kwargs) -> Dict: cutouts = OrderedDict() existing_files = set() for (cutout, cutout_hash) in self._tuner.cutouts(): cutout...
def register_Ns3ThreeGppHttpServerTxBuffer_methods(root_module, cls): cls.add_constructor([param('ns3::ThreeGppHttpServerTxBuffer const &', 'arg0')]) cls.add_constructor([]) cls.add_method('AddSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')]) cls.add_method('CloseAllSockets', 'void', []) ...
def filter(input_file, output_file, minK): filtered = 0 total = 0 for line in input_file: total += 1 fields = line.rstrip().split('\t') assert (len(fields) == 3) if (int(fields[2]) >= minK): output_file.write('\t'.join(fields)) output_file.write('\n') ...
def test_panloss(): panloss = losses.PANLoss() mask = [[1, 0, 1], [1, 1, 1], [0, 0, 1]] target = [[1, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] masks = [np.array(mask)] bitmasks = BitmapMasks(masks, 3, 3) target_sz = (6, 5) results = pa...
def test_deskl(): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() deskl = DESKL(pool_classifiers, DFP=True) deskl.fit(X_dsel, y_dsel) assert np.isclose(deskl.score(X_test, y_test), 0.)
() .usefixtures('spark') def log(spark): return spark.createDataFrame(log_data, schema=['user_id', 'item_id', 'timestamp', 'relevance'])