code
stringlengths
101
5.91M
def log_t(u, t): def _internal_log_t(u, t): return (((u ** (1.0 - t)) - 1.0) / (1.0 - t)) return tf.cond(tf.equal(t, 1.0), (lambda : tf.math.log(u)), functools.partial(_internal_log_t, u, t))
def test_get_constant_for(pool): pool.add_constant(42) assert (pool.get_constant_for(int) == 42)
.lower_builtin('real', ArrayBuilderType, numba.types.Integer) .lower_builtin('real', ArrayBuilderType, numba.types.Float) def lower_real(context, builder, sig, args): (arraybuildertype, xtype) = sig.args (arraybuilderval, xval) = args proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)...
class AttentionGRUEncoder(GRUEncoder): def __init__(self, n_layers, n_vocab, n_genre, pretrained_w2v, is_update_w2v, dropout, genre_units=5): super(AttentionGRUEncoder, self).__init__(n_layers=n_layers, n_vocab=n_vocab, n_genre=n_genre, pretrained_w2v=pretrained_w2v, is_update_w2v=is_update_w2v, dropout=dro...
def main(): style = {'border': {'color': 'red', 'linewidth': 0.5}} (world, reward, terminal) = setup_mdp() ax = plt.figure(num='Original Reward').add_subplot(111) P.plot_state_values(ax, world, reward, **style) plt.draw() (trajectories, expert_policy) = generate_trajectories(world, reward, termi...
def polish(): output_dir = 'data' KLEJ = ' path = (lambda p: os.path.join(output_dir, p)) get_data(KLEJ.format('klej_nkjp-ner'), path('KLEJ/NKJP-NER'), 'NKJP-NER') get_data(KLEJ.format('klej_cdsc-e'), path('KLEJ/CDSC-E'), 'CDSC-E') get_data(KLEJ.format('klej_cdsc-r'), path('KLEJ/CDSC-R'), 'CDSC-...
class Manifolds(Category_over_base_ring): def __init__(self, base, name=None): if (base not in Fields().Topological()): raise ValueError('base must be a topological field') Category_over_base_ring.__init__(self, base, name) _method def super_categories(self): return [Sets...
class NeuralOptimizer1(BaseCustomOptimizer): def __init__(self, beta1=0.9, decrease_factor=0.1, **kwargs): super(NeuralOptimizer1, self).__init__(**kwargs) self._beta1 = beta1 self._decrease_factor = decrease_factor def _prepare(self): super(NeuralOptimizer1, self)._prepare() ...
def test_module_field_field(static_module_field_mock): ref = vr.StaticModuleFieldReference(static_module_field_mock) assert (ref.field == static_module_field_mock)
def test_dict(capture, doc): d = m.get_dict() assert (d == {'key': 'value'}) with capture: d['key2'] = 'value2' m.print_dict(d) assert (capture.unordered == '\n key: key, value=value\n key: key2, value=value2\n ') assert (doc(m.get_dict) == 'get_dict() -> dict') ...
(scope='module') def df_null_headers() -> pd.DataFrame: df = pd.DataFrame({'': [], np.nan: ['How Google Works'], None: ['Eric Schmidt, Jonathan Rosenberg'], 'N/A': [2014]}) return df
def cora_pandas_parts(include_nodes): if include_nodes: nodes = pd.read_csv(cora_content_path, header=None, sep='\t', index_col=0, usecols=range(0, (1433 + 1)), dtype=cora_dtypes, na_filter=False) else: nodes = None edges = pd.read_csv(cora_cites_path, header=None, sep='\t', names=['source',...
_function_api('dummy') def dummy_parametric_function(shape, f=10, i=1, s='dummy', fix_parameters=False): from nnabla import Variable from nnabla.parameter import get_parameter_or_create from nnabla.initializer import UniformInitializer p1 = get_parameter_or_create('p1', shape, UniformInitializer(((- 1),...
def print_final_metrics(metrics: TrackingMetrics) -> None: print('\n### Final results ###') metric_names = metrics.label_metrics.keys() print('\nPer-class results:') print('\t\t', end='') print('\t'.join([m.upper() for m in metric_names])) class_names = metrics.class_names max_name_length = ...
def main(): exit_success = 0 exit_failure = 1 cargs = parse_cmdline() if cargs.version: print(('afl-cov-' + __version__)) return exit_success if (cargs.gcov_check or cargs.gcov_check_bin): if is_gcov_enabled(cargs): return exit_success else: re...
def get_shape_nodedict(finaltree, prefix, nodedict): nodename = prefix nodeval = finaltree['id'] nodedict[nodeval] = nodename treeshape = [nodename] if ('children' in finaltree): for childid in range(len(finaltree['children'])): (childshape, nodedict) = get_shape_nodedict(finaltr...
def test_TaskSystem_Pickler(): from returnn.util.task_system import Pickler from io import BytesIO stream = BytesIO() pickler = Pickler(stream) obj = {'foo': 'bar'} pickler.dump(obj)
def construct_raw_transaction(sender, recipient, nonce, amount, data): tx = {'nonce': nonce, 'from': sender, 'to': recipient, 'value': Web3.toWei(amount, 'ether'), 'gas': 2000000, 'chainId': 10, 'gasPrice': Web3.toWei('50', 'gwei'), 'data': data} return tx
def tetrad_graph_to_pcalg(g): endpoint_map = {'NULL': 0, 'CIRCLE': 1, 'ARROW': 2, 'TAIL': 3} nodes = g.getNodes() p = g.getNumNodes() A = np.zeros((p, p), dtype=int) for edge in g.getEdges(): i = nodes.indexOf(edge.getNode1()) j = nodes.indexOf(edge.getNode2()) A[j][i] = endp...
class TestCaseToAstVisitor(TestCaseVisitor): def __init__(self, module_aliases: ns.NamingScope, common_modules: set[str], exec_result: (ex.ExecutionResult | None)=None) -> None: self._module_aliases: ns.NamingScope = module_aliases self._common_modules: set[str] = common_modules self._exec_r...
def loss_calc_(y_true, y_pred, gain_type, sigma, N, device): rank_df = pd.DataFrame({'y': y_true, 'doc': np.arange(y_true.shape[0])}) rank_df = rank_df.sort_values('y').reset_index(drop=True) rank_order = (rank_df.sort_values('doc').index.values + 1) pos_pairs_score_diff = (1.0 + torch.exp(((- sigma) * ...
def get_supported(version=None, platform=None, impl=None, abi=None): supported = [] python_version = None if (version is not None): python_version = _get_python_version(version) interpreter = _get_custom_interpreter(impl, version) abis = None if (abi is not None): abis = [abi] ...
def download_glove(data_dir_path=None): if (data_dir_path is None): data_dir_path = 'very_large_data' glove_model_path = (((data_dir_path + '/glove.6B.') + str(GLOVE_EMBEDDING_SIZE)) + 'd.txt') if (not os.path.exists(glove_model_path)): glove_zip = (data_dir_path + '/glove.6B.zip') i...
def main(args): print('Loading models...') TOKENIZER_GPT2 = load_tokenizer_for_causal_lm('gpt2') MODEL_GPT2 = load_model_for_causal_lm('gpt2', device) MODEL_GPT2_XL = load_model_for_causal_lm('gpt2-xl', device) print('GPT2 and GPT2-XL models loaded!') seq_len = 256 top_k = 40 num_batches...
class NeuralNet(): def __init__(self, game): pass def train(self, examples): pass def predict(self, board): pass def save_checkpoint(self, folder, filename): pass def load_checkpoint(self, folder, filename): pass
def get_bootstrap_dataset_config() -> CN: _C = CN() _C.DATASET = '' _C.RATIO = 0.1 _C.IMAGE_LOADER = CN(new_allowed=True) _C.IMAGE_LOADER.TYPE = '' _C.IMAGE_LOADER.BATCH_SIZE = 4 _C.IMAGE_LOADER.NUM_WORKERS = 4 _C.IMAGE_LOADER.CATEGORIES = [] _C.IMAGE_LOADER.MAX_COUNT_PER_CATEGORY = ...
class CBNet(CBNetBase): def __init__(self, subnet, cb_inplanes, cb_zero_init=True, cb_del_stages=0, cb_num_modules=2, **kwargs): super(CBNet, self).__init__() self.cb_zero_init = cb_zero_init self.cb_del_stages = cb_del_stages self.cb_num_modules = cb_num_modules assert (cb_n...
def get_minified_adata_scrna(adata: AnnData, minified_data_type: MinifiedDataType) -> AnnData: if (minified_data_type != ADATA_MINIFY_TYPE.LATENT_POSTERIOR): raise NotImplementedError(f'Unknown MinifiedDataType: {minified_data_type}') all_zeros = csr_matrix(adata.X.shape) layers = {layer: all_zeros....
class ContentChecker(object): def feed(self, block): return def is_valid(self): return True def report(self, reporter, template): return
def configure_pipeline(cfg: DictConfig) -> Pipeline: if (cfg.model == 'flat'): classifier = configure_flat[cfg.classifier] classifier.set_params(**delete_non_hyperparameters(cfg)) else: local_classifier = configure_flat[cfg.classifier] local_classifier.set_params(**delete_non_hyp...
def save_checkpoint(args, state, is_best, filename='checkpoint.pth.tar'): savedir = args.snapshot_dir if (not os.path.exists(savedir)): os.makedirs(savedir) savepath = os.path.join(savedir, filename) torch.save(state, savepath) if is_best: shutil.copyfile(savepath, os.path.join(saved...
def item_frequency(data_tr, power): item_counts = {} item_population = set([]) for (u, i, _) in data_tr: item_counts[i] = (1 if (i not in item_counts) else (item_counts[i] + 1)) item_population.add(i) item_population = list(item_population) counts = [item_counts[v] for v in item_popu...
def main_train(): os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' os.environ['CUDA_VISIBLE_DEVICES'] = GPU config = tf.ConfigProto(allow_soft_placement=True) sess = tf.Session(config=config) x1 = tf.placeholder(tf.float32, [BATCH_SIZE, HEIGHT, WIDTH, CHANNEL]) x2 = tf.placeholder(tf.float32, [BATCH_SIZ...
def test_persistDockerImage2(): designerUrl = (designerIp + '/dockerimage') headers = {'Content-Type': 'application/json'} r = requests.post(designerUrl, data=json.dumps(data.test201), headers=headers) assert (r.status_code == 200)
def exec_bfs_compact(G, workers, calcUntilLayer): futures = {} degreeList = {} t0 = time() vertices = G.keys() parts = workers chunks = partition(vertices, parts) logging.info('Capturing larger degree...') maxDegree = 0 for v in vertices: if (len(G[v]) > maxDegree): ...
def test_reshape_behavior(): xp = _NumPyAPIWrapper() X = xp.asarray([[1, 2, 3], [3, 4, 5]]) X_no_copy = xp.reshape(X, ((- 1),), copy=False) assert (X_no_copy.base is X) X_copy = xp.reshape(X, (6, 1), copy=True) assert (X_copy.base is not X.base) with pytest.raises(TypeError, match='shape mus...
def prepare_hypothesis_settings(database: (str | None)=None, deadline: ((int | NotSet) | None)=None, derandomize: (bool | None)=None, max_examples: (int | None)=None, phases: (list[hypothesis.Phase] | None)=None, report_multiple_bugs: (bool | None)=None, suppress_health_check: (list[hypothesis.HealthCheck] | None)=None...
class PointPillar(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() def forward(self, batch_dict): for cur_module in self.module_list: ba...
class ElementWithLabel(): def __init__(self, element, label): self.element = element self.label = label def _latex_(self): return latex(self.label) def __str__(self): return str(self.label) def __repr__(self): return repr(self.label) def __hash__(self): ...
def dbladd(A: dace.float64[(1000, 1000)], B: dace.float64[(1000, 1000)]): dbl = B return (A + (dbl * B))
class Human(): def __init__(self, name: str, number: (int | float)) -> None: self._name = name self._number = number def __str__(self): return super().__str__() def get_name(self) -> str: return self._name def get_number(self) -> (int | float): return self._number...
def configure_output(options): output_screen = options.get('output_screen', True) output_log_name = options.get('output_log_name', None) output.set_output(filename=output_log_name, quiet=(not output_screen), combined=(output_screen and (output_log_name is not None)))
def test_enm_6(): SBP_enm = enm.Enm(fname, sparse=True) import mdtraj as md traj_mode = SBP_enm.get_mode_traj(6) traj_mode.save_pdb(('%s/enm_14.test.pdb' % outdir)) comp(('%s/enm_14.test.pdb' % refdir))
class FC(nn.Module): def __init__(self, in_features, out_features, NL='relu'): super(FC, self).__init__() self.fc = nn.Linear(in_features, out_features) if (NL == 'relu'): self.relu = nn.ReLU(inplace=True) elif (NL == 'prelu'): self.relu = nn.PReLU() e...
class onlyOn(object): def __init__(self, device_type): self.device_type = device_type def __call__(self, fn): (fn) def only_fn(slf, device, *args, **kwargs): if (self.device_type != slf.device_type): reason = 'Only runs on {0}'.format(self.device_type) ...
def trim_sigfig(x: float, n: int) -> float: assert (n == int(n)) magnitude = int(np.ceil(np.log10(np.abs(x)))) scale = (10 ** (magnitude - n)) return (np.round((x / scale)) * scale)
def test_maxpool_agg_constructor_1(): agg = MaxPoolingAggregator(output_dim=4, bias=True, act=(lambda x: (x + 1))) assert (agg.output_dim == 4) assert (agg.hidden_dim == 4) assert agg.has_bias assert (agg.act(2) == 3)
def test_crt(): assert (crt([0, 1, 2, 4], [2, 3, 4, 5]) == 34) assert (crt([3, 5], [6, 21]) is None)
def PbLe(args, k): _z3_check_cint_overflow(k, 'k') (ctx, sz, _args, _coeffs, args) = _pb_args_coeffs(args) return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
def eval_sl2z_word(w): mat = [Lm, Rm] w0 = Idm w1 = w return (w0 * prod(((mat[a[0]] ** a[1]) for a in w1), Idm))
.parametrize('checked', [True, False]) def test_write_label_html(checked): name = 'LogisticRegression' tool_tip = 'hello-world' with closing(StringIO()) as out: _write_label_html(out, name, tool_tip, checked=checked) html_label = out.getvalue() p = '<label for="sk-estimator-id-[0-9]*...
def write_json_to_file(json_object, json_file, mode='w', encoding='utf-8'): with open(json_file, mode, encoding=encoding) as outfile: json.dump(json_object, outfile, indent=4, sort_keys=True, ensure_ascii=False)
class DeploymentConfig(object): def __init__(self, num_clones=1, clone_on_cpu=False, replica_id=0, num_replicas=1, num_ps_tasks=0, worker_job_name='worker', ps_job_name='ps'): if (num_replicas > 1): if (num_ps_tasks < 1): raise ValueError('When using replicas num_ps_tasks must be...
.parametrize('data, lower_bound, upper_bound', [(np.geomspace(0.1, 1, 5), 5, 6), ((- np.geomspace(0.1, 1, 10)), 7, 8), (np.linspace(0, 1, 5), 0.9, 1.1), ([1, 2, 5, 10, 20, 50], 20, 40)]) def test_inverval_max_min_ratio(data, lower_bound, upper_bound): assert (lower_bound < _interval_max_min_ratio(data) < upper_boun...
def test_ListOffsetArray_RecordArray_NumpyArray(): v2a = ak.contents.listoffsetarray.ListOffsetArray(ak.index.Index(np.array([1, 4, 4, 6], np.int64)), ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([6.6, 1.1, 2.2, 3.3, 4.4, 5.5, 7.7]))], ['nest'])) resultv2 = v2a[np.array([1, 2]...
def rouge_l_sentence_level(evaluated_sentences, reference_sentences): if ((len(evaluated_sentences) <= 0) or (len(reference_sentences) <= 0)): raise ValueError('Collections must contain at least 1 sentence.') reference_words = _split_into_words(reference_sentences) evaluated_words = _split_into_word...
class SKLearnEmbedder(BaseEstimator): def __init__(self, embedder=None, pass_input_space=False): super(BaseEstimator, self).__init__() self.embedder = embedder self.pass_input_space = pass_input_space def fit(self, X, y): self.embedder.fit(X, y) def fit_transform(self, X, y):...
def test_batch_norm(): time_dim = Dim(Tensor('time', [batch_dim], dtype='int32')) in_dim = Dim(7, name='in') extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')}) class _Net(rf.Module): def __init__(self): super().__init__() se...
class VertexFeatureEmbedder(nn.Module): def __init__(self, num_vertices: int, feature_dim: int, embed_dim: int, train_features: bool=False): super(VertexFeatureEmbedder, self).__init__() if train_features: self.features = nn.Parameter(torch.Tensor(num_vertices, feature_dim)) else...
.parametrize('observation_shape', [(4, 84, 84)]) .parametrize('action_size', [2]) .parametrize('discrete_action', [False, True]) def test_pixel_encoder_factory(observation_shape: Sequence[int], action_size: int, discrete_action: bool) -> None: factory = PixelEncoderFactory() encoder = factory.create(observation...
class ForeignKeyConstraint(): imported_key_cascade = '0' imported_key_restrict = '1' imported_key_set_null = '2' imported_key_no_action = '3' def __init__(self, child: Table, name: str, delete_rule: str, update_rule: str): self.name = name.replace("'", '') self.delete_rule = delete_r...
def __setstate__(state): g = globals() for (k, v) in state.items(): g[('_sset_' + _state_vars[k])](k, g[k], v) return state
def infer_trainer_type(trainer_type): if (trainer_type == 'si'): return TrainerTypes.SILOG if (trainer_type == 'silog_chamfer'): return TrainerTypes.SILOG_CHAMFER
class LSQUnivariateSpline(UnivariateSpline): def __init__(self, x, y, t, w=None, bbox=([None] * 2), k=3, ext=0, check_finite=False): (x, y, w, bbox, self.ext) = self.validate_input(x, y, w, bbox, k, None, ext, check_finite) if (not np.all((diff(x) >= 0.0))): raise ValueError('x must be i...
class DechunkedInput(io.RawIOBase): def __init__(self, rfile): self._rfile = rfile self._done = False self._len = 0 def readable(self): return True def read_chunk_len(self): try: line = self._rfile.readline().decode('latin1') _len = int(line.st...
def test_constructor_statement_accept(test_case_mock, variable_reference_mock, constructor_mock): statement = stmt.ConstructorStatement(test_case_mock, constructor_mock) visitor = MagicMock(stmt.StatementVisitor) statement.accept(visitor) visitor.visit_constructor_statement.assert_called_once_with(state...
def _peel(G, A): Acomp = set(G) Acomp.difference_update(A) peeling = [] H = copy(G) H.delete_vertices(list(Acomp)) del Acomp while H: ui = next(H.vertex_iterator()) Vi = set(H) peeling.append((ui, Vi)) H.delete_vertices(H.neighbor_iterator(ui, closed=True)) ...
def create_summarized_columns_node(columns): count_dict = defaultdict(int) for (column_name, meta) in columns.items(): sdtype = ('other' if (meta['sdtype'] not in DEFAULT_SDTYPES) else meta['sdtype']) count_dict[sdtype] += 1 count_dict = dict(sorted(count_dict.items())) columns = ['Colum...
.parametrize('CurveDisplay, specific_params', [(ValidationCurveDisplay, {'param_name': 'max_depth', 'param_range': [1, 3, 5]}), (LearningCurveDisplay, {'train_sizes': [0.3, 0.6, 0.9]})]) def test_curve_display_negate_score(pyplot, data, CurveDisplay, specific_params): (X, y) = data estimator = DecisionTreeClass...
def plot_acc(model_dir): file_dir = os.path.join(model_dir, 'acc.csv') data = pd.read_csv(file_dir) epochs = data['epoch'].ravel() acc_train = data['acc_train'].ravel() acc_test = data['acc_test'].ravel() (fig, ax) = plt.subplots(1, 1, figsize=(7, 5), sharey=True, sharex=True, dpi=400) ax.pl...
def get_end_time(list_: List, is_sorted: bool=False, attr: str='time'): if (not list_): return 0 if is_sorted: return getattr(list_[(- 1)], attr) return max((getattr(item, attr) for item in list_))
class HasNUWPred(FunPred): sig = (WrappingBinaryOperator,) code = 'hasNUW' type_constraints = _none
class TensorFlowBenchmarkArguments(BenchmarkArguments): deprecated_args = ['no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process'] def __init__(self, **kwargs): for deprecated_arg in self.deprecated_args: if (deprecated_arg in kwargs): ...
def report_speed(outputs, speed_meters): total_time = 0 for key in outputs: if ('time' in key): total_time += outputs[key] speed_meters[key].update(outputs[key]) print(('%s: %.4f' % (key, speed_meters[key].avg))) speed_meters['total_time'].update(total_time) p...
def monkey_patch_RMSprop(RMSProp_class): def step(self, closure=None): loss = None if (closure is not None): loss = closure() effective_lrs = {} for group in self.param_groups: for p in group['params']: if (p.grad is None): ...
class FormanRicci(): def __init__(self, G: nx.Graph, weight='weight', method='augmented', verbose='ERROR'): self.G = G.copy() self.weight = weight self.method = method if (not nx.get_edge_attributes(self.G, self.weight)): logger.info('Edge weight not detected in graph, us...
def get_data(file): fin = open(file) for i in range(3): fin.readline() x = [] y = [] for line in fin.readlines(): line = line.strip().split(' ') if (len(line) < 3): break x.append(float(line[2])) line = line[3].split('[')[1].split(',')[0] y...
.corpus def test_speech_commands(): env = dotenv_values() corpus = SpeechCommandsV1(env['GSC1'], env['GSC1_TEST']) all_data = corpus.all_data classes = set([value['class_name'] for (key, value) in all_data.items()]) assert (len(classes) == 12), f'{classes}' (train, valid, test) = corpus.data_spl...
class RandomVerticalFlip(object): def __init__(self, prob: float=0.5): self.prob = prob def __call__(self, img, mask=None): if (mask is not None): if (random.random() < self.prob): return (img.transpose(Image.FLIP_TOP_BOTTOM), mask.transpose(Image.FLIP_TOP_BOTTOM)) ...
def input_user() -> str: try: user_utterance = input(((bcolors.OKCYAN + bcolors.BOLD) + 'User: ')) while (not user_utterance.strip()): user_utterance = input(((bcolors.OKCYAN + bcolors.BOLD) + 'User: ')) finally: print(bcolors.ENDC) return user_utterance
def get_qd_to_answer(data): key_to_answer = {} for datum in data['Data']: for page in (datum.get('EntityPages', []) + datum.get('SearchResults', [])): qd_tuple = get_question_doc_string(datum['QuestionId'], page['Filename']) key_to_answer[qd_tuple] = datum['Answer'] return ke...
def test_fetch(fetch_california_housing_fxt): data = fetch_california_housing_fxt() assert ((20640, 8) == data.data.shape) assert ((20640,) == data.target.shape) assert data.DESCR.startswith('.. _california_housing_dataset:') fetch_func = partial(fetch_california_housing_fxt) check_return_X_y(da...
class DatasetLoader(): supported_datasets = {'reddit': partial(Reddit, transform=Compose([RandomNodeSplit(num_val=0.1, num_test=0.15), FilterClassByCount(min_count=10000, remove_unlabeled=True)])), 'amazon': partial(Amazon, transform=Compose([RandomNodeSplit(num_val=0.1, num_test=0.15), FilterClassByCount(min_count...
def test(): j1 = ak.from_numpy(np.empty(0, np.int32)) assert (str(ak.Record({'d': j1}).type) == '{d: 0 * int32}')
def prologue_opt(args, OUTD_OPTMASKS, SHARED_OPT_MASKS): subs = ['learning', 'gifs', 'tmp', 'bin_masks', 'continuous_masks', 'final_masks'] for fd in subs: if (not os.path.exists(join(OUTD_OPTMASKS, fd))): os.makedirs(join(OUTD_OPTMASKS, fd)) if args.share_masks: msg = '{} is not...
class ScaledValuation_generic(DiscreteValuation): def __init__(self, parent, base_valuation, s): DiscreteValuation.__init__(self, parent) self._base_valuation = base_valuation self._scale = s def _repr_(self): return ('%r * %r' % (self._scale, self._base_valuation)) def resid...
class PrecoDocumentState(BaseDocumentState): def __init__(self, key): super().__init__(key) def final_process(self): all_mentions = flatten(self.clusters) self.sentence_map = get_sentence_map(self.segments, self.sentence_end) self.subtoken_map = flatten(self.segment_subtoken_map)...
def shap_explain(booster, datasource, dataset, summary_params, result_table='', is_pai=False, oss_dest=None, oss_ak=None, oss_sk=None, oss_endpoint=None, oss_bucket_name=None): tree_explainer = shap.TreeExplainer(booster) shap_values = tree_explainer.shap_values(dataset) if result_table: if is_pai: ...
def wrightomega_exp_error(x): exponential_approx = mpmath.exp(x) desired = mpmath_wrightomega(x) return (abs((exponential_approx - desired)) / desired)
class TFMPNetPreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def remove_leading_spaces(data): print('Removing leading spaces ...') for i in range(len(data)): for j in range(len(data[i])): data[i][j] = data[i][j].strip() return data
def fit_predict_selected(model, train_log, inf_log, user_features, queries): train_dataset = create_dataset(train_log, user_features=user_features) pred_dataset = create_dataset(inf_log, user_features=user_features) model.fit(train_dataset) return model.predict(dataset=pred_dataset, queries=queries, k=1...
def unpad_seqs(seqs, seq_lens): if isinstance(seq_lens, torch.LongTensor): seq_lens = seq_lens.cpu().tolist() return [seq[:seq_len] for (seq, seq_len) in zip(seqs.cpu().tolist(), seq_lens)]
class UpBottleneck(nn.Module): def __init__(self, in_places, places, stride=2, expansion=4, is_relu=True, p=0.01): super(UpBottleneck, self).__init__() mid_channels = (in_places // expansion) self.bottleneck = nn.Sequential(Conv1x1BNReLU(in_places, mid_channels, is_relu), TransposeConv3x3BNR...
.torch def test_item_id_feature_not_specified(small_dataset): schema = TensorSchemaBuilder().categorical('item_id', cardinality=6, is_seq=True, feature_source=TensorFeatureSource(FeatureSource.INTERACTIONS, 'item_id')).categorical('user_id', cardinality=6, is_seq=True, feature_source=TensorFeatureSource(FeatureSour...
def find_sage_dangling_links(app, env, node, contnode): debug_inf(app, ' find_sage_dangling_links ') reftype = node['reftype'] reftarget = node['reftarget'] try: doc = node['refdoc'] except KeyError: debug_inf(app, ('-- no refdoc in node %s' % node)) return None debug_inf...
class InstanceWhitening(nn.Module): def __init__(self, dim): super(InstanceWhitening, self).__init__() self.instance_standardization = nn.InstanceNorm2d(dim, affine=False) def forward(self, x): x = self.instance_standardization(x) w = x return (x, w)
class QuantumCliffordAlgebraGeneric(QuantumCliffordAlgebra): def __init__(self, n, k, q, F): psi = cartesian_product(([((- 1), 0, 1)] * n)) indices = [(tuple(p), tuple(w)) for p in psi for w in product(*[list(range(((4 - (2 * abs(p[i]))) * k))) for i in range(n)])] super().__init__(n, k, q, ...
class Lark(Serialize): def __init__(self, grammar, **options): self.options = LarkOptions(options) use_regex = self.options.regex if use_regex: if regex: re_module = regex else: raise ImportError('`regex` module must be installed if cal...
def assign_pyramid(roi, k0=4, size=224): roi_width = (roi[3] - roi[1]) roi_height = (roi[4] - roi[2]) return np.ceil((np.log2((np.sqrt(float((roi_width * roi_height))) / float(size))) + k0))