code
stringlengths
101
5.91M
class Function(with_metaclass(FunctionMeta, _C._FunctionBase, _ContextMethodMixin, _HookMixin)): __call__ = _C._FunctionBase._do_forward is_traceable = False def forward(ctx, *args, **kwargs): raise NotImplementedError def backward(ctx, *grad_outputs): raise NotImplementedError
def simulate_calibration_ref(n=1000, fixm=False, fixz=False, fixalign=False): logger.info('Generating calibration data with %s images from prior', 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 fix...
def parse_batch(batch, keys=None): keys = (keys or ['image', 'target']) assert isinstance(keys, list) outputs = {} if (not isinstance(batch, dict)): return batch if all((isinstance(v, dict) for v in batch.values())): for (k, v) in batch.items(): values = [v.get(key) for k...
class TestULP(object): def test_equal(self): x = np.random.randn(10) assert_array_max_ulp(x, x, maxulp=0) def test_single(self): x = np.ones(10).astype(np.float32) x += (0.01 * np.random.randn(10).astype(np.float32)) eps = np.finfo(np.float32).eps assert_array_max...
def get_learner_data(stage1_result_dir, pred_datatrack, use_cv_result, use_upper_lower, column_tag, k_cv=K_CV): df_vals = [] df_tests = [] for i_cv in range(k_cv): if use_cv_result: df_vals.append(pd.read_csv(((stage1_result_dir / str(i_cv)) / f'val.csv'), index_col=0)) df_te...
def run_sanity_check(cmd_args: Namespace, partitioner: PartitioningTask, analysis_config: AnalysisPipelineConfig, device='cpu', training=False, check_grads=True, ref_model=None, check_init=False): try: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False try: ...
class DLRep(ComposableProofStmt): verifier_cls = DLRepVerifier def __init__(self, lhs, expr, simulated=False): if isinstance(expr, Expression): self.bases = list(expr.bases) self.secret_vars = list(expr.secrets) else: raise TypeError('Expected an Expression. G...
def style_doc_files(*files, max_len=119, check_only=False): changed = [] black_errors = [] for file in files: if os.path.isdir(file): files = [os.path.join(file, f) for f in os.listdir(file)] files = [f for f in files if (os.path.isdir(f) or f.endswith('.mdx') or f.endswith('...
def check_core_pattern(): rv = True core_pattern_file = '/proc/sys/kernel/core_pattern' if os.path.exists(core_pattern_file): with open(core_pattern_file, 'r') as f: if (f.readline().rstrip()[0] == '|'): print(("[*] afl-fuzz requires 'echo core >%s'" % core_pattern_file))...
def test_ccprmod_one_support(): supports = [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]] idx_correct_label = [2, 1] assert np.isclose(ccprmod(supports, idx_correct_label), 1, atol=0.01).all()
class RectTupleData(): def __init__(self, len_tuple, DATA_PATH, n=N): self._len_tuple = len_tuple self._cur_ind = 0 self._N = n try: self._fid_X = open((DATA_PATH + ('/X_%d_%d.bin' % (n, len_tuple))), 'rb') self._fid_Y = open((DATA_PATH + ('/Y_%d_%d.bin' % (n,...
class RandomSized_new(object): def __init__(self, size, scale1=0.5, scale2=2): self.size = size self.crop = RandomCrop_new(self.size) self.small_scale = scale1 self.big_scale = scale2 def __call__(self, sample): img = sample['image'] mask = sample['label'] ...
def matmul_delegation_test2(matrix0: dace.float32[(N, K)], matrix1: dace.float32[(K, M)], vector0: dace.float32[M], vector1: dace.float32[N], result: dace.float32[1]): result[0] = ((vector1 (matrix0 matrix1)) vector0)
def calculate_cm(cm_dump_filepath: str, gt_filepath: str, n: int) -> np.ndarray: cm = np.zeros((n, n), dtype=int) print(cm_dump_filepath, gt_filepath) predictions = [] with open(cm_dump_filepath, 'r') as fp: reader = csv.reader(fp, delimiter=';', quotechar='"') predictions = list(reader)...
class LowInkRandomLines(LowInkLine): def __init__(self, count_range=(5, 10), use_consistent_lines=True, noise_probability=0.1, p=1): super().__init__(use_consistent_lines=use_consistent_lines, noise_probability=noise_probability, p=p) self.count_range = count_range def __repr__(self): re...
class GaussianConnector(nn.Module): def __init__(self, use_gpu): super(GaussianConnector, self).__init__() self.use_gpu = use_gpu def forward(self, mu, logvar): epsilon = th.randn(logvar.size()) epsilon = cast_type(Variable(epsilon), FLOAT, self.use_gpu) std = th.exp((0.5...
class WordEmbeddings(): def __init__(self, file_name, word2cnt=None): self.id2word = {} self.word2id = {} self.embeddings = [] if word2cnt: self.load_based_word2cnt(file_name, word2cnt) else: self.load_from_file(file_name) self.word2id['<UNK>']...
def _remote_method(method, rref, *args, **kwargs): args = ([method, rref] + list(args)) return rpc.rpc_async(rref.owner(), _call_method, args=args, kwargs=kwargs)
def process_fa_arman(paths, short_name): assert (short_name == 'fa_arman') language = 'fa' base_input_path = os.path.join(paths['NERBASE'], 'PersianNER') train_input_file = os.path.join(base_input_path, 'train_fold1.txt') test_input_file = os.path.join(base_input_path, 'test_fold1.txt') if ((not...
def Xception(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): if (weights not in {'imagenet', None}): raise ValueError('The `weights` argument should be either `None` (random initialization) or `imagenet` (pre-training on ImageNet).') if ((weights =...
def getILD(category_id, recList, reverse_item): score = 0 n = len(recList) for i in range(0, n): for j in range(0, n): if ((j != i) and (category_id[reverse_item[recList[i]]] != category_id[reverse_item[recList[j]]])): score += 1 return (score / (n * (n - 1)))
class TestImbalance(unittest.TestCase): def test(self): feature_names = ['Age', 'Workclass', 'fnlwgt', 'Education', 'Education-Num', 'Marital Status', 'Occupation', 'Relationship', 'Race', 'Sex', 'Capital Gain', 'Capital Loss', 'Hours per week', 'Country', 'label'] data_dir = os.path.join(os.path.di...
def parse_detail_file(dict_exp, file_path) -> defaultdict: combos = generate_combos() i = 0 with open(os.path.join(os.curdir, file_path)) as f: lines = f.readlines() curr_exp = None for line in lines: values = line.split() if (len(values) == 2): ...
class RandomSideObstacleSpaceInvadersWorld(SpaceInvadersWorld): def reset_world(self): super(RandomSideObstacleSpaceInvadersWorld, self).reset_world() self.reset_obstacle() def reset_obstacle(self): if hasattr(self, 'obstacle'): self.obstacle.kill() side = self.np_ran...
class CARHead(torch.nn.Module): def __init__(self, in_channels, out_channels, cls_out_num_classes): super(CARHead, self).__init__() self.fi = nn.Sequential(nn.Conv2d((in_channels * 2), out_channels, 1, 1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)) cls_tower = [] reg_tower ...
class WeightedSSLModel(torch.nn.Module): def __init__(self, hub, num_layers, layernorm=False): super().__init__() self.encoder = AutoModel.from_pretrained(hub, output_hidden_states=True) self.num_layers = num_layers zero_init = torch.cat([torch.zeros(self.num_layers)]) self.w...
def test_regulartype_numpytype_categorical_parameter(): t = RegularType(NumpyType('int32'), 5, parameters={'__categorical__': True, '__array__': 'Something'}) assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t))
(frozen=True) class PLASWithPerturbationModules(PLASModules): perturbation: DeterministicResidualPolicy targ_perturbation: DeterministicResidualPolicy
def get_workflow_jobs(): config_list = instantiate_configs() x = [] for conf_options in config_list: phases = (conf_options.restrict_phases or dimensions.PHASES) for phase in phases: if (Conf.is_test_phase(phase) and (conf_options.cuda_version == '10')): continue ...
def test_setup_no_batch_size(): deterministic.set_seed(0) runner = LocalRunner(snapshot_config) algo = CrashingAlgo() algo.max_path_length = 100 algo.policy = None runner.setup(algo, None, sampler_cls=LocalSampler) with pytest.raises(ValueError, match='batch_size'): runner.train(n_ep...
def arg_casts(arg): if (arg in ['npy_complex64', 'npy_complex128', '_cselect1', '_cselect2', '_dselect2', '_dselect3', '_sselect2', '_sselect3', '_zselect1', '_zselect2']): return '<{0}*>'.format(arg) return ''
def register_Ns3ChannelAccessManager_methods(root_module, cls): cls.add_constructor([param('ns3::ChannelAccessManager const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Txop >', 'dcf')]) cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True) cls...
def test_MemoryTimeCard_add(): timecard = MemoryTimeCard(0) r1 = Reservation('', '', 10, 20, 5, 0.9) assert (timecard.add(r1) is True) r2 = Reservation('', '', 5, 7, 5, 0.9) assert (timecard.add(r2) is True) r3 = Reservation('', '', 20, 25, 5, 0.9) assert (timecard.add(r3) is False) r4 =...
def test_load_metadata(): default_clipid = 'Beach-01-Raw' dataset = eigenscape_raw.Dataset(TEST_DATA_HOME) clip = dataset.clip(default_clipid) assert (clip.location == 'Bridlington Beach') assert (clip.time == '10:42') assert (clip.date == '09/05/2017') assert (clip.additional_information ==...
def CreateDataset(dataroots, dataset_mode='2afc', load_size=64): dataset = None if (dataset_mode == '2afc'): from dataset.twoafc_dataset import TwoAFCDataset dataset = TwoAFCDataset() elif (dataset_mode == 'jnd'): from dataset.jnd_dataset import JNDDataset dataset = JNDDatase...
class flickr30k_train(Dataset): def __init__(self, transform, image_root, ann_root, max_words=30, prompt=''): url = ' filename = 'flickr30k_train.json' download_url(url, ann_root) self.annotation = json.load(open(os.path.join(ann_root, filename), 'r')) self.transform = transf...
def subprocess_call(cmd, logger='bar', errorprint=True): logger = proglog.default_bar_logger(logger) logger(message='Moviepy - Running:\n>>> "+ " ".join(cmd)') popen_params = {'stdout': DEVNULL, 'stderr': sp.PIPE, 'stdin': DEVNULL} if (os.name == 'nt'): popen_params['creationflags'] = proc ...
class Model(nn.Module): def __init__(self, args): super().__init__() self.graph = Graph() self.source_nodes = self.graph.source_nodes self.target_nodes = self.graph.target_nodes A = torch.tensor(self.graph.A, dtype=torch.float32, requires_grad=False) self.register_buf...
class MultipleOutputsNet(torch.nn.Module): def __init__(self): super(MultipleOutputsNet, self).__init__() self.conv1 = torch.nn.Conv2d(3, 3, kernel_size=1, stride=1) self.conv2 = torch.nn.Conv2d(1, 3, kernel_size=1, stride=1) self.conv3 = torch.nn.Conv2d(1, 3, kernel_size=1, stride=1...
def global_average_pooling_data_grad_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): gdx = grad_inputs[0] gdy = F.global_average_pooling(gdx) return gdy
def _find_pow_of_frobenius(p, n, x, y): from .integer_mod import mod for i in range(n): if (x == y): break y = (y ** p) else: raise RuntimeError('No appropriate power of Frobenius found') return mod(i, n)
class TFDebertaV2ForQuestionAnswering(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class DCProblemTestsN_Nuemann_storeJ(DCProblem_2DTests): formulation = 'Simulation2DNodal' storeJ = True adjoint_tol = 1e-08 bc_type = 'Neumann'
class NextWordShardDataset(ShardDataset): def __init__(self, X, y): self.X = X self.y = y def __len__(self): return len(self.X) def __getitem__(self, index: int): return (self.X[index], self.y[index])
class Test_createMagConversionDict(TestCase): def test_works(self): magTable = eq._createMagConversionDict() self.assertEqual(magTable['A6'][10], '0.44') self.assertEqual(magTable['B0'][0], '30000') self.assertEqual(magTable['M6'][14], 'nan')
class TestInference(unittest.TestCase): def setUp(self): attrs = ['a', 'b', 'c', 'd', 'e'] shape = [2, 3, 4, 5, 6] self.domain = Domain(attrs, shape) self.measurements = [] for i in range(4): I = np.eye(shape[i]) y = np.random.rand(shape[i]) ...
def test_fortran_eof_ok(tmpdir): filename = path.join(str(tmpdir), 'scratch') np.random.seed(1) with FortranFile(filename, 'w') as f: f.write_record(np.random.randn(5)) f.write_record(np.random.randn(3)) with FortranFile(filename, 'r') as f: assert (len(f.read_reals()) == 5) ...
class HidingRes(nn.Module): def __init__(self, in_c=4, out_c=3, only_residual=False, requires_grad=True): super(HidingRes, self).__init__() self.conv1 = nn.Conv2d(in_c, 128, 3, 1, 1, bias=False) self.norm1 = nn.InstanceNorm2d(128, affine=True) self.conv2 = nn.Conv2d(128, 128, 3, 1, 1...
class LoopScopeGuard(): def __init__(self, scopes, non_static_guard=None): self.scopes = scopes self.non_static_guard = non_static_guard def __enter__(self): self.scopes.append(LoopScopeAttribute((self.non_static_guard is None))) if self.non_static_guard: self.non_sta...
def test_api(): import pgx env = pgx.bridge_bidding.BridgeBidding(DDS_HASH_TABLE_PATH) pgx.api_test(env, 3, use_key=False) pgx.api_test(env, 3, use_key=True)
def write_version_py(): content = "# GENERATED VERSION FILE\n# TIME: {}\n__version__ = '{}'\n__gitsha__ = '{}'\nversion_info = ({})\n" sha = get_hash() with open('VERSION', 'r') as f: SHORT_VERSION = f.read().strip() VERSION_INFO = ', '.join([(x if x.isdigit() else f'"{x}"') for x in SHORT_VERSI...
def test(image_file, fc, feat_dir): (index_list, label_list) = ([], []) with open(image_file) as fp: for line in fp: (index, l) = line.split() index_list.append(index.split('.')[0]) label_list.append(int(l)) top_retrv = [1, 5] hit_count = np.zeros(len(top_retr...
def stacked_core_full_gauss_readout(dataloaders, seed, hidden_channels=32, input_kern=13, hidden_kern=3, layers=3, gamma_input=15.5, skip=0, final_nonlinearity=True, momentum=0.9, pad_input=False, batch_norm=True, hidden_dilation=1, laplace_padding=None, input_regularizer='LaplaceL2norm', use_avg_reg=False, init_mu_ran...
class MLP(eqx.Module): layers: List[nn.Linear] activation: Callable = eqx.static_field() final_activation: Callable = eqx.static_field() in_size: int = static_field() out_size: int = static_field() width_size: int = static_field() depth: int = static_field() def __init__(self, in_size: i...
def encode(ob, extensions=None, **options): s = BsdfSerializer(extensions, **options) return s.encode(ob)
class AlexNet(nn.Module): configs = [3, 96, 256, 384, 384, 256] def __init__(self, width_mult=1): configs = list(map((lambda x: (3 if (x == 3) else int((x * width_mult)))), AlexNet.configs)) super(AlexNet, self).__init__() self.layer1 = nn.Sequential(nn.Conv2d(configs[0], configs[1], ker...
class Tagger(object): def __init__(self, tagsfile): self.tagsfile = tagsfile self.prevline = None self.ignored = 0 def __call__(self, words): tagsline = '\n' while (tagsline == '\n'): tagsline = tagsfile.readline() tags = get_tags(tagsline) if ...
def test_autodetect_function_in_for(): def adff(A): for _ in range(5): freefunction2(A) A = np.random.rand(20) ref = np.copy(A) adff(A) assert np.allclose(A, (ref + (2 * 5)))
def make_dataset(dataset_name, data_dir, batch_size=128, sample_size=None, SOTA=False): if (dataset_name == 'cifar10'): print('Dataset: CIFAR10.') if SOTA: trainset = CIFAR10(root=data_dir, train=True, download=True, transform=transforms.Compose([transforms.RandomCrop(size=32, padding=4)...
class ScalarInequality(Constraint): def _validate_inputs(cls, **kwargs): errors = [] try: super()._validate_inputs(**kwargs) except Exception as e: errors.append(e) if (('relation' in kwargs) and (kwargs['relation'] not in {'>', '>=', '<', '<='})): ...
def construct_beta_hats(opt_beta, opt_beta_sens, eps_list, max_norm): beta_hats = gen_list(opt_beta, opt_beta_sens, eps_list) for i in range(len(beta_hats)): beta_hats[i] = project.two_norm_project(beta_hats[i], max_norm) return beta_hats
def create_val_img_folder(root): dataset_dir = os.path.join(root) val_dir = os.path.join(dataset_dir, 'val') img_dir = os.path.join(val_dir, 'images') fp = open(os.path.join(val_dir, 'val_annotations.txt'), 'r') data = fp.readlines() val_img_dict = {} for line in data: words = line.s...
class Context(): def __init__(self, name): self.name = name self.constants = {} self.symbols = [] self.containers = [] self.read_vars = [] self.written_vars = []
def norm(input, is_train, reuse=True, norm=None): assert (norm in ['instance', 'batch', None]) if (norm == 'instance'): with tf.variable_scope('instance_norm', reuse=reuse): eps = 1e-05 (mean, sigma) = tf.nn.moments(input, [1, 2], keep_dims=True) normalized = ((input ...
def set_window_size_callback(window, cbfun): window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if (window_addr in _window_size_callback_repository): previous_callback = _window_size_callback_repository[window_addr] else: previous_callback = None ...
def scatter(inputs, target_gpus, dim=0): def scatter_map(obj): if isinstance(obj, torch.Tensor): if (target_gpus != [(- 1)]): return OrigScatter.apply(target_gpus, None, dim, obj) else: return Scatter.forward(target_gpus, obj) if isinstance(obj...
def mask_and(clip, other_clip): if isinstance(other_clip, ImageClip): other_clip = other_clip.img if isinstance(other_clip, np.ndarray): return clip.fl_image((lambda f: np.minimum(f, other_clip))) else: return clip.fl((lambda gf, t: np.minimum(gf(t), other_clip.get_frame(t))))
.parametrize('tau', [0.05]) .parametrize('input_size', [32]) .parametrize('output_size', [32]) def test_soft_sync(tau: float, input_size: int, output_size: int) -> None: module = torch.nn.Linear(input_size, output_size) targ_module = torch.nn.Linear(input_size, output_size) original = copy.deepcopy(targ_mod...
class lPCA(GlobalEstimator): def __init__(self, ver='FO', alphaRatio=0.05, alphaFO=0.05, alphaFan=10, betaFan=0.8, PFan=0.95, verbose=True, fit_explained_variance=False): self.ver = ver self.alphaRatio = alphaRatio self.alphaFO = alphaFO self.alphaFan = alphaFan self.betaFan ...
.parametrize('name', ['foo', '_foo']) def test_valid_identifier_names(name): t = sqlparse.parse(name)[0].tokens assert isinstance(t[0], sqlparse.sql.Identifier)
class Trainer(object): def __init__(self, train_data, model, optimizer=None, loss=None, batch_size=32, sampler=None, drop_last=False, update_every=1, num_workers=0, n_epochs=10, print_every=5, dev_data=None, metrics=None, metric_key=None, validate_every=(- 1), save_path=None, use_tqdm=True, device=None, callbacks=N...
def test_config_namespace_copy(config_ns): config_ns2 = config_ns.deepcopy() config_ns2.a.b.param1 = 2 assert (config_ns2.a.b.param1 != config_ns.a.b.param1)
def register(*args, **kwargs): q = ctx.Queue() p = ctx.Process(target=_registration_worker, args=[q, args, kwargs], daemon=True) p.start() try: result = q.get() if isinstance(result, BaseException): raise result p.join() except BaseException as e: p.termin...
_toolkit() class Shopify(FunctionToolkit): name_for_human = 'Shopify' description_for_human = 'Toolkit for managing Shopify stores.' name_for_model = 'Shopify' description_for_model = 'A comprehensive toolkit for managing Shopify stores, including product, order, and customer management, as well as stor...
class decoder4(nn.Module): def __init__(self): super(decoder4, self).__init__() self.reflecPad11 = nn.ReflectionPad2d((1, 1, 1, 1)) self.conv11 = nn.Conv2d(512, 256, 3, 1, 0) self.relu11 = nn.ReLU(inplace=True) self.unpool = nn.UpsamplingNearest2d(scale_factor=2) self...
class EigenQuaternionPrinter(): def __init__(self, val): type = val.type if (type.code == gdb.TYPE_CODE_REF): type = type.target() self.type = type.unqualified().strip_typedefs() self.innerType = self.type.template_argument(0) self.val = val self.data = se...
def get_rgb_data(rgb_dir): assert os.path.exists(rgb_dir) return DataLoader_NoisyData(rgb_dir)
class Conv2dSame(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True): super(Conv2dSame, self).__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias) nn.init.xavier_uniform_(self.weight) def forw...
def load_toy_cancer(): train = Database() test = Database() train.modes = ['friends(+Person,-Person).', 'friends(-Person,+Person).', 'smokes(+Person).', 'cancer(+Person).'] train.pos = ['cancer(alice).', 'cancer(bob).', 'cancer(chuck).', 'cancer(fred).'] train.neg = ['cancer(dan).', 'cancer(earl).']...
def convert_tensorflow(nlp: Pipeline, opset: int, output: Path): if (not is_tf_available()): raise Exception('Cannot convert because TF is not installed. Please install tensorflow first.') print("/!\\ Please note TensorFlow doesn't support exporting model > 2Gb /!\\") try: import tensorflow ...
def logit(x, is_training=True, update_batch_stats=True, stochastic=True, seed=1234): return cnn.logit(x, is_training=is_training, update_batch_stats=update_batch_stats, stochastic=stochastic, seed=seed)
class TrainingSummary(): model_name: str language: Optional[Union[(str, List[str])]] = None license: Optional[str] = None tags: Optional[Union[(str, List[str])]] = None finetuned_from: Optional[str] = None tasks: Optional[Union[(str, List[str])]] = None dataset: Optional[Union[(str, List[str...
def test_multiple_or_proof_infix_operator(group, params): (p1, p2, secrets) = params g = group.generator() x10 = Secret() secrets.update({x10: 13}) orproof = ((p1 | p2) | DLRep((13 * g), (x10 * g))) assert verify_proof(orproof, secrets)
def random_quadraticform_with_conditions(R, n, condition_list=[], rand_arg_list=[]): Q = random_quadraticform(R, n, rand_arg_list) done_flag = True while done_flag: done_flag = False for c in condition_list: try: bool_ans = Q.c() except Exception: ...
.function def run_inception_jit(inputs, inception_model, num_batches=1): inputs = ((tf2.cast(inputs, tf2.float32) - 127.5) / 127.5) return tfgan.eval.run_classifier_fn(inputs, num_batches=num_batches, classifier_fn=classifier_fn_from_tfhub(INCEPTION_TFHUB, None, inception_model), dtypes=_DEFAULT_DTYPES)
.parametrize('create_solver', ss.solvers.values()) def test_cons_rts(create_solver): solver = create_solver(False) (solver, ts) = build_simple_ts(solver, pono.RelationalTransitionSystem)
def convert_id_to_speaker(ids_to_speakers, index, unk_token=''): return ids_to_speakers.get(index, unk_token)
def _iter_vectors(n, lower, upper, step=None): if (step is None): if (ZZ(lower) >= ZZ(upper)): raise ValueError(('Expected lower < upper, but got %d >= %d' % (lower, upper))) if (ZZ(n) <= 0): raise ValueError(('Expected n>0 but got %d <= 0' % n)) step = n assert (...
class LAUC(BaseMetric): def __init__(self, recommendations, config, params, eval_objects): super().__init__(recommendations, config, params, eval_objects) self.logger = logging.get_logger('Evaluator', (pylog.CRITICAL if config.config_test else pylog.DEBUG)) self._cutoff = self._evaluation_ob...
def test_vectorizer_max_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', max_df=1.0) vect.fit(test_data) assert ('a' in vect.vocabulary_.keys()) assert (len(vect.vocabulary_.keys()) == 6) assert (len(vect.stop_words_) == 0) vect.max_df = 0.5 vect.fit(test_d...
class ELU_VGG(nn.Module): def __init__(self, vgg_name): super(ELU_VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, 10) def forward(self, x): out = self.features(x) out = out.view(out.size(0), (- 1)) out = self...
def test_lambertw(): assert (LambertW(0) == 0) assert (LambertW(E) == 1) assert (LambertW(((- 1) / E)) == (- 1)) assert (LambertW(((- log(2)) / 2)) == (- log(2)))
class SPADENorm(nn.Module): def __init__(self, opt, norm_type, norm_nc, label_nc): super(SPADENorm, self).__init__() self.param_opt = opt self.noise_scale = nn.Parameter(torch.zeros(norm_nc)) assert norm_type.startswith('alias') param_free_norm_type = norm_type[len('alias'):]...
def run_attack(exp_meta, exp_meta_lock, adrAttack): global running try: print('ATK: Starting attack') adrAttack.attack() except: with exp_meta_lock: exp_meta['reason_stop'] = ('Attack threw an exception: ' + str(sys.exc_info()[1])) running = False raise ...
def chunks(l, n): bigger_count = (len(l) % n) start = 0 block_size = (len(l) // n) for i in range(n): end = ((start + block_size) + (1 if (i < bigger_count) else 0)) (yield l[start:end]) start = end
def main(_): header = ['content', 'label', 'id'] contents = load_data_by_id('train', FLAGS.train_id_path) os.mkdir(FLAGS.output_dir) dump_raw_data(([header] + contents), os.path.join(FLAGS.output_dir, 'train.csv')) contents = load_all_data('test') dump_raw_data(([header] + contents), os.path.joi...
def enable_dropout(model): for m in model.modules(): if m.__class__.__name__.startswith('Dropout'): m.train() print(m)
class MetaTransformer(MetaEstimatorMixin, TransformerMixin, BaseEstimator): def __init__(self, transformer): self.transformer = transformer def fit(self, X, y=None, **fit_params): params = process_routing(self, 'fit', **fit_params) self.transformer_ = clone(self.transformer).fit(X, y, **...
class GNN_node_Virtualnode(torch.nn.Module): def __init__(self, num_layer, emb_dim, node_encoder, drop_ratio=0.5, JK='last', residual=False, gnn_type='gin'): super(GNN_node_Virtualnode, self).__init__() self.num_layer = num_layer self.drop_ratio = drop_ratio self.JK = JK self...
def run_test_in_subprocess(test_case, target_func, inputs=None, timeout=None): if (timeout is None): timeout = int(os.environ.get('PYTEST_TIMEOUT', 600)) start_methohd = 'spawn' ctx = multiprocessing.get_context(start_methohd) input_queue = ctx.Queue(1) output_queue = ctx.JoinableQueue(1) ...