code
stringlengths
101
5.91M
def label_mapping(input, mapping): output = np.copy(input) for ind in range(len(mapping)): output[(input == mapping[ind][0])] = mapping[ind][1] return np.array(output, dtype=np.int64)
def parse_config(): parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config for training') parser.add_argument('--batch_size', type=int, default=None, required=False, help='batch size for training') parser.add_argument...
class RandomActiveLearningNodeMC(LearningNodeMC, RandomActiveLeafClass): def __init__(self, initial_stats=None, max_features=2, random_state=None): super().__init__(initial_stats) self.max_features = max_features self.feature_indices = np.array([]) self.random_state = random_state ...
def handy_var(a, unbias=True): n = a.size(0) asum = a.sum(dim=0) as_sum = (a ** 2).sum(dim=0) sumvar = (as_sum - ((asum * asum) / n)) if unbias: return (sumvar / (n - 1)) else: return (sumvar / n)
class MaskedImageModelingOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None reconstruction: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None def logits(self): warnings.warn('logits attribute is ...
class BaseOptions(): def __init__(self): self.initialized = False def initialize(self, parser): g_ours = parser.add_argument_group('DeepHuman') g_ours.add_argument('--meshDirSearch', type=str, default='/trainman-mount/trainman-storage-d5c0a121-bb5d-4afb-8020-c53f096d2a5c/data') g...
def AlignedOneImageUsingFaceXAlignment(input_root, out_root, image_path): try: image = cv2.imread(image_path, cv2.IMREAD_COLOR) (input_height, input_width, _) = image.shape except: return dets = faceDetModelHandler.inference_on_image(image) if (len(dets) > 0): dets = Filt...
def _distributed_worker(local_rank, main_func, world_size, num_gpus_per_machine, machine_rank, dist_url, args, timeout=DEFAULT_TIMEOUT): assert torch.cuda.is_available(), 'cuda is not available. Please check your installation.' global_rank = ((machine_rank * num_gpus_per_machine) + local_rank) try: ...
def batch_recall(candidates, sources, gold_edits, max_unchanged_words=2, beta=0.5, ignore_whitespace_casing=False, verbose=False): return batch_pre_rec_f1(candidates, sources, gold_edits, max_unchanged_words, beta, ignore_whitespace_casing, verbose)[1]
class TestThreading(object): def check_func_thread(self, n, fun, args, out): from threading import Thread thrds = [Thread(target=fun, args=args, kwargs={'output': out[x]}) for x in range(n)] [t.start() for t in thrds] [t.join() for t in thrds] def check_func_serial(self, n, fun, ...
class DeformRoIPooling(nn.Module): def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0): super(DeformRoIPooling, self).__init__() self.spatial_scale = spatial_scale self.out_size = out_size self.out_channe...
def process_part(header_contents): retval = list() l = list() for elem in header_contents: headers = elem.header if ((len(headers) > 0) and headers[0].strip().lower().startswith('part')): l.append(len(headers)) max_count = max(set(l), key=l.count) for elem in header_conte...
(config_path='config/preprocessing.yaml') def preprocess_dataset(cfg): in_dir = Path(utils.to_absolute_path(cfg.in_dir)) out_dir = (Path(utils.to_absolute_path('datasets')) / str(cfg.dataset.dataset)) out_dir.mkdir(parents=True, exist_ok=True) executor = ProcessPoolExecutor(max_workers=cpu_count()) ...
def generate_combos(): wkload_combos = [] for seq in ['readseq', 'readreverse']: for rand in ['readrandom', 'readrandomwriterandom', 'mixgraph']: wkload_combos.append((seq, rand)) return wkload_combos
class ReduLayer(nn.Module): def __init__(self): super(ReduLayer, self).__init__() def __name__(self): return 'ReduNet' def forward(self, Z): raise NotImplementedError def zero(self): state_dict = self.state_dict() state_dict['E.weight'] = torch.zeros_like(self.E.w...
class RandomHorizontalFlip(): def __init__(self, p=0.5): self.p = p def __call__(self, sample): if (random.random() < self.p): (image, target) = sample image = (F.hflip(image) if isinstance(image, torch.Tensor) else image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)) ...
.parametrize('dataset_type', [pytest.param('log_spark', marks=pytest.mark.spark), pytest.param('log', marks=pytest.mark.core)]) .parametrize('test_size', test_sizes) def test_nothing_is_lost(test_size, dataset_type, request): log = request.getfixturevalue(dataset_type) splitter = RandomSplitter(test_size=test_s...
class PretrainConfig(): defaults: List[Any] = field(default_factory=(lambda : DEFAULTS)) hydra: Dict[(str, Any)] = field(default_factory=(lambda : {'run': {'dir': 'runs/train/${model.identifier}+dataset-${dataset.name}'}})) run_id: Optional[str] = None seed: int = 21 resume: bool = True wandb_re...
class BaseRealBanditDataset(BaseBanditDataset): def load_raw_data(self) -> None: raise NotImplementedError def pre_process(self) -> None: raise NotImplementedError
(frozen=True) class ModelDeployment(): name: str client_spec: ClientSpec model_name: Optional[str] = None tokenizer_name: Optional[str] = None window_service_spec: Optional[WindowServiceSpec] = None max_sequence_length: Optional[int] = None max_request_length: Optional[int] = None max_se...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', required=True) parser.add_argument('--config-args') args = parser.parse_args() if args.config_args: config = json.loads(_jsonnet.evaluate_file(args.config, tla_codes={'args': args.config_args})) else: ...
def main(root, tsv_path, ckpt_path, layer, nshard, rank, feat_dir, split, max_chunk): reader = HubertFeatureReaderS2T(ckpt_path, layer, max_chunk) (generator, num) = get_path_iterator(root, tsv_path, nshard, rank) dump_feature(reader, generator, num, split, nshard, rank, feat_dir)
.node class CSRMM(dace.sdfg.nodes.LibraryNode): implementations = {'pure': ExpandCSRMMPure, 'MKL': ExpandCSRMMMKL, 'cuSPARSE': ExpandCSRMMCuSPARSE} default_implementation = None transB = properties.Property(dtype=bool, desc='Whether to transpose B before multiplying') alpha = properties.Property(allow_n...
class pseudo_audio(): def __init__(self, secs: List[float], sample_rate: int=SAMPLE_RATE): self.tempdir = Path(tempfile.TemporaryDirectory().name) self.tempdir.mkdir(parents=True, exist_ok=True) self.num_samples = [] for (n, sec) in enumerate(secs): wav = torch.randn(1, r...
def init_particles(x: ti.types.ndarray(ndim=1), v: ti.types.ndarray(ndim=1), J: ti.types.ndarray(ndim=1)): for i in range(n_particles): x[i] = [((ti.random() * 0.4) + 0.2), ((ti.random() * 0.4) + 0.2)] v[i] = [0, (- 1)] J[i] = 1
def run_inference(args, ind_range=None, multi_gpu_testing=False): is_parent = (ind_range is None) def result_getter(): if is_parent: return test_net_on_dataset(args, multi_gpu=multi_gpu_testing) else: return test_net(args, ind_range=ind_range) all_results = result_get...
def get_ANLI_examples(prefix, hypo_only=False): folders = ['R1', 'R2', 'R3'] examples = [] guid_id = 0 pos_size = 0 neg_size = 0 path = '/export/home/Dataset/para_entail_datasets/ANLI/anli_v0.1/' for folder in folders: filename = ((((path + folder) + '/') + prefix) + '.jsonl') ...
def _plot_pixel_importance(attributions, image, polarity='positive', clip_above_percentile=99.0, clip_below_percentile=0, outlines_component_percentage=90, use_linear_transform=True, overlay=False): if (polarity == 'both'): pos_attributions = _plot_pixel_importance(attributions, image, polarity='positive', ...
def test_fake_deps_only_root(): result = maybe_add_fake_dependencies(ONLY_ROOT_EXAMPLE) assert (result == ONLY_ROOT_EXPECTED)
.script def bias_gelu(y, bias): x = (bias + y) return ((x * 0.5) * (1.0 + torch.tanh(((0. * x) * (1 + ((0.044715 * x) * x)))))).to(dtype=y.dtype)
def generate_gif(frames, path, size=(180, 180, 3), duration=(1 / 20)): import imageio from skimage.transform import resize for (idx, frame_idx) in enumerate(frames): frames[idx] = resize(frame_idx, size, preserve_range=True, order=0).astype(np.uint8) imageio.mimsave(path, frames, duration=durati...
def parse(task_log, tool_log, tool_output): tool = task_log['tool'] filename = task_log['filename'] exit_code = task_log['result']['exit_code'] tool_parser = get_parser(tool) try: (findings, infos, errors, fails) = tool_parser.parse(exit_code, tool_log, tool_output) for finding in fi...
.skip def test_inline_lambda_scalar(): def lamb(A: dace.float64[20], B: dace.float64[20], C: dace.float64[20]): f = (lambda a, b: (a + b)) for i in dace.map[0:20]: A[i] = f(B[i], C[i]) A = np.random.rand(20) B = np.random.rand(20) C = np.random.rand(20) lamb(A, B, C) ...
def dump_conv2d_nobn(name='Conv2d_1x1'): conv_operation = sess.graph.get_operation_by_name((('InceptionResnetV2/' + name) + '/Conv2D')) weights_tensor = sess.graph.get_tensor_by_name((('InceptionResnetV2/' + name) + '/weights:0')) weights = weights_tensor.eval() biases_tensor = sess.graph.get_tensor_by_...
class Sequential(torch.nn.Sequential): def __init__(self, *args): super(Sequential, self).__init__() if ((len(args) == 1) and isinstance(args[0], OrderedDict)): for (key, module) in args[0].items(): self.add_module(key, module) else: discount_none = 0 ...
class DIN(BaseModel): def __init__(self, dnn_feature_columns, history_feature_list, dnn_use_bn=False, dnn_hidden_units=(256, 128), dnn_activation='relu', att_hidden_size=(64, 16), att_activation='Dice', att_weight_normalization=False, l2_reg_dnn=0.0, l2_reg_embedding=1e-06, dnn_dropout=0, init_std=0.0001, seed=1024...
class MjrRectWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src def ptr(self): return self._wrapped def obj(self): return self._wrapped.contents def left(self): return self._wrapped.contents.left def ...
def try_rewrite_ast_with_print(code): try: return rewrite_ast_with_print(code) except Exception as e: print(e) return code
def apply_hysteresis_threshold(image, low, high): low = np.clip(low, a_min=None, a_max=high) mask_low = (image > low) mask_high = (image > high) (labels_low, num_labels) = ndi.label(mask_low) sums = ndi.sum(mask_high, labels_low, np.arange((num_labels + 1))) connected_to_high = (sums > 0) th...
class FairseqTask(object): def add_args(parser): pass def __init__(self, args): self.args = args self.datasets = {} def setup_task(cls, args, **kwargs): return cls(args) def load_dataset(self, split, combine=False): raise NotImplementedError def dataset(self, ...
_model def skresnet34(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['skresnet34'] sk_kwargs = dict(min_attn_channels=16, attn_reduction=8, split_input=True) model = ResNet(SelectiveKernelBasic, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, block_args=dict(...
def _constant_fill(g, sizes, dtype, const_value): if (dtype is None): dtype = 6 if (not sym_help.scalar_type_to_pytorch_type[dtype].is_floating_point): result = g.op('ConstantFill', sizes, dtype_i=sym_help.cast_pytorch_to_onnx['Float'], input_as_shape_i=1, value_f=const_value) return sym...
class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() self.l1 = nn.Linear((state_dim + action_dim), 256) self.l2 = nn.Linear(256, 256) self.l3 = nn.Linear(256, 1) self.l4 = nn.Linear((state_dim + action_dim), 256) self.l5 =...
def get_feature_detector(url, device=torch.device('cpu'), num_gpus=1, rank=0, verbose=False): assert (0 <= rank < num_gpus) key = (url, device) if (key not in _feature_detector_cache): is_leader = (rank == 0) if ((not is_leader) and (num_gpus > 1)): torch.distributed.barrier() ...
class SequencePredictor(): def __init__(self, builder): self.builder = builder def predict_sequence(self, inputs): return [self.builder(x) for x in inputs]
def backup_code(save_path, save_parent=False, ignored_in_current_folder=None, marked_in_parent_folder=None): if (ignored_in_current_folder is None): ignored_in_current_folder = ['tmp', 'log', 'data', '__pycache__', 'output', 'sythc_data'] if (marked_in_parent_folder is None): marked_in_parent_fo...
class MultilayerTest(unittest.TestCase): def setUp(self): warnings.filterwarnings('ignore') np.random.seed(42) w2 = (np.random.randn(20, 50) / np.sqrt(50)) w1 = (np.random.randn(50, 100) / np.sqrt(100)) alpha2 = (float(w2.shape[0]) / w2.shape[1]) alpha1 = (float(w1.sh...
('coref') class ConllCorefReader(DatasetReader): def __init__(self, max_span_width: int, token_indexers: Dict[(str, TokenIndexer)]=None) -> None: self._max_span_width = max_span_width self._token_indexers = (token_indexers or {'tokens': SingleIdTokenIndexer()}) self._begin_document_regex = r...
def build_gauss_wavefront_xy(nx, ny, ekev, xMin, xMax, yMin, yMax, sigX, sigY, d2waist, xoff=0.0, yoff=0.0, tiltX=0.0, tiltY=0.0, pulseEn=None, pulseTau=None, repRate=None, _mx=None, _my=None): GsnBm = srwlib.SRWLGsnBm() GsnBm.x = xoff GsnBm.y = yoff GsnBm.z = 0 GsnBm.xp = tiltX GsnBm.yp = tiltY...
def generate_vuv(condition, cat_input): model_path = 'snapshots/vuv' model = load_latest_model_from(2, model_path) gen = model.generate(condition, cat_input).squeeze() return gen.cpu().numpy().astype(np.uint8)
def _child_of(node: SDFGState, parent: SDFGState, ptree: Dict[(SDFGState, SDFGState)]) -> bool: curnode = node while (curnode is not None): if (curnode is parent): return True curnode = ptree[curnode] return False
class MentionCandidatesTranslator(FromParams): def __init__(self, inter_wiki_path: str, multilingual_entity_db_path: Dict[(str, str)]=None): self.inter_wiki_db = InterwikiDB.load(inter_wiki_path) multilingual_entity_db_path = (multilingual_entity_db_path or {}) self.entity_db_dict = {lang: E...
class ConfigParser(): def __init__(self, file_path): directory = os.path.dirname(os.path.abspath(__file__)) if (file_path is None): file_path = os.path.join(directory, 'configs/default.yaml') with open(file_path, 'r') as f: self.config = yaml.safe_load(f) if (...
def GetHits_PDirNet(Graph, NIdHubH, NIdAuthH, MaxIter=20): return _snap.GetHits_PDirNet(Graph, NIdHubH, NIdAuthH, MaxIter)
class _DecoratorBaseClass(): _stack_length = {} def get_stack_length(self, func): return self._stack_length.get(func.__name__, _get_stack_length(func))
class ThreeInterpolate(Function): def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: assert features.is_contiguous() assert idx.is_contiguous() assert weight.is_contiguous() (B, c, m) = features.size() n = idx.size(1) ct...
def pickle_dump(python_object, file_path): make_parent(file_path) with open(file_path, 'wb') as f: pickle.dump(python_object, f)
def push_graphs_to_main_directory(model_dirname, name): dirname = model_dirname files = os.listdir(dirname) files = [f for f in files if f.endswith('svg')] for f in files: outdir = f[:(- 4)] output_name = os.path.join('graph_outputs', outdir) os.makedirs(output_name, exist_ok=Tru...
def mk_lean_function_auto_soundness_theorem(func: LeanFunctionInfo, lean_info: LeanProgramInfo, assembly_info: LeanAssemblyInfo, out): soundness_gen = LeanSoundnessGen(func=func, lean_info=lean_info, assembly_info=assembly_info) soundness_gen.gen_blocks() proofs = soundness_gen.gen_func_proofs() for lin...
def pytest_addoption(parser): group = parser.getgroup('timeout', 'Interrupt test run and dump stacks of all threads after a test times out') group.addoption('--timeout', type=float, help=TIMEOUT_DESC) parser.addini('timeout', TIMEOUT_DESC) parser.addini('timeout_func_only', FUNC_ONLY_DESC, type='bool')
def test__get_reference_position_multi(sample_test_case): assert (tf.TestFactory._get_reference_positions(sample_test_case, 0) == {0, 2, 3})
class Resnet3dCSNiRLight(Resnet3dEmbeddingMultiDecoder): def __init__(self, tw=16, sample_size=112, e_dim=7): super(Resnet3dCSNiRLight, self).__init__(decoders=[DecoderLight(), DecoderLight(n_classes=e_dim, conv_t=True)]) self.encoder = Encoder3d_csn_ir(tw, sample_size)
def segment_f1(segments: List[dict], segments_gold: List[dict]) -> float: if ((len(segments_gold) == 0) or (len(segments) == 0)): return (1 if (len(segments) == len(segments_gold)) else 0) precision = segment_precision(segments, segments_gold) recall = segment_recall(segments, segments_gold) ret...
def test_array_copy_outside_scope(): sdfg = dace.SDFG('array_copy_outside_scope') (iname, _) = sdfg.add_array('inp', (10,), dtype=dace.int32) (oname, _) = sdfg.add_array('out', (10,), dtype=dace.int32) nsdfg = dace.SDFG('nested_sdfg') (niname, nidesc) = nsdfg.add_array('ninp', (1,), dtype=dace.int32...
def collate_by_len(data, budget=((256 ** 2) * 64)): sorted_data = sorted(data, key=(lambda d: len(d[0])), reverse=True) idx = 0 splits = [] while (idx < len(data)): x = sorted_data[idx][0] cost_each = (len(x) ** 2) split_size = max((budget // cost_each), 16) last_idx = mi...
def process_generators_chain(gen_string, dim, base_ring=None): deprecation(33777, 'the CHomP interface is deprecated') from sage.modules.free_module_element import vector from sage.rings.integer_ring import ZZ if (base_ring is None): base_ring = ZZ g_srch = re.compile(('\\[H_%s\\]\\n([^]]*)(...
class DocumentState(OntoNotesDocumentState): def __init__(self, key): super().__init__(key) def finalize(self): self.final_processing() return {'doc_key': self.doc_key, 'sentences': self.segments, 'clusters': self.merged_clusters, 'sentence_map': self.sentence_map, 'subtoken_map': self.s...
class MultiHeadAttention(nn.Module): def __init__(self, n_head, d_model_read, d_model_write, d_model_out, d_k, d_v, num_blocks_read, num_blocks_write, topk, grad_sparse, residual=True, dropout=0.1, skip_write=False, joined_heads_write=False): super().__init__() self.n_head = n_head self.d_k ...
def _sentence_case(text: Any) -> Any: return (str(text).capitalize() if pd.notna(text) else text)
.parametrize('estimator', all_survival_function_estimators()) .parametrize('y_time', [(- 1e-08), (- 1), np.finfo(float).min]) def test_fit_negative_survial_time_raises(estimator, y_time): X = np.random.randn(7, 3) y = Surv.from_arrays(event=np.ones(7, dtype=bool), time=[1, 9, 3, y_time, 1, 8, .0]) with pyte...
def check_results(documents, expected_conllu, expected_txt, expected_labels): with tempfile.TemporaryDirectory() as output_dir: write_section(output_dir, 'orchid', 'train', documents) with open(os.path.join(output_dir, 'th_orchid.train.gold.conllu')) as fin: conllu = fin.read().strip() ...
def iter_traceback(tb=None, enforce_most_recent_call_first=False): if (tb is None): tb = get_current_frame() def is_stack_summary(_tb): return isinstance(_tb, StackSummary) is_frame = inspect.isframe is_traceback = inspect.istraceback assert (is_traceback(tb) or is_frame(tb) or is_st...
def skip(*filenames): for filename in filenames: if (not os.path.isfile(filename)): return False return True
def triplet_margin_loss_gor(anchor, positive, negative1, negative2, beta=1.0, margin=1.0, p=2, eps=1e-06, swap=False): assert (anchor.size() == positive.size()), 'Input sizes between positive and negative must be equal.' assert (anchor.size() == negative1.size()), 'Input sizes between anchor and negative must b...
def recognize_coxeter_type_from_matrix(coxeter_matrix, index_set): n = ZZ(coxeter_matrix.nrows()) G = Graph([index_set, [(index_set[i], index_set[j], coxeter_matrix[(i, j)]) for i in range(n) for j in range(i, n) if (coxeter_matrix[(i, j)] not in [1, 2])]], format='vertices_and_edges') types = [] for S ...
def argumenttype_type(t: Type, *, mutable: bool) -> str: if (local.use_c10_dispatcher() is UseC10Dispatcher.full): return cpp.argumenttype_type(t, mutable=mutable) else: return legacy_dispatcher.argumenttype_type(t, mutable=mutable)
def marching_cubes(fn, c1, c2, reso, isosurface, chunk): grid = np.vstack(np.meshgrid(*(np.linspace(lo, hi, sz, dtype=np.float32) for (lo, hi, sz) in zip(c1, c2, reso)), indexing='ij')).reshape(3, (- 1)).T h0print('* Evaluating sigma ', grid.shape[0], 'points') (rgbs, sigmas) = utils.eval_points(fn, grid, c...
class Data2VecTextForCausalLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_cursor_path(sqlite_path: str): try: if (not os.path.exists(sqlite_path)): print(('Openning a new connection %s' % sqlite_path)) connection = sqlite3.connect(sqlite_path) except Exception as e: print(sqlite_path) raise e connection.text_factory = (lambda b:...
def conv_block_d(input_tensor, f, use_norm=False, k=3, strides=2): x = input_tensor if (not (k == 1)): x = ReflectPadding2D(x) x = Conv2D(f, kernel_size=k, strides=strides, kernel_regularizer=regularizers.l2(w_l2), kernel_initializer=conv_init, use_bias=(not use_norm))(x) x = (normalization(x, '...
class _ConvBnReLU(nn.Sequential): BATCH_NORM = _BATCH_NORM def __init__(self, in_ch, out_ch, kernel_size, stride, padding, dilation, relu=True): super(_ConvBnReLU, self).__init__() self.add_module('conv', nn.Conv2d(in_ch, out_ch, kernel_size, stride, padding, dilation, bias=False)) self....
def get_path_to_root_old(node_idx, struct): paths_list = [] while (node_idx >= 0): paths_list.append(node_idx) node_idx = get_parent(node_idx, struct) return paths_list[::(- 1)]
def detect_special_tokens(word): try: int(word) word = SPECIAL_TOKENS[4] except ValueError: if AtMentionRegex.findall(word): word = SPECIAL_TOKENS[2] elif urlRegex.findall(word): word = SPECIAL_TOKENS[3] return word
class GANTask(GPUTask): def main(self): import os import tensorflow as tf from gan.load_data import load_dSprites from gan.latent import UniformLatent, JointLatent from gan.network import Decoder, InfoGANDiscriminator, CrDiscriminator, MetricRegresser from gan.infogan...
def delexicaliseDomain(utt, dictionary, domain): for (key, val) in dictionary: if ((key == domain) or (key == 'value')): utt = ((' ' + utt) + ' ').replace(((' ' + key) + ' '), ((' ' + val) + ' ')) utt = utt[1:(- 1)] for (key, val) in dictionary: utt = ((' ' + utt) + ' ')....
class SemanticSegAlgo(): def __init__(self, loss, num_classes, ignore_index=255): self.loss = loss self.num_classes = num_classes self.ignore_index = ignore_index def _pack_logits(sem_logits, valid_size, img_size): sem_logits = functional.interpolate(sem_logits, size=img_size, mo...
def _get_custom_interpreter(implementation=None, version=None): if (implementation is None): implementation = interpreter_name() if (version is None): version = interpreter_version() return '{}{}'.format(implementation, version)
def test_error_ndim(): arr_error = np.random.randn(1, 2) with testing.raises(ValueError): montage(arr_error) arr_error = np.random.randn(1, 2, 3, 4) with testing.raises(ValueError): montage(arr_error) arr_error = np.random.randn(1, 2, 3) with testing.raises(ValueError): m...
def get_tempo_info(beat_df): (mean, std) = (beat_df['duration'].mean(), beat_df['duration'].std()) return (sec2tempo(mean), (sec2tempo((mean - (2 * std))) - sec2tempo((mean + (2 * std)))))
def print_task_log(demo_task_counter, live_task_counter, mod): print() logger.info(f'Modality: {mod}') for task in demo_task_counter: logger.info((f'{task}: SR = {((live_task_counter[task] / demo_task_counter[task]) * 100):.0f}%' + f' | {live_task_counter[task]} of {demo_task_counter[task]}')) ...
class ConvMergeNetwork(LayersPowered, Serializable): def __init__(self, name, input_shape, extra_input_shape, output_dim, hidden_sizes, conv_filters, conv_filter_sizes, conv_strides, conv_pads, extra_hidden_sizes=None, hidden_W_init=L.XavierUniformInitializer(), hidden_b_init=tf.zeros_initializer(), output_W_init=L...
def main(cfg): (train_loader, train_loader_ca, train_loader_cb, val_loader_c, val_loader_b, num_query_c, num_query_b, num_classes) = make_data_loader(cfg, use_eraser=True) model = build_model(num_classes, 'base', pretrain_choice=True) model = (torch.nn.DataParallel(model).cuda() if torch.cuda.is_available()...
class TestTokenEmbedder(object): def embedder(self): vocab = SimpleVocab((['<unk>', '<start>', '<stop>'] + ['a', 'b', 'c'])) arr = np.eye(len(vocab), dtype=np.float32) word_embeddings = Bunch(vocab=vocab, array=arr) return TokenEmbedder(word_embeddings) def test_embedding_from_ar...
def LF_implant_indication(c): mention = c.implant.get_span().lower() implant_boolean = False if any(((implant_term in mention) for implant_term in implant_dict)): implant_boolean = True keywords = set() lemma = ' '.join([w.lower() for w in c.complication.get_attrib_tokens('lemmas') if w.stri...
class SoftBCEWithLogitsLoss(nn.Module): __constants__ = ['weight', 'pos_weight', 'reduction', 'ignore_index', 'smooth_factor'] def __init__(self, weight=None, ignore_index: Optional[int]=(- 100), reduction='mean', smooth_factor=None, pos_weight=None): super().__init__() self.ignore_index = ignor...
(frozen=True) class Table(): title: str header: List[HeaderCell] rows: List[List[Cell]] links: List[Hyperlink] = field(default_factory=list) name: Optional[str] = None description: Optional[str] = None
def check_precomputed_polar(a, side, expected_u, expected_p): (u, p) = polar(a, side=side) assert_allclose(u, expected_u, atol=1e-15) assert_allclose(p, expected_p, atol=1e-15)
class DeviceSession_V1_1(DeviceSession): def __init__(self, FNwkSIntKey=None, SNwkSIntKey=None, NwkSEncKey=None, **kwargs): super().__init__(**kwargs) self.FNwkSIntKey = FNwkSIntKey self.SNwkSIntKey = SNwkSIntKey self.NwkSEncKey = NwkSEncKey
def poly(): for i in x: v = x[i] ret = 0.0 guard = 0.2 if ((v < (- guard)) or (v > guard)): ret = (4 / ti.max(v, 0.1)) else: ret = 0 y[i] = ret
def distance2center(x1, y1, x2, y2, image): im_cx = int((image.shape[1] / 2)) im_cy = int((image.shape[0] / 2)) cx = ((x2 + x1) / 2).astype(int) cy = ((y2 + y1) / 2).astype(int) return math.sqrt((math.pow((im_cx - cx), 2) + math.pow((im_cy - cy), 2)))