code
stringlengths
101
5.91M
.parametrize('voiced_region', ['pulse', 'sinusoidal', 'sawtooth']) def test_waveform(voiced_region, P=80, verbose=False): excite = diffsptk.ExcitationGeneration(P, voiced_region=voiced_region, unvoiced_region='zeros') pitch = torch.from_numpy(U.call(f'x2x +sd tools/SPTK/asset/data.short | pitch -s 16 -p {P} -o ...
.parametrize('module_creator', [ModuleCreator(TSTNetNormal(), [(4, 3, 32, 32), (4, 3, 32, 32)]), ModuleCreator(ResUnit(16), [(4, 3, 32, 32)]), ModuleCreator(NestedTestNet(), [(4, 3, 32, 32), (4, 3, 32, 32)])]) def test_with_statement_graph_def_test_name(module_creator): module = module_creator.module proto_vari...
class DocTestReporter(SageObject): def __init__(self, controller): self.controller = controller self.postscript = {'lines': [], 'cputime': 0, 'walltime': 0} self.sources_completed = 0 self.stats = {} self.error_status = 0 def were_doctests_with_optional_tag_run(self, tag)...
def make_just_x(ds): d = defaultdict(list) for feature in ds: for (key, val) in vars(feature).items(): if (key == 'label'): continue if (val is None): continue d[key].append(val) print(d.keys()) return TensorDataset(*[torch.tens...
def tounroll(A: dace.float64[20], B: dace.float64[20]): for i in range(5): for j in dace.map[0:20]: with dace.tasklet: (a << A[j]) (b_in << B[j]) (b_out >> B[j]) b_out = (b_in + (a * i))
def yaml_load(filename): with open(filename, 'r') as f: data = yaml.load(f, Loader=yaml.BaseLoader) return data
def psi(N): if (not N.is_integral()): raise ValueError('psi only defined for integral ideals') from sage.misc.misc_c import prod return prod([((np + 1) * (np ** (e - 1))) for (np, e) in [(p.absolute_norm(), e) for (p, e) in N.factor()]])
def test_inv_residual(): with pytest.raises(AssertionError): InvertedResidual(32, 32, 3, 4) inv_module = InvertedResidual(32, 32, 1, 4) assert inv_module.use_res_connect assert (inv_module.conv[0].kernel_size == (1, 1)) assert (inv_module.conv[0].padding == 0) assert (inv_module.conv[1]....
_kl(Pareto, Normal) def _kl_pareto_normal(p, q): var_normal = (2 * q.scale.pow(2)) common_term = (p.scale / (p.alpha - 1)) t1 = (((math.sqrt((2 * math.pi)) * q.scale) * p.alpha) / p.scale).log() t2 = p.alpha.reciprocal() t3 = ((p.alpha * common_term.pow(2)) / (p.alpha - 2)) t4 = ((p.alpha * comm...
def _collect_best_span_string(best_span: torch.Tensor, cspan: torch.IntTensor, context_tokens: List[Token], context_string: str, cls_ind: Optional[Union[(torch.LongTensor, int)]]=0) -> str: best_span = best_span.detach().cpu().numpy() if (best_span[0] == cls_ind): best_span_string = '' else: ...
_interact(title=(lambda : text_control('<h2>Simpson integration</h2>')), f=(lambda : input_box(default='x*sin(x)+x+1', label='$f(x)=$')), n=(lambda : slider(2, 100, 2, 6, label='# divisions')), interval_input=(lambda : selector(['from slider', 'from keyboard'], label='Integration interval', buttons=True)), interval_s=(...
def are_almost_same(name_a: str, name_b: str, max_dist: int=1) -> bool: if ((not name_a) or (not name_b)): return False return (lev.distance(name_a, name_b) <= max_dist)
def path_to_display(path): if (path is None): return None if isinstance(path, text_type): return path try: display_path = path.decode(sys.getfilesystemencoding(), 'strict') except UnicodeDecodeError: if PY2: display_path = str_to_display('b{!r}'.format(path)) ...
def main(): dataset = CNNDataset() output_dir = 'data/cnn' os.makedirs(output_dir) tokenizer = GPT2Tokenizer.from_pretrained('gpt2-large') split_size = {'train': 10000, 'dev': 5000, 'test': 1000} train_texts = [] for i in trange(20000, desc='Getting Train Text'): (_, story_lines, _) ...
def encode_datas(table, queries, column2vec, op2vec): return [encode_data(table, q, column2vec, op2vec) for q in queries]
.parametrize('param', PARAMS, ids=IDS) def test_cython_api(param): (pyfunc, cyfunc, specializations, knownfailure) = param if knownfailure: pytest.xfail(reason=knownfailure) values = [set() for code in specializations[0]] for typecodes in specializations: for (j, v) in enumerate(typecode...
class Node(with_metaclass(NodeType, object)): fields = () attributes = ('lineno', 'environment') abstract = True def __init__(self, *fields, **attributes): if self.abstract: raise TypeError('abstract nodes are not instantiable') if fields: if (len(fields) != len(s...
def same_width(epsilon=0.1): return (lambda bbox1, bbox2: (abs((_width(bbox1) - _width(bbox2))) < epsilon))
class Simulator(): def __init__(self, simulator): self.simulator = simulator def __call__(self, *args, batch_size=1, random_state=None): return self.simulator(torch.from_numpy(np.stack(args).astype(np.float32).T)).numpy().reshape(batch_size, (- 1))
def IBA_calc(TPR, TNR, alpha=1): try: IBA = (((1 + (alpha * (TPR - TNR))) * TPR) * TNR) return IBA except TypeError: return 'None'
class Calculator(): amount_calculation = 0 results = [] class Decorators(): def calc_decorator(func): def inner(self, a, b): result = func(self, a, b) cr = CalculatorResult(func.__name__, result) Calculator.results.append(cr) ...
.parametrize('num_of_slices', [7]) .parametrize('size', [55, 31]) .parametrize('batch_size', [1, 3]) .parametrize('shuffle', [False]) .parametrize('drop_last', [True, False]) def test_sliced_data_iterator_equivalence(test_data_csv_png_10, num_of_slices, size, batch_size, shuffle, drop_last): def lcm(a, b): ...
def OA_17_560(): from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF alpha = 5 beta = 4 p = 2 k = 17 m = 16 n = (p ** alpha) G = GF((p, alpha), prefix='x') G_set = sorted(G) G_to_int = {v: i for (i, v) in enumerate(G_set)} OA = [[G_to_int[(i + (x * ...
def simGetSimulationTimeStep(): step = lib.simGetSimulationTimeStep() _check_return(step) return step
def test_sample_sym(): gaussian = DiagonalGaussian(dim=2) dist = dict(mean=np.array([1.0, 1.0], dtype=np.float32), log_std=np.array([0.0, 0.0], dtype=np.float32)) samples = [gaussian.sample_sym(dist).numpy() for _ in range(10000)] assert np.isclose(np.mean(samples), 1, atol=0.1) assert np.isclose(np...
def get_dataloader(dataset, tokenizer, args, split='train'): def collate(examples): if (tokenizer._pad_token is None): if (args.model_type == 'gpt2_double'): text = [ex[0] for ex in examples] labels = [ex[1] for ex in examples] padded_labels = torc...
class RosenbrockBenchmark(Benchmark): def __init__(self, nb_features: int=2): self.nb_features = nb_features ind_domain = ((- 2.048), 2.048) super().__init__(fn=algorithms.partial(illumination_rosenbrock, nb_features=nb_features), ind_domain=ind_domain, fitness_domain=((0.0, math.inf),), fea...
class Sampling(Estimator): def __init__(self, table, ratio, seed): super(Sampling, self).__init__(table=table, version=table.version, ratio=ratio, seed=seed) self.sample = table.data.sample(frac=ratio, random_state=seed) self.sample_num = len(self.sample) def query(self, query): ...
def create_GAT_model(graph): generator = FullBatchNodeGenerator(graph, sparse=False, method=None) train_gen = generator.flow([0, 1], np.array([[1, 0], [0, 1]])) gat = GAT(layer_sizes=[2, 2], generator=generator, bias=False, in_dropout=0, attn_dropout=0, activations=['elu', 'softmax'], normalize=None, salien...
class GdsMaterialStackLayer(schema_utils.Model): foreground = types.ModelType(Material) background = types.ModelType(Material) extents = optplan.vec2d() gds_layer = types.ListType(types.IntType())
def validate_headers(ctx: click.core.Context, param: click.core.Parameter, raw_value: tuple[(str, ...)]) -> dict[(str, str)]: headers = {} for header in raw_value: with reraise_format_error(header): (key, value) = header.split(':', maxsplit=1) value = value.lstrip() key = key...
class CorundumVerilatorNIC(NICSim): def __init__(self) -> None: super().__init__() self.clock_freq = 250 def resreq_mem(self) -> int: return 512 def run_cmd(self, env: ExpEnv) -> str: return self.basic_run_cmd(env, '/corundum/corundum_verilator', str(self.clock_freq))
class IsolationForestConfig(DetectorConfig): _default_transform = TransformSequence([DifferenceTransform(), Shingle(size=2, stride=1)]) def __init__(self, max_n_samples: int=None, n_estimators: int=100, n_jobs=(- 1), **kwargs): self.max_n_samples = (1.0 if (max_n_samples is None) else max_n_samples) ...
def exchook(exc_type, exc_obj, exc_tb): if (exc_type is KeyboardInterrupt): print(('SprintExternInterface[pid %i]: KeyboardInterrupt' % (os.getpid(),))) sys.exit(1) better_exchook.better_exchook(exc_type, exc_obj, exc_tb)
class Transition(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.in_channels = in_channels self.out_channels = out_channels def forward(x): pass
def make_read_x(): sdfg = SDFG('spmv_read_x') (pre_state, body, post_state) = make_iteration_space(sdfg) x_mem = body.add_array('x_mem', (cols,), dtype, storage=StorageType.FPGA_Global) col_pipe = body.add_stream('col_pipe', itype, storage=StorageType.FPGA_Local) compute_pipe = body.add_stream('comp...
def test_sentences(): docs = list(Reader(utf8_open(CONLL_MULTISENT))) for d in docs: last = None for s in d.sentences: for span in s: if last: assert (span.start == last) else: assert (span.start == 0) ...
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): assert isinstance(commands, list) process = None popen_kwargs = {} if (sys.platform == 'win32'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW po...
def register_Ns3FlameFlameHeader_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_constructor([param('ns3::flame::FlameHeader const &', 'arg0')]) cls.add_constructor([]) cls.add_method('AddCost', 'void', [param('uint8_t', 'cost')]) cls.add_method('Deserialize', 'uint32_t',...
class TrainOptions(BaseOptions): def initialize(self, parser): parser = BaseOptions.initialize(self, parser) parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen') parser.add_argument('--display_ncols', type=int, default=4, help='...
def fused_leaky_relu(input, bias, negative_slope=0.2, scale=(2 ** 0.5)): global use_custom_kernel if use_custom_kernel: return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) else: dims = ([1, (- 1)] + ([1] * (input.dim() - 2))) bias = bias.view(*dims) return...
def _is_list_of_str(obj): return (isinstance(obj, list) and all((isinstance(item, six.string_types) for item in obj)))
def test_thrombocytopenia(tmp_path: pathlib.Path): outcome_codes = {'child_1_1', 'child_2', 'SNOMED/', 'child_1', 'SNOMED/'} _create_specific_labvalue_labeler(ThrombocytopeniaCodeLabeler, outcome_codes)
def train(): global train_step, train_loss, best_val_loss, eval_start_time, log_start_time model.train() if (args.batch_chunk > 1): mems = [tuple() for _ in range(args.batch_chunk)] else: mems = tuple() train_iter = (tr_iter.get_varlen_iter() if args.varlen else tr_iter) for (bat...
def main(): parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument('input', help='Cirrus Json wiki dump file') groupO = parser.add_argument_group('Output') groupO.add_argument('-o', '--output', d...
(**njit_dict_no_parallel) def pair_creation_packet(packet): probability_gamma = ((2 * ELECTRON_MASS_ENERGY_KEV) / (H_CGS_KEV * packet.nu_cmf)) if (np.random.random() > probability_gamma): packet.status = GXPacketStatus.PHOTOABSORPTION return packet new_direction = get_random_unit_vector() ...
def get_n_params(model): pp = 0 for p in list(model.parameters()): nn = 1 for s in list(p.size()): nn = (nn * s) pp += nn return pp
class CleanAuthors(): def __init__(self, authors): self.authors = authors def get_valid_names(self, blocklist): authors = set() for author in self.authors: if (not self.contains_blocklist(author, blocklist)): if (len(author) > 1): authors.a...
def eg_rule_action1(memories_info, args): def eg_req_func(protocols, args): for protocol in protocols: if isinstance(protocol, EntanglementGenerationA): return protocol memories = [info.memory for info in memories_info] memory = memories[0] protocol = EntanglementGene...
class FblasDiag(aenum.AutoNumberEnum): FblasUnit = ((),) FblasNoUnit = ((),) FblasDiagUndef = ()
def get_lr_scheduler_class(args): attr = getattr(args, 'lr_scheduler') if (attr['type'] in pipe.optimizers.lr_scheduler.ADDITIONAL_AVAILABLE_LR_SCHEDULERS): scheduler_cls = pipe.optimizers.lr_scheduler.ADDITIONAL_AVAILABLE_LR_SCHEDULERS[attr['type']] else: scheduler_cls = getattr(torch.optim...
class MHSA_stage_adapt_M(nn.Module): def __init__(self, seq_length, dim, num_layers, num_heads, mlp_ratio, qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, num_domains=4, norm_layer=nn.LayerNorm, adapt_method=None, crpe_window={3: 2, 5: 3, 7: 3}): super(MHSA_stage_adapt_M...
_utils.test(debug=True, advanced_optimization=False, exclude=[ti.vulkan, ti.metal, ti.opengl, ti.gles]) def test_ipow_negative_exp_i32(): _ipow_negative_exp(ti.i32)
def torch_where(condition, x, y): return ((condition.to(device='meta') + x.to(device='meta')) + y.to(device='meta'))
def plot_partitioning(axs, field, cell_tasks, gfd, output_dir, size): mesh = field.domain.mesh ax = pc.plot_wireframe(axs[0], mesh.cmesh) coors = field.get_coor() econn = field.econn ax = pd.plot_global_dofs(ax, coors, econn) ax.set_title('global DOFs') ax.figure.savefig(os.path.join(output_...
def GetUpdatedAPdrawDataset(opt, img_path, img_background): opt.im_p = img_path opt.img_background = img_background data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() return dataset
def computeROUGE(outputs, targets, rouge_types): targets = [target[0] for target in targets] rouge_metric = load_metric('rouge') return rouge_metric.compute(references=targets, predictions=outputs, rouge_types=rouge_types)
def weights_init(m): classname = m.__class__.__name__ if (classname.find('Conv') != (- 1)): m.weight.data.normal_(0.0, 0.01) m.bias.data.normal_(0.0, 0.01) elif (classname.find('BatchNorm') != (- 1)): m.weight.data.normal_(1.0, 0.01) m.bias.data.fill_(0)
class ExponentialLR(_LRScheduler): def __init__(self, optimizer, gamma, last_epoch=(- 1), verbose=False): self.gamma = gamma super(ExponentialLR, self).__init__(optimizer, last_epoch, verbose) def get_lr(self): if (not self._get_lr_called_within_step): warnings.warn('To get t...
.parametrize('n', [0, 1, 2]) .parametrize('x', [0, 1, np.nan]) def test_hermite_nan(n, x): assert (np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x]))) assert (np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x])))
def export(): dummy_input = torch.randn(1, 3, 224, 224) model = torchvision.models.resnet18(pretrained=True) torch.onnx.export(model, dummy_input, 'resnet.onnx')
def parse_cfg(cfg, args): if (len(cfg.task) == 0): raise ValueError('task must be specified') os.environ['CUDA_VISIBLE_DEVICES'] = ', '.join([str(gpu) for gpu in cfg.gpus]) if (cfg.task in _heads_factory): cfg.heads = _heads_factory[cfg.task] cfg.det_dir = os.path.join(cfg.model_dir, cfg...
class RecurrentDropoutLSTMCell(RNNCellBase): def __init__(self, input_size, hidden_size, dropout=0.0): super(RecurrentDropoutLSTMCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.dropout = dropout self.W_i = Parameter(torch.Tensor(hidden_...
def simulate_test_prior(n=1000, fixm=False, fixz=False, fixalign=False): logger.info('Generating prior test data with %s images', n) (f_sub, beta) = draw_params_from_prior(n) (theta, x, _, _, _, z) = augmented_data(f_sub=f_sub, beta=beta, n_images=n, mine_gold=False, draw_host_mass=(not fixm), draw_host_red...
class StepLrUpdaterHook(LrUpdaterHook): def __init__(self, step, gamma=0.1, **kwargs): assert isinstance(step, (list, int)) if isinstance(step, list): for s in step: assert (isinstance(s, int) and (s > 0)) elif isinstance(step, int): assert (step > 0) ...
def test_listarray(): listoffsetarray = ak_Array([[1, 2, 3], [], [4, 5]]).layout listarray = ak.contents.ListArray(listoffsetarray.starts, listoffsetarray.stops, listoffsetarray.content) assert (ak_from_buffers(*ak_to_buffers(listarray)).to_list() == [[1, 2, 3], [], [4, 5]]) assert (pickle.loads(pickle....
.parametrize('categorical_as_dictionary', [False, True]) .parametrize('extensionarray', [False, True]) def test_dictionary_encoding(tmp_path, categorical_as_dictionary, extensionarray): akarray = ak.contents.IndexedArray(ak.index.Index64(np.array([3, 2, 2, 2, 0, 1, 3], dtype=np.uint64)), ak.contents.NumpyArray(np.a...
def buffered_random(stream, buffer_items=100, leak_percent=0.9): item_buffer = ([None] * buffer_items) leak_count = int((buffer_items * leak_percent)) item_count = 0 for item in stream: item_buffer[item_count] = item item_count += 1 if (buffer_items == item_count): ra...
def random_rotate(image, label): angle = np.random.randint((- 20), 20) image = ndimage.rotate(image, angle, order=0, reshape=False) label = ndimage.rotate(label, angle, order=0, reshape=False) return (image, label)
_optimizer('sgd') class SGD(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = torch.optim.SGD(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--momentum', default=0.0, type=float, metavar='M', help='momentum factor')...
class Bsite_extractor(): def __init__(self, lig_thres, bw=15): self.T = lig_thres self.ms = MeanShift(bandwidth=bw, bin_seeding=True, cluster_all=False, n_jobs=4) def _cluster_points(self, prot, lig_scores): T_new = self.T while ((sum((lig_scores >= T_new)) < 10) and (T_new > 0.3...
class Configuration(object): def __init__(self, *args, **kwargs): for (opt, val) in zip(list(PROJECT_CONFIG['options'].keys())[:len(args)], args): setattr(self, opt, PROJECT_CONFIG['options'][opt]['type'](val)) for (opt, val) in kwargs.items(): if (opt not in PROJECT_CONFIG['...
def main(): parser = argparse.ArgumentParser(description='PyTorch Object Detection Training') parser.add_argument('--config-file', default='', metavar='FILE', help='path to config file', type=str) parser.add_argument('--local_rank', type=int, default=0) parser.add_argument('--skip-test', dest='skip_test...
class Omniglot(data.Dataset): folder = 'omniglot-py' download_url_prefix = ' zips_md5 = {'images_background': '68d2efa1b9178cc56df9314c21c6e718', 'images_evaluation': '6b91aef0f799c5bb55b94e3f2daec811'} def __init__(self, root, background=True, transform=None, target_transform=None, download=False): ...
class MaterialOptimizer(object): def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp (required, other) = get_stand...
def make_multiagent_env(env_id, num_agents, dist_threshold, arena_size, identity_size): scenario = scenarios.load((env_id + '.py')).Scenario(num_agents=num_agents, dist_threshold=dist_threshold, arena_size=arena_size, identity_size=identity_size) world = scenario.make_world() env = MultiAgentEnv(world=world...
def get_workspace_path(agent: Agent, file_name: str) -> str: return str(agent.workspace.get_path(file_name))
def read_contamination(): hlog(f'Reading contamination information from {CONTAMINATION_YAML_FILENAME}...') contamination_path = resources.files(CONTAMINATION_YAML_PACKAGE).joinpath(CONTAMINATION_YAML_FILENAME) with contamination_path.open('r') as f: raw = yaml.safe_load(f) return dacite.from_dic...
def make_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, verbose_logging): example_index_to_features = collections.defaultdict(list) for feature in all_features: example_index_to_features[feature.example_index].append(feature) unique_id_to_result =...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() conv_kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1} self.conv1 = nn.Conv2d(3, 16, **conv_kwargs) self.conv2 = nn.Conv2d(16, 32, **conv_kwargs) self.conv3 = nn.Conv2d(32, 64, **conv_kwargs) s...
class VectorDiscriminator(nn.Module): def __init__(self, input_nc=64, n_layers=2, use_sigmoid=True, gpu_ids=[]): super(VectorDiscriminator, self).__init__() self.gpu_ids = gpu_ids ndf = (2 * input_nc) sequence = [nn.Linear(input_nc, ndf, bias=True), nn.LeakyReLU(0.1, inplace=False)] ...
def handler(event): sleep_time = event.get('sleep') sleep(sleep_time) return {'result': sleep_time}
def setup_ec2(): for region in ['us-west-1', 'us-west-2', 'us-east-1']: print(('Setting up region %s' % region)) ec2 = boto3.resource('ec2', region_name=region, aws_access_key_id=ACCESS_KEY, aws_secret_access_key=ACCESS_SECRET) ec2_client = boto3.client('ec2', region_name=region, aws_access_...
_utils.test() def test_fill_vector_field_recompile(): a = ti.Vector.field(2, ti.i32, shape=3) for i in range(2): a.fill(ti.Vector([0, 0])) assert (impl.get_runtime().get_num_compiled_functions() == 1)
def gen_dependent_configs(xenial_parent_config): extra_parms = [(['multigpu'], 'large'), (['nogpu', 'NO_AVX2'], None), (['nogpu', 'NO_AVX'], None), (['slow'], 'medium')] configs = [] for (parms, gpu) in extra_parms: c = Conf(xenial_parent_config.distro, (['py3'] + parms), pyver=xenial_parent_config....
def run(testdir, cli, unique_hook, schema, openapi3_base_url, hypothesis_max_examples, *args): schema_file = testdir.make_openapi_schema_file(schema) return cli.main('run', str(schema_file), f'--base-url={openapi3_base_url}', '-cunique_test_cases', f'--hypothesis-max-examples={(hypothesis_max_examples or 30)}',...
def parallel_hash(data, format): duplicate_groups = {} process_func = {'solid': hash_solid, 'profile': hash_profile, 'loop': hash_loop, 'model': hash_model} num_cpus = multiprocessing.cpu_count() objs_iter = multiprocessing.Pool(num_cpus).imap(process_func[format], data) for (h, uid) in tqdm(objs_it...
def _precision_micro_3d(y_true: np.ndarray, y_pred: np.ndarray): sum_intersection = 0 sum_prediction_and_ancestors = 0 for (row_ground_truth, row_prediction) in zip(y_true, y_pred): ground_truth_set = set() predicted_set = set() for (ground_truth, prediction) in zip(row_ground_truth,...
def two_conv_model(): inputs = Input(shape=INPUT_SHAPE) x = Conv2D(2, 3)(inputs) x = BatchNormalization()(x) x = ReLU()(x) outputs = Conv2D(2, 3)(x) return keras.Model(inputs=inputs, outputs=outputs)
def build_dataloader(cfg, dataset): if cfg.distributed: if (dataset.which_set == 'train'): sampler = DistributedGroupSampler(dataset, cfg.data.samples_per_gpu, cfg.world_size, cfg.rank, seed=cfg.seed) else: sampler = DistributedSampler(dataset, cfg.world_size, cfg.rank, shuff...
class HyperbolicArcCore(BezierPath): def _bezier_path(self, z0, z1, model, first=False): import numpy as np from sage.rings.infinity import infinity EPSILON = (10 ** (- 5)) arc0 = model.get_geodesic(z0, z1).plot()[0] if isinstance(arc0, BezierPath): points = arc0....
def pipeline_archetype5(): ink_phase = [Faxify(monochrome=1, monochrome_method='threshold_otsu', halftone=0), InkBleed(intensity_range=(0.3, 0.4), kernel_size=(3, 3), severity=(1.0, 1.0)), Scribbles(scribbles_type='text', scribbles_ink='pen', scribbles_location=(0.8, 0.8), scribbles_size_range=(320, 320), scribbles...
class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False, return_intermediate_dec=False): super().__init__() encoder_layer = TransformerEncoderLayer(d_model, nhead, ...
def rand_data(shape, dtype): if (dtype == 'float32'): return np.random.random(shape).astype(np.float32) if ((dtype == 'int32') or 'uint32' or 'int16' or 'uint16' or 'int8' or 'uint8'): return np.random.randint(0, 256, size=shape).astype(dtype) raise Exception('Not supported data type: {}!'.f...
class ExperimentWorkspace(): def __init__(self, experiment_name: str, data_file_path: Path, install_requirements: bool=False, remove_archive: bool=True) -> None: self.experiment_name = experiment_name self.data_file_path = data_file_path self.install_requirements = install_requirements ...
class LogLevel(): DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR CRITICAL = logging.CRITICAL
def random_ndarray(n, p, seed): import string random.seed(seed) alphabet = list(string.ascii_uppercase) return random.choice(alphabet, size=(n, p))
def process_routing(_obj, _method, /, **kwargs): if ((not _routing_enabled()) and (not kwargs)): class EmptyRequest(): def get(self, name, default=None): return (default if default else {}) def __getitem__(self, name): return Bunch(**{method: dict() fo...
class SBMPDCSVD(SBMPATTERNEval, BaseSVDModelScheme): def get_default_config(self): config_dict = super().get_default_config() config_dict.update(dataset_name='sbm_pattern', class_sizes=[979220, 209900], rlr_monitor='val_xent', save_best_monitor='val_xent') return config_dict def get_data...
def test_dia_fields(): (M, N, nnz, num_diags) = (dace.symbol(s) for s in ('M', 'N', 'nnz', 'num_diags')) diag = dace.data.Tensor(dace.float32, (M, N), [(dace.data.TensorIndexDense(), num_diags), (dace.data.TensorIndexRange(), 0), (dace.data.TensorIndexOffset(), 1)], nnz, 'DIA_Matrix') expected_fields = ['id...