code
stringlengths
101
5.91M
def entropy_loss(logits): min_prob = 1e-16 probs = F.softmax(logits, dim=(- 1)).clamp(min=min_prob) log_probs = probs.log() entropy = ((- probs) * log_probs) entropy_loss = (- entropy.mean()) return entropy_loss
def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0, tfirst=False): if (ml is None): ml = (- 1) if (mu is None): mu = (- 1) dt = n...
def test_online_boosting(): stream = SEAGenerator(1, noise_percentage=0.067, random_state=112) nb = NaiveBayes() learner = OnlineBoostingClassifier(base_estimator=nb, n_estimators=3, random_state=112) first = True cnt = 0 max_samples = 5000 predictions = [] wait_samples = 100 correct...
class NONLocalBlock3D(_NonLocalBlockND): def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True, return_sim=False): super(NONLocalBlock3D, self).__init__(in_channels, inter_channels=inter_channels, dimension=3, sub_sample=sub_sample, bn_layer=bn_layer, return_sim=return_sim)
def launch_mpi_driver(driver_path, args, config, partitions, m): workers = config.resource_info['worker'] _prepare_workers(workers, driver_path, args, partitions, (m is not None)) mpi_cmd = _get_mpi_cmd(config) parallax_log.warning(colored(('\n$ %s' % mpi_cmd), 'red')) proc = subprocess.Popen(args=m...
class SEDataset(Dataset): def __init__(self, clean_dir, noisy_dir, preemph, cache_dir='.', split='train', slice_size=(2 ** 14), stride=0.5, max_samples=None, do_cache=False, verbose=False, slice_workers=2, preemph_norm=False, random_scale=[1]): super(SEDataset, self).__init__() print('Creating {} sp...
def test_arrow_null_struct(): a = pyarrow.array([{'x': 1, 'y': 1.1}, None, {'x': 2, 'y': 2.2}, {'x': 3, 'y': 3.3}]) assert (to_list(ak._connect.pyarrow.handle_arrow(a)) == [{'x': 1, 'y': 1.1}, None, {'x': 2, 'y': 2.2}, {'x': 3, 'y': 3.3}])
def generate_bad(dims, reduce_dim, libname, reps=1): if os.path.exists(libname): return size = reduce((lambda x, y: (x * y)), dims.values()) reduce_size = dims[reduce_dim] dims_declaration = '\n'.join([('struct %s { enum { value = %d }; };' % (d, dims[d])) for d in dims]) temp_source = ('\n ...
_REGISTRY.register() class VideoRecurrentTestDataset(VideoTestDataset): def __init__(self, opt): super(VideoRecurrentTestDataset, self).__init__(opt) self.folders = sorted(list(set(self.data_info['folder']))) def __getitem__(self, index): folder = self.folders[index] if self.cach...
def plot_alignment_to_numpy(alignment, info=None): (fig, ax) = plt.subplots(figsize=(6, 4)) im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none') fig.colorbar(im, ax=ax) xlabel = 'Decoder timestep' if (info is not None): xlabel += ('\n\n' + info) plt.xlabel(xlabe...
def test_rdn(): scale = 4 model_cfg = dict(type='RDN', in_channels=3, out_channels=3, mid_channels=64, num_blocks=16, upscale_factor=scale) model = build_backbone(model_cfg) assert (model.__class__.__name__ == 'RDN') inputs = torch.rand(1, 3, 32, 16) targets = torch.rand(1, 3, 128, 64) loss_...
class Scorer(): __metaclass__ = ABCMeta def __init__(self, argument_string): self._reference = None self._arguments = {} if argument_string: argument_strings = argument_string.split(',') for a in argument_strings: (argument, value) = a.split('=') ...
class WavLMConfig(PretrainedConfig): model_type = 'wavlm' def __init__(self, vocab_size=32, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout=0.1, activation_dropout=0.1, attention_dropout=0.1, feat_proj_dropout=0.0, final_dropout=0.1, layer...
class VisualGoalEncoder(nn.Module): def __init__(self, hidden_size: int, latent_goal_features: int, in_features: int, l2_normalize_goal_embeddings: bool, activation_function: str): super().__init__() self.l2_normalize_output = l2_normalize_goal_embeddings self.act_fn = getattr(nn, activation...
_operation def mtimes(a: torch.Tensor, b: torch.Tensor, conj_a=False, conj_b=False): if is_real(a): if (a.dim() >= b.dim()): raise ValueError('Incorrect dimensions.') return mtimes_real_complex(a, b, conj_b=conj_b) if is_real(b): if (b.dim() >= a.dim()): raise Val...
class NFM(BaseModel): def __init__(self, linear_feature_columns, dnn_feature_columns, dnn_hidden_units=(128, 128), l2_reg_embedding=1e-05, l2_reg_linear=1e-05, l2_reg_dnn=0, init_std=0.0001, seed=1024, bi_dropout=0, dnn_dropout=0, dnn_activation='relu', task='binary', device='cpu'): super(NFM, self).__init_...
class DownsamplerBlock(nn.Module): def __init__(self, ninput, noutput): super().__init__() self.conv = nn.Conv2d(ninput, (noutput - ninput), (3, 3), stride=2, padding=1, bias=True) self.pool = nn.MaxPool2d(2, stride=2) self.bn = nn.BatchNorm2d(noutput, eps=0.001) def forward(self...
def main(): parser = ArgumentParser() parser.add_argument('--train_corpus', type=Path, required=True) parser.add_argument('--output_dir', type=Path, required=True) parser.add_argument('--bert_model', type=str, required=True, choices=['bert-base-uncased', 'bert-large-uncased', 'bert-base-cased', 'bert-ba...
class WarmupSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): def __init__(self, learnrate, warmup_steps): super().__init__() self.learnrate = learnrate self.warmup_steps = warmup_steps def __call__(self, step): arg1 = self.learnrate arg2 = ((step * self.learn...
class KeyCheckerDict(): def __init__(self, children): self.children = children def __getitem__(self, key): return self.children[key] def __setitem__(self, key, value): self.children[key] = value def verify(self, obj): for (k, v) in self.children.items(): self....
class MLQALanguage(): def __init__(self, articles_regex_pattern: Optional[re.Pattern]=None): self.articles_regex_pattern = articles_regex_pattern def tokenize(self, text: str): return whitespace_tokenize(text) def from_code(cls, code: str): code_to_language = {'en': English, 'es': Sp...
class AutoProphet(ICAutoMLForecaster, SeasonalityLayer): config_class = AutoProphetConfig def supports_exog(self): return True def generate_theta(self, train_data: TimeSeries) -> Iterator: seas = list(super().generate_theta(train_data)) modes = ['additive', 'multiplicative'] ...
def traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[Type[nn.Module]]=(), full: bool=False) -> Iterator[Tuple[(nn.Module, str, nn.Module)]]: if (prefix is None): prefix = type(module).__name__ for (name, sub_module) in module.named_children(): scope =...
def _iterator_size(size, length=None, alphabet=None): if alphabet: min_p = min(alphabet) max_p = max(alphabet) for alpha in IntegerListsLex(size, length=length, min_part=1, max_part=min(size, sum(alphabet))): for p in product(*[IntegerListsLex(a, min_slope=1, min_part=min_p, max_...
def get_path(g, src, dst): try: path = nx.shortest_path(g, src, dst) except NetworkXNoPath: try: if verbose: print('Warning: trying inverse path.') path = nx.shortest_path(g, dst, src) except NetworkXNoPath: return NO_PATH labeled_p...
class Timer(): def __init__(self): self.start = time.process_time() def reset(self): self.start = time.process_time() def elapsed(self): return (time.process_time() - self.start)
def apply_mutation(base_seq, mut_pos, mut_res, op_type, tokenizer): tokens = tokenizer.decode(tokenizer.encode(base_seq)).split(' ')[1:(- 1)] if (op_type == 'sub'): mut_seq = ''.join(((tokens[:mut_pos] + [mut_res]) + tokens[(mut_pos + 1):])) elif (op_type == 'ins'): mut_seq = ''.join(((token...
def load_model(config, num_train_steps, label_list, pretrain=None): device = torch.device('cuda') n_gpu = torch.cuda.device_count() if pretrain: model = BertMRCNER_CLUSTER(config) pretrained_dict = torch.load((pretrain + 'bert_finetune_model.bin')) model_dict = model.state_dict() ...
def calc_total_sphere_msd(initial_location, initial_rot_matrix, location, rot_matrix): dx = (np.array(location) - np.array(initial_location)) u_hat = np.zeros(3) for i in range(3): e = np.zeros(3) e[i] = 1.0 u_hat += (0.5 * np.cross(np.inner(initial_rot_matrix, e), np.inner(rot_matri...
class Model(object): def __init__(self, mode, x_input): self.mode = mode self.x_input = x_input self._build_model() def add_internal_summaries(self): pass def _stride_arr(self, stride): return [1, stride, stride, 1] def _build_model(self): assert ((self.mo...
class QDQBertModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class FaceDataset(Dataset): def __init__(self, istraining=True, args=None, transform=None): self.transform = transform self.istraining = istraining self.args = args self.metas = [] if istraining: with open(args.train_list) as f: lines = f.readlines...
class MBInvertedConvLayer(BasicUnit): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, expand_ratio=6): super(MBInvertedConvLayer, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride...
def rot_y(beta): return torch.tensor([[cos(beta), 0, sin(beta)], [0, 1, 0], [(- sin(beta)), 0, cos(beta)]], dtype=beta.dtype)
def _get_uplift_curve(y_treatment: np.ndarray, y_control: np.ndarray, n_treatment: np.ndarray, n_control: np.ndarray, mode: str): assert (mode in _available_uplift_modes), "Mode isn't available" if (mode == 'qini'): curve_values = ((y_treatment / n_treatment[(- 1)]) - (y_control / n_control[(- 1)])) ...
def qiskit_info_original(file_name, new_file_name): original_circ = QuantumCircuit.from_qasm_file(file_name) original_depth = original_circ.depth() original_gate_count = original_circ.count_ops() print('depth =', original_depth) print('gate count =', original_gate_count) with open((new_file_name...
def create_AP_plot(axis, data_to_plot, accept_classes, max_depth): if ('AP_per_depth' not in data_to_plot): raise ValueError() axis.set_title('AP per depth') axis.set_ylim([0, 1.01]) axis.set_ylabel('AP') for label in accept_classes: aps = data_to_plot['AP_per_depth'][label] ...
def register_model_metadata_from_path(path: str) -> None: with open(path, 'r') as f: raw = yaml.safe_load(f) model_metadata_list = dacite.from_dict(ModelMetadataList, raw) for model_metadata in model_metadata_list.models: register_model_metadata(model_metadata)
class GAEASearchTrial(PyTorchTrial): def __init__(self, trial_context: PyTorchTrialContext) -> None: self.context = trial_context self.hparams = AttrDict(trial_context.get_hparams()) self.last_epoch = 0 self.download_directory = self.download_data_from_s3() dataset_hypers = {...
(scope='module') def comments_tree() -> astroid.Module: module = importlib.import_module('tests.fixtures.cluster.comments') return astroid.parse(inspect.getsource(module), path='comments.py')
class ContinuedFraction_infinite(ContinuedFraction_base): def __init__(self, w, value=None, check=True): ContinuedFraction_base.__init__(self) self._w = w if check: for i in range(10): k = w[i] if (not isinstance(k, Integer)): t...
def louvain_animation(adj_matrix, frames, dark=False, duration=15, filename=None, dpi=None, seed=2): anim = Animation(adj_matrix, frames, seed, dark) return anim.show(duration, filename, dpi)
def save_quiver_data(n, up_to=True, types='ClassicalExceptional', verbose=True): from sage.combinat.cluster_algebra_quiver.mutation_type import load_data if (up_to is True): ranks = range(1, (n + 1)) elif (up_to is False): ranks = [n] for i in ranks: _save_data_dig6(i, types=type...
def cached_tally_directory(directory, size=10000, cachedir=None, seed=1): filename = ('%s_segtally_%d.npy' % (directory, size)) if (seed != 1): filename = ('%d_%s' % (seed, filename)) if (cachedir is not None): filename = os.path.join(cachedir, filename.replace('/', '_')) if (os.path.isf...
def mlp_block(x: tf.Tensor, filters: int, name: str) -> tf.Tensor: x = layers.Dense(filters, name=f'{name}_dense')(x) x = layers.BatchNormalization(momentum=0.0, name=f'{name}_batch_norm')(x) return layers.Activation('relu', name=f'{name}_relu')(x)
class LukeConfig(PretrainedConfig): model_type = 'luke' def __init__(self, vocab_size=50267, entity_vocab_size=500000, hidden_size=768, entity_emb_size=256, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_pos...
def fc_prune(model, blob_in, blob_out, dim_in, dim_out, weight_init=None, bias_init=None, mask_init=None, threshold=1e-05, need_compress_rate=False, comp_lb=0.05, **kwargs): weight_init = (weight_init if weight_init else ('XavierFill', {})) bias_init = (bias_init if bias_init else ('ConstantFill', {})) mask...
() ('--num_epochs', default=1000) ('--num_train_tasks', default=10) ('--num_test_tasks', default=5) ('--encoder_hidden_size', default=200) ('--net_size', default=300) ('--num_steps_per_epoch', default=4000) ('--num_initial_steps', default=4000) ('--num_steps_prior', default=750) ('--num_extra_rl_steps_posterior', defau...
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[(int, float, str, bool)]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[(Tuple[(float, float)], float)]]=None, init_gain: float=0, fan_mode: str='fan_in', init_non...
def get_profiling_event(postfix, profiler): event_list = (profiler.events() if isinstance(profiler, torch.profiler.profile) else profiler.function_events) return [event for event in event_list if event.name.endswith(postfix)]
('data.dsprites', 'class') class DSpritesData(base.ImageTfdsData): def __init__(self, predicted_attribute, num_classes=None, data_dir=None): dataset_builder = tfds.builder('dsprites:2.*.*', data_dir=data_dir) dataset_builder.download_and_prepare() info = dataset_builder.info if (pred...
class NewT5HFLoader(HFLoader): def __init__(self, hf_transformers_model_class=T5ForConditionalGeneration): super().__init__(hf_transformers_model_class=hf_transformers_model_class) def substitue_state_dict_keys_back_to_original(self, training_state_dict): d = dict() for (k, v) in trainin...
class ContTransformerChain(nn.Module): def __init__(self, x, tfms): super().__init__() self.tfms = [] for tf in tfms: itf = tf(x) x = itf.forward(x) self.tfms += [itf] def forward(self, x): for tf in self.tfms: x = tf.forward(x) ...
class LRFinder(Callback): def __init__(self, start_lr=1e-06, end_lr=10): super(LRFinder, self).__init__() (self.start_lr, self.end_lr) = (start_lr, end_lr) self.stop = False self.best_loss = 0.0 self.best_lr = None self.loss_history = [] self.smooth_value = Sm...
def data_load_and_process(dataset, classes=[0, 1], feature_reduction='resize256', binary=True): if (dataset == 'fashion_mnist'): ((x_train, y_train), (x_test, y_test)) = tf.keras.datasets.fashion_mnist.load_data() elif (dataset == 'mnist'): ((x_train, y_train), (x_test, y_test)) = tf.keras.datas...
def log_sinkhorn(x: _Array, steps: int, temperature: float, zero_diagonal: bool, noise_rng_key: Optional[_Array]) -> _Array: assert (x.ndim >= 2) assert (x.shape[(- 1)] == x.shape[(- 2)]) if (noise_rng_key is not None): noise = (- jnp.log(((- jnp.log((jax.random.uniform(noise_rng_key, x.shape) + 1e-...
def load_tokenizer(mode: str, vocab_file: str=None, vocab_list: List[str]=None, slots_file: str=None) -> Tokenizer: assert ((int((vocab_file is not None)) + int((vocab_list is not None))) <= 1), "For 'vocab_file' and 'vocab_list', at most one argument can be presented" with tempfile.NamedTemporaryFile('w') as f...
def generate_webpage(prefix, regex, perrow=1, perpage=None, verbose=False): filenames = [] regex_list = regex.split('|') for regex_single in regex_list: filenames.extend(glob(os.path.join(prefix, regex_single))) filenames.sort() if verbose: print('find {} files'.format(len(filenames)...
.parametrize('knn_methods', knn_methods) def test_ola(knn_methods): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() ola = OLA(pool_classifiers, knn_classifier=knn_methods) ola.fit(X_dsel, y_dsel) assert np.isclose(ola.score(X_test, y_test), 0.)
class SPEDDataset(Dataset): def __init__(self, input_transform=None): self.input_transform = input_transform self.dbImages = np.load((GT_ROOT + 'SPED/SPED_dbImages.npy')) self.qImages = np.load((GT_ROOT + 'SPED/SPED_qImages.npy')) self.ground_truth = np.load((GT_ROOT + 'SPED/SPED_gt....
class Pretrain(Dataset): def __init__(self, dataset, tokenizer, type_path, input_length, output_length, args): self.args = args self.tokenizer = tokenizer self.type_path = type_path self.category = None self.whole_dataset = dataset self.dataset_name = dataset ...
def test_getitem(): with pytest.raises(IndexError): empty[(0,)] jagged = ak.highlevel.Array([[]])[0:0] assert (empty[jagged].to_list() == [])
class QDQBertLMHeadModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class SqueezeBertModule(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def merge_dicts(dicts_in): dict_out = {} for k in dicts_in[0].keys(): dict_out[k] = [] for d in dicts_in: dict_out[k].append(d[k]) dict_out[k] = np.array(dict_out[k]) return dict_out
def update_density(pos: ti.types.ndarray(ndim=1), den: ti.types.ndarray(ndim=1), pre: ti.types.ndarray(ndim=1)): for i in range(particle_num): den[i] = 0.0 for j in range(particle_num): R = (pos[i] - pos[j]) den[i] += (mass * W(R, h)) pre[i] = (pressure_scale * max((p...
def main(args): global_exp_name = args.exp_name search_space_config = json.load(open(args.search_space_file)) hyperparam_space = {k: eval(v['type'])(k, **v['options']) for (k, v) in search_space_config.items()} for i in range(args.num_searches): new_env = os.environ.copy() hyperparam_val...
def get_fixed_dict_and_times_single(exp_fn, checkpoints_eval_fn, checkpoint_every_x_epochs=1, epochs_in_last_checkpoint=None, time_units='hours', subkey=None): times_list = extract_cumsum_train_times(load_experiment(exp_fn), time_units=time_units) checkpoints_dict = extract_values(parse_all_eval_results_dict(ch...
class TestResize(): def setup_method(self): self.width = 16 self.height = 16 self.env = DummyDiscrete2DEnv() self.env_r = Resize(DummyDiscrete2DEnv(), width=self.width, height=self.height) def teardown_method(self): self.env.close() self.env_r.close() def test...
def createResolutionCallbackFromEnv(lookup_base): def lookupInModule(qualified_name, module): if ('.' in qualified_name): parts = qualified_name.split('.') base = parts[0] remaining_pieces = '.'.join(parts[1:]) module_value = getattr(module, base) ...
def test_hdbscan_all_points_membership_vectors(): clusterer = HDBSCAN(prediction_data=True, min_cluster_size=200).fit(X) vects = all_points_membership_vectors(clusterer) assert_array_equal(vects, np.zeros(clusterer.prediction_data_.raw_data.shape[0]))
class Group(Storage): GroupT = T.TypeVar('GroupT', bound='Group') def identity(cls: T.Type[GroupT]) -> GroupT: raise NotImplementedError() def compose(self: GroupT, other: GroupT) -> GroupT: raise NotImplementedError() def inverse(self: GroupT) -> GroupT: raise NotImplementedErro...
class HTML(): def __init__(self, web_dir, title, refresh=0): self.title = title self.web_dir = web_dir self.img_dir = os.path.join(self.web_dir, 'images') if (not os.path.exists(self.web_dir)): os.makedirs(self.web_dir) if (not os.path.exists(self.img_dir)): ...
def cli_main(): parser = options.get_generation_parser(interactive=True) args = options.parse_args_and_arch(parser) main(args)
class GomiDiff(nn.Module): def __init__(self, in_channels: int, residual_layers: int, residual_channels: int, dilation_cycle_length: int, num_diffusion_steps: int): super().__init__() self.dilation_cycle_length = dilation_cycle_length self.num_diffusion_steps = num_diffusion_steps se...
def main(): args = parser.parse_args() print(('JAX host: %d / %d' % (jax.host_id(), jax.host_count()))) print(('JAX devices:\n%s' % '\n'.join((str(d) for d in jax.devices()))), flush=True) if (get_model_cfg(args.model) is not None): validate(args) else: models = list_models(pretraine...
class DICE(nn.Module): def __init__(self, channel_in, channel_out, height, width, kernel_size=3, dilation=[1, 1, 1], shuffle=True): super().__init__() assert (len(dilation) == 3) padding_1 = (int(((kernel_size - 1) / 2)) * dilation[0]) padding_2 = (int(((kernel_size - 1) / 2)) * dila...
def test_categoricals_are_not_preprocessed(): data = pd.DataFrame(data={'age': [56, 61, 36, 52, 42], 'therapy': [True, False, True, False, True], 'alcohol': ['medium', 'medium', 'low', 'high', 'low']}) metadata = SingleTableMetadata.load_from_dict({'columns': {'age': {'sdtype': 'numerical'}, 'therapy': {'sdtype...
class _FSMTapeCacheDetectAll_(_FSMTapeCache_): def compare_to_tape(self, track_number, word): track_cache = self.cache[track_number] it_word = iter(word) for _ in track_cache: next(it_word) for _ in it_word: (successful, _) = self.read(track_number) ...
def save_args(filename, args): args_dict = {} for (key, value) in vars(args).items(): if isinstance(value, pathlib.Path): args_dict[key] = str(value) else: args_dict[key] = value save_json(filename, args_dict)
class DogsCatsSD(DataInterface): def __init__(self, validation_fraction=(1 / 5), **kwargs): super().__init__(**kwargs) self.validation_fraction = validation_fraction def shard_descriptor(self): return self._shard_descriptor _descriptor.setter def shard_descriptor(self, shard_desc...
def print_network(net): num_params = 0 for param in net.parameters(): num_params += param.numel() print(('Total number of parameters: %d' % num_params))
class UtteranceBuilder(BaseUtteranceBuilder): def scene_to_sent(self, variables, vocab): sent_ids = variables.data.cpu().numpy() sent_words = [vocab.to_word(x) for x in sent_ids] title = 'KB SCENARIO:' book = ' Book count: {}, value: {}'.format(sent_words[0], sent_words[1]) ...
def _dump_loader_info(loader): (yield ('class: %s.%s' % (type(loader).__module__, type(loader).__name__))) for (key, value) in sorted(loader.__dict__.items()): if key.startswith('_'): continue if isinstance(value, (tuple, list)): if (not all((isinstance(x, (str, text_type...
class PairedData(object): def __init__(self, data_loader_A, data_loader_B, max_dataset_size, flip): self.data_loader_A = data_loader_A self.data_loader_B = data_loader_B self.stop_A = False self.stop_B = False self.max_dataset_size = max_dataset_size self.flip = flip ...
class MahalanobisDistance(NumpyArrayMetric): def __init__(self, metric: str='MAHLNBS'): super().__init__(metric) def calculate(self): gt_n = np.count_nonzero(self.reference) seg_n = np.count_nonzero(self.prediction) if (gt_n == 0): warnings.warn('Unable to compute Mah...
def _gen_qubit_mapping(circuit: QuantumCircuit) -> dict: dic = {} try: from qiskit.transpiler.layout import TranspileLayout if isinstance(circuit._layout, TranspileLayout): layout = circuit._layout.initial_layout else: layout = circuit._layout bit_location...
def _Constant(t, symbols, inferred_symbols): if isinstance(t.value, (str, bytes)): return dtypes.pointer(dtypes.int8) return dtypes.result_type_of(dtypes.typeclass(type(t.value)), dtypes.typeclass(np.min_scalar_type(t.value).name))
def _morphological_process(image, kernel_size=5): if (len(image.shape) == 3): raise ValueError('Binary segmentation result image should be a single channel image') if (image.dtype is not np.uint8): image = np.array(image, np.uint8) kernel = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ...
class Examples(SegmentationBase): def __init__(self, size=256, random_crop=False, interpolation='bicubic'): super().__init__(data_csv='data/coco_examples.txt', data_root='data/coco_images', segmentation_root='data/coco_segmentations', size=size, random_crop=random_crop, interpolation=interpolation, n_labels...
def apply_learned_embed_in_clip(learned_embeds, text_encoder, tokenizer, token: Optional[Union[(str, List[str])]]=None, idempotent=False): if isinstance(token, str): trained_tokens = [token] elif isinstance(token, list): assert (len(learned_embeds.keys()) == len(token)), 'The number of tokens an...
def _read_signal(sim, signal_name): signal_name = _find_signal(sim, signal_name) return sim.io[signal_name]
def start_server(): daemon = Pyro4.Daemon(config.SPACEMOUSE_HOSTNAME) ns = Pyro4.locateNS() uri = daemon.register(DeviceState) ns.register('example.greeting', uri) print('uri:', uri) print('Server ready.') daemon.requestLoop()
def get_test_runner(project_module): __import__(project_module) test = sys.modules[project_module].test version = sys.modules[project_module].__version__ mod_path = sys.modules[project_module].__file__ mod_path = os.path.abspath(os.path.join(os.path.dirname(mod_path))) return (test, version, mod...
def _color_from_level(level): if (level == PrettyPrintLevel.INFO): return '92' if (level == PrettyPrintLevel.WARNING): return '93' if (level == PrettyPrintLevel.ERROR): return '91' if (level == PrettyPrintLevel.SUCCESS): return '92' else: raise ValueError(('Un...
def validate_string(property_name, var, string_list=None, case_sensitive=False): if isinstance(var, str): if (string_list is None): return var if (not case_sensitive): test_var = var.casefold() def fold_input(input_variable): if isinstance(input_va...
def _seg_33(): return [(13070, 'M', u''), (13071, 'M', u''), (13072, 'M', u''), (13073, 'M', u''), (13074, 'M', u''), (13075, 'M', u''), (13076, 'M', u''), (13077, 'M', u''), (13078, 'M', u''), (13079, 'M', u''), (13080, 'M', u''), (13081, 'M', u''), (13082, 'M', u''), (13083, 'M', u''), (13084, 'M', u''), (13085, ...
def get_dict(name, clear=False, **kwargs): return get_mpdict_value('dict', ('d_' + name), clear=clear)
def main(): top_females = read_collection.aggregate(top_sources_by_gender(args, field='sourcesFemale')) top_males = read_collection.aggregate(top_sources_by_gender(args, field='sourcesMale')) delete_existing_docs(write_collection) update_db(write_collection, top_females) update_db(write_collection, ...
_level_function() def almost_equal(left, right, *, rtol: float=1e-05, atol: float=1e-08, dtype_exact: bool=True, check_parameters: bool=True, check_regular: bool=True): (yield (left, right)) left_behavior = behavior_of(left) right_behavior = behavior_of(right) left_backend = backend_of_obj(left, default...