code
stringlengths
101
5.91M
class Resnet18_3D(nn.Module): def __init__(self, embedding_dimension=512): super(Resnet18_3D, self).__init__() self.model = resnet18() self.input_features_fc_layer = self.model.fc.in_features self.model.fc = common_functions.Identity() def forward(self, images): embedding...
def phi_on_multiplicative_basis(compo): f = F_algebra(QQ).gen if (tuple(compo) == (2,)): return f(2) if (len(compo) == 1): (n,) = compo return f(n) return compute_u_on_compo(compo)
def preprocess_args(fun, varnames): def wrapper(f, *a, **kw): if hasattr(f, 'func_code'): func_code = f.func_code else: func_code = f.__code__ names = func_code.co_varnames new_a = [(fun(arg) if (name in varnames) else arg) for (arg, name) in zip(a, names)] ...
def main(argv=None): if (argv is None): argv = sys.argv[1:] from optparse import OptionParser parser = OptionParser(usage='usage: %prog [options] collection') parser.add_option('--overwrite', default=0, type='int', help='overwrite existing file (default: 0)') parser.add_option('--rootpath', ...
class Clip(core.Clip): def __init__(self, clip_id, data_home, dataset_name, index, metadata): super().__init__(clip_id, data_home, dataset_name=dataset_name, index=index, metadata=metadata) self.audio_path = self.get_path('audio') self.annotation_path = self.get_path('annotation') _prope...
def mk_lean_code_file(file_names: LeanFileNames, lean_info: LeanProgramInfo, assembly_info: LeanAssemblyInfo): out = open(file_names.code_filename, 'w') lean_code = [code_line for code_elt in assembly_info.lean_code for code_line in code_elt.code] print('/-', file=out) print('File: {}.lean'.format(file_...
class SkewTableaux(UniqueRepresentation, Parent): def __init__(self, category=None): if (category is None): Parent.__init__(self, category=Sets()) else: Parent.__init__(self, category=category) def _repr_(self): return 'Skew tableaux' def _element_constructor_...
class Take_all(): def take(self, net, RAT=None, LDP=None): cd = {} if (RAT is None): Rat = net.RAT elif isinstance(RAT, str): Rat = [RAT] if (LDP is None): Ldp = net.LDP elif isinstance(LDP, str): Ldp = [LDP] for ldp in ...
def mean_kernel_inception_distance(): source_alpha = 0.98 target_alpha = (1 - source_alpha) filenames = glob(os.path.join('./real_source', '*.*')) real_source_images = [get_images(filename) for filename in filenames] real_source_images = np.transpose(real_source_images, axes=[0, 3, 1, 2]) filena...
def init_test_kitti(): config['kitti_image_root'] = '/home/ssm/ssj/dataset/KITTI/tracking/image_2' config['kitti_detection_root'] = '/home/ssm/ssj/dataset/KITTI/tracking/det_2_lsvm' config['type'] = 'train' config['dataset_type'] = 'training' config['resume'] = '/home/ssm/ssj/weights/KITTI/weights04...
class TestBackBones(unittest.TestCase): def count_layers(self, model): if isinstance(model[4][0], BasicBlock): n_convs = 2 elif isinstance(model[4][0], Bottleneck): n_convs = 3 else: raise ValueError('Backbone layer block not supported!') return ((...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes, criterion): self.inplanes = 128 super(ResNet, self).__init__() self.conv1 = conv3x3(3, 64, stride=2) self.bn1 = BatchNorm2d(64) self.relu1 = nn.ReLU(inplace=False) self.conv2 = conv3x3(64, 64) ...
.parametrize('action_size', [4]) .parametrize('batch_size', [32]) .parametrize('observation_shape', [(100,)]) def test_discrete_random_policy(action_size: int, batch_size: int, observation_shape: Sequence[int]) -> None: algo = DiscreteRandomPolicyConfig().create() algo.create_impl(observation_shape, action_size...
class TransSfPNet(nn.Module): def __init__(self, backbone='resnet', output_stride=16, num_classes=21, sync_bn=True, freeze_bn=False, device=None): super(TransSfPNet, self).__init__() if (backbone == 'drn'): output_stride = 8 if (sync_bn == True): BatchNorm = Synchroni...
class FaissIndexer(): def __init__(self, index=None): import faiss as faiss_module self.faiss_module = faiss_module self.index = index def train_index(self, embeddings): self.index = self.faiss_module.IndexFlatL2(embeddings.shape[1]) self.add_to_index(embeddings) def ...
class Closeness(BaseRanking): def __init__(self, method: str='exact', tol: float=0.1): super(Closeness, self).__init__() self.method = method self.tol = tol def fit(self, adjacency: Union[(sparse.csr_matrix, np.ndarray)]) -> 'Closeness': adjacency = check_format(adjacency) ...
def is_chinese(word: str): for char in word: char = ord(char) if (not _is_chinese_char(char)): return 0 return 1
def generate_h5(model_resnext101, video_ids, outfile): video_total_num = len(video_ids) with h5py.File(outfile, 'w') as fd: feat_dset_resnext101 = None video_ids_dset = None i0 = 0 for (i, (video_path, video_id)) in enumerate(video_ids): (clips, valid) = extract_clips...
class LinearSeqAttn(nn.Module): def __init__(self, input_size): super(LinearSeqAttn, self).__init__() self.linear = nn.Linear(input_size, 1) def forward(self, x, x_mask): x_flat = x.view((- 1), x.size((- 1))) scores = self.linear(x_flat).view(x.size(0), x.size(1)) scores....
def parse_few_shot_qa_single_answer(string, setting_name, language='en'): answer = try_parse_few_shot_qa_single_answer(string, setting_name, language) if (answer is None): return find_first_capital_letter(string) else: return answer
class GaussianRasterizationSettings(NamedTuple): image_height: int image_width: int tanfovx: float tanfovy: float bg: torch.Tensor scale_modifier: float viewmatrix: torch.Tensor projmatrix: torch.Tensor sh_degree: int campos: torch.Tensor prefiltered: bool debug: bool
class Setup(object): def setup(self): raise NotImplementedError() def shutdown(self): raise NotImplementedError()
def nlte_raw_plasma_w0(tardis_model_config_nlte, nlte_raw_simulation_state, nlte_atom_data): nlte_raw_simulation_state.dilution_factor = np.zeros_like(nlte_raw_simulation_state.dilution_factor) plasma = assemble_plasma(tardis_model_config_nlte, nlte_raw_simulation_state, nlte_atom_data) return plasma
def copy_checkpoint(src, dst, logger): if osp.isfile(dst): if hasattr(logger, 'log'): logger.log('Find {:} exist, delete is at first before saving'.format(dst)) os.remove(dst) copyfile(src, dst) if hasattr(logger, 'log'): logger.log('copy the file from {:} into {:}'.forma...
def _update_from_config(obj, cfg): for k in obj.__dict__.keys(): try: obj.__dict__[k] = cfg[k.upper()] except KeyError: raise KeyError("'{}' has not been defined in config file".format(k.upper())) except Exception as e: raise Exception(e)
class Kmer(): def __init__(self, k=1, normalize=False, upto=False, alphabet='ACGT'): self.k = k self.upto = upto self.normalize = normalize self.alphabet = alphabet check_nac_para(k=self.k, upto=self.upto, normalize=self.normalize, alphabet=self.alphabet) self._kmer_l...
class FederatedFlow(FLSpec): def __init__(self, model=None, optimizer=None, rounds=3, **kwargs): super().__init__(**kwargs) if (model is not None): self.model = model self.optimizer = optimizer else: self.model = Net() self.optimizer = optim.SG...
def test_sample_regular_pass_smote_enn(): smote = SMOTEENN(smote=SMOTE(sampling_strategy='auto', random_state=RND_SEED), enn=EditedNearestNeighbours(sampling_strategy='all'), random_state=RND_SEED) (X_resampled, y_resampled) = smote.fit_resample(X, Y) X_gt = np.array([[1., (- 0.)], [0., (- 0.)], [0., (- 0.)...
_utils.test(arch=get_host_arch_list()) def test_order_must_throw_vector(): with pytest.raises(ti.TaichiCompilationError, match='The dimensionality of shape and order must be the same'): a = ti.Vector.field(3, dtype=ti.f32, shape=3, order='ij') with pytest.raises(ti.TaichiCompilationError, match='shape c...
class LayerNorm(nn.Module): def __init__(self, n_out, eps=1e-05, affine=True): super(LayerNorm, self).__init__() self.n_out = n_out self.affine = affine if self.affine: self.weight = nn.Parameter(torch.ones(n_out, 1, 1)) self.bias = nn.Parameter(torch.zeros(n_...
class DocStringSlot(SlotDescriptor): def slot_code(self, scope): doc = scope.doc if (doc is None): return '0' if doc.is_unicode: doc = doc.as_utf8_string() return doc.as_c_string_literal()
def _make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module() out_shape1 = in_shape[0] out_shape2 = in_shape[1] out_shape3 = in_shape[2] out_shape4 = in_shape[3] scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=...
class VGGATest(tf.test.TestCase): def testBuild(self): batch_size = 5 (height, width) = (224, 224) num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) (logits, _) = vgg.vgg_a(inputs, num_classes) ...
def save_file(obj, filename, *args, **kwargs): ext = get_ext(filename) if (ext in _ext_table): before_save(filename) return _ext_table[ext][0](obj, filename, *args, **kwargs) else: raise ValueError('Unsupported file {} with file extension {}'.format(filename, ext))
def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--graph', help='compiled TF graph', required=True) arg_parser.add_argument('--chkpt', help='TF checkpoint (model params)', required=True) arg_parser.add_argument('--beam_size', type=int, default=12) arg_parser.add_argument('...
_to_string class Rule(RuleFactory): def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, merge_slashes=None, redirect_to=None, alias=False, host=None, websocket=False): if (not string.startswith('/')): raise ValueError('url...
class ImageBindModality(Modality): def __init__(self, num_projector_layers: int=2, num_tokens: int=4, preprocess_device: str='cpu'): self.module = ImageBindModule() self.dtype = torch.float32 self.device = 'cpu' self.imagebind_device = 'cpu' self.preprocess_device = preproces...
(autouse=True, scope='session') def add_imports(doctest_namespace: dict[(str, Any)]): import sage.all dict_all = sage.all.__dict__ dict_all.pop('__package__', None) sage_namespace = dict(dict_all) sage_namespace['__name__'] = '__main__' doctest_namespace.update(**sage_namespace)
class Node(object): def __init__(self, node_type, name, n_name=None, caseless=True): self.node_type = node_type self.name = name self.normalized_name = (n_name if n_name else name) self.indexable_name = utils.to_indexable(name, caseless) self.lexical_features = None def c...
def verify_no_leak(callback: Callable[([], Any)], repeat: int=10000, fuzzy: int=10) -> None: callback() initial_blocks = (0, 0, 0, 0) valgrind.memcheck_do_leak_check() initial_blocks = valgrind.memcheck_count_leak_blocks() for _ in range(repeat): callback() valgrind.memcheck_do_leak_chec...
def example_to_device(example, device, non_blocking=False) -> dict: example_torch = {} float_names = ['voxels', 'bev_map'] for (k, v) in example.items(): if (k in ['anchors', 'anchors_mask', 'reg_targets', 'reg_weights', 'labels', 'hm', 'anno_box', 'ind', 'mask', 'cat']): example_torch[k...
def parse_sim_time(path): ret = {} if (not os.path.exists(path)): return ret with open(path, 'r', encoding='utf-8') as f: data = json.load(f) ret['simtime'] = ((data['end_time'] - data['start_time']) / 60) f.close() return ret
def get_valid_stats(args, trainer, stats): stats['num_updates'] = trainer.get_num_updates() if hasattr(checkpoint_utils.save_checkpoint, 'best'): key = 'best_{0}'.format(args.best_checkpoint_metric) best_function = (max if args.maximize_best_checkpoint_metric else min) stats[key] = best_...
class GecDataModule(pl.LightningDataModule): def __init__(self, args, tokenizer, DatasetModule): super().__init__() self.args = args self.tokenizer = tokenizer self.train = DatasetModule(self.args.train_data_path, self.tokenizer, self.args.max_seq_len, data_split_type='train') ...
def GetNodeOutDegV_PUndirNet(Graph, NIdOutDegV): return _snap.GetNodeOutDegV_PUndirNet(Graph, NIdOutDegV)
def make_user_schema(**kwargs): return make_object_schema(first_name={'type': 'string'}, last_name={'type': 'string'}, **kwargs)
def _shuffle_and_split(data: List, test_ratio=None, test_size=None, seed=0): random.seed(seed) size = len(data) if (test_ratio is not None): train_ratio = (1 - test_ratio) train_size = math.floor((size * train_ratio)) elif (test_size is not None): train_size = (size - test_size) ...
def test_tpfp_openimages(): det_bboxes = np.array([[10, 10, 15, 15, 1.0], [15, 15, 30, 30, 0.98], [10, 10, 25, 25, 0.98], [28, 28, 35, 35, 0.97], [30, 30, 51, 51, 0.96], [100, 110, 120, 130, 0.15]]) gt_bboxes = np.array([[10.0, 10.0, 30.0, 30.0], [30.0, 30.0, 50.0, 50.0]]) gt_groups_of = np.array([True, Fal...
_mode(matmul=False) def kid(x, y, max_size=5000): (x_size, y_size) = (x.shape[0], y.shape[0]) n_partitions = math.ceil(max((x_size / max_size), (y_size / max_size))) total_mmd = x.new_zeros([]) for i in range(n_partitions): cur_x = x[round(((i * x_size) / n_partitions)):round((((i + 1) * x_size)...
def generate_syn_feature(generator, classes, attribute, num): nclass = classes.size(0) syn_feature = torch.FloatTensor((nclass * num), opt.resSize) syn_label = torch.LongTensor((nclass * num)) syn_att = torch.FloatTensor(num, opt.attSize) syn_noise = torch.FloatTensor(num, opt.nz) if opt.cuda: ...
class PROBINGEval(object): def __init__(self, task, task_path, seed=1111): self.seed = seed self.task = task logging.debug('***** (Probing) Transfer task : %s classification *****', self.task.upper()) self.task_data = {'train': {'X': [], 'y': []}, 'dev': {'X': [], 'y': []}, 'test': {...
def gen_lean_struct(struct_def: StructDefinition, namespace: ScopedName, open_namespaces: List[ScopedName]) -> List[List[str]]: member_defs = [f'( {name} : {get_lean_type(member.cairo_type, namespace, open_namespaces)} )' for (name, member) in struct_def.members.items()] member_casts = [(name, get_lean_type_cas...
def simImportShape(fileformat, pathAndFilename, options, identicalVerticeTolerance, scalingFactor): handle = lib.simImportShape(fileformat, pathAndFilename.encode('ascii'), options, identicalVerticeTolerance, scalingFactor) _check_return(handle) return handle
.parametrize('data_dict', [pytest.param('full_spark_dataset', marks=pytest.mark.spark), pytest.param('full_pandas_dataset', marks=pytest.mark.core)]) def test_feature_schema_schema_columns(data_dict, request): dataset = create_dataset(request.getfixturevalue(data_dict)) assert (dataset.feature_schema.columns ==...
def test_tmu_tilde(caplog): mu = 1.0 model = pyhf.simplemodels.uncorrelated_background([6], [9], [3]) data = ([9] + model.config.auxdata) init_pars = model.config.suggested_init() par_bounds = model.config.suggested_bounds() fixed_params = model.config.suggested_fixed() par_bounds[model.conf...
class TestMinisketch(unittest.TestCase): def construct_data(cls, field_size, num_a_only, num_b_only, num_both): sample = [] for _ in range(((num_a_only + num_b_only) + num_both)): while True: r = random.randrange(1, (1 << field_size)) if (r not in sample):...
def main(): print(("Loading train and validate data from '%s'" % opt.data)) train = torch.load((opt.data + '.train.pt')) valid = torch.load((opt.data + '.valid.pt')) print((' * number of training sentences: %d' % len(train))) print((' * maximum batch size: %d' % opt.batch_size)) if opt.train_fro...
class Robot(): def __init__(self, filename, base_position, base_orientation, initial_joint_positions, max_joint_force, gripper_force, arm_joint_ids, gripper_joint_ids, gripper_joint_limits, tcp_link_id, end_effector_link_id, cid, use_nullspace, max_velocity, use_ik_fast, euler_obs, lower_joint_limits=((- 2.8973), (...
def _check_valid_values(data: str) -> bool: not_valid = ((data in NULL_VALUES) or pd.isna(data)) return (not not_valid)
def create_data_module(env: gym.Env, env_name: str, rollout_directory: str, batch_size: int=256, val_frac: float=0.1, unconditional_policy: bool=False, reward_conditioning: bool=False, average_reward_to_go: bool=True, seed: Optional[int]=None) -> AbstractDataModule: if (unconditional_policy and reward_conditioning)...
def tf_efficientnet_b5_ap(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet('tf_efficientnet_b5_ap', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs) return model
def _set_components_and_inputs(parser, args): args.components = [] if (args.translate or args.run_all): args.components.append('translate') if (args.preprocess or args.run_all): args.components.append('preprocess') if (args.search or args.run_all): args.components.append('search'...
class MarkdownParser(ParserStrategy): def read(self, file_path: str) -> str: with open(file_path, 'r') as f: html = markdown.markdown(f.read()) text = ''.join(BeautifulSoup(html, 'html.parser').findAll(string=True)) return text
def performance_fit(y_label, y_output): y_output_logistic = fit_function(y_label, y_output) PLCC = stats.pearsonr(y_output_logistic, y_label)[0] SRCC = stats.spearmanr(y_output, y_label)[0] KRCC = stats.stats.kendalltau(y_output, y_label)[0] RMSE = np.sqrt(((y_output_logistic - y_label) ** 2).mean()...
def generate_lemp_decision_rule_table(lemp_decision_rule_df): csv_fname = 'lemp-decision-rule.csv' with open(csv_fname, 'w') as csv_out: print('model,K,avg_num_items_visited,num_users,num_items,mm_time,lemp_time', file=csv_out) for (_, row) in lemp_decision_rule_df.iterrows(): model ...
def main(): start_time = time.time() threads = [] lock = threading.Lock() for snr_idx in range(len(snrs)): tx_payload_file = './data/tx_payload{}.txt'.format(snr_idx) rx_payload_file = './data/rx_payload{}.txt'.format(snr_idx) rx_crc_file = './data/rx_crc_valid{}.txt'.format(snr_...
_task('speech_recognition') class SpeechRecognitionTask(LegacyFairseqTask): def add_args(parser): parser.add_argument('data', help='path to data directory') parser.add_argument('--silence-token', default='', help='token for silence (used by w2l)') parser.add_argument('--max-source-positions'...
class DefectInputFeatures(object): def __init__(self, example_id, source_ids, label): self.example_id = example_id self.source_ids = source_ids self.label = label
class SpeciesWrapper(CombinatorialClass): def __init__(self, species, labels, iterator, generating_series, name, structure_class): self._species = species self._labels = labels self._iterator = iterator self._generating_series = generating_series self._name = ('%s for %s with...
class qcdevice(): def __init__(self, name: str, nqubits: int=None, connection: list=None, swap_duration: int=None, fmeas: list=None, fsingle: list=None, ftwo: list=None): if (not isinstance(name, str)): raise TypeError('name should be a string.') if (nqubits is not None): if ...
def symbolic_expression(x): from sage.symbolic.expression import Expression from sage.symbolic.ring import SR from sage.modules.free_module_element import is_FreeModuleElement from sage.structure.element import is_Matrix if isinstance(x, Expression): return x elif hasattr(x, '_symbolic_'...
class OPRA(Dataset): root = 'datasets/opra' num_actions = 7 actions = ['hold', 'touch', 'rotate', 'push', 'pull', 'pick up', 'put down'] def __init__(self, split, clip_length_in_frames, frames_between_clips, frame_rate, resize): super().__init__() self.resize = resize self.traini...
class LALR_Parser(Serialize): def __init__(self, parser_conf, debug=False): analysis = LALR_Analyzer(parser_conf, debug=debug) analysis.compute_lalr() callbacks = parser_conf.callbacks self._parse_table = analysis.parse_table self.parser_conf = parser_conf self.parser...
class UnaryOpTest(serial.SerializedTestCase): def _test_unary_op(self, opname, X, rtol=1e-05, atol=1e-08): workspace.ResetWorkspace() pred_net = caffe2_pb2.NetDef() pred_net.name = 'pred' pred_net.external_input.append('X') pred_net.external_output.append('Y') pred_ne...
class TestWeighting(): def test_zero_on_xaxis(self): pim = PersImage() wf = pim.weighting() assert (wf([1, 0]) == 0) assert (wf([100, 0]) == 0) assert (wf([99, 1.4]) == 1.4) def test_scales(self): pim = PersImage() wf = pim.weighting(np.array([[0, 1], [1, ...
def draw_bounding_boxes_on_image(image, boxes, color='red', thickness=4, display_str_list_list=()): boxes_shape = boxes.shape if (not boxes_shape): return if ((len(boxes_shape) != 2) or (boxes_shape[1] != 4)): raise ValueError('Input must be of size [N, 4]') for i in range(boxes_shape[0]...
.unit .convert def test_imread_default(): helpers.setup(with_data=True) test_file = os.path.join(helpers.TEST_PATH, 'test_tiling_image.jpg') expected_array = np.flipud(Image.open(test_file)) empty_array = np.zeros([256, 256]) actual_array = convert.imread_default(test_file, empty_array) helpers....
def cauchy(v, z, w, conj=False): expr = 'ComplexDivide(v, z-w)' cauchy_mult = Genred(expr, ['v = Vj(2)', 'z = Vi(2)', 'w = Vj(2)'], reduction_op='Sum', axis=1) if conj: v = _conj(v) w = _conj(w) (v, z, w) = _broadcast_dims(v, z, w) v = _c2r(v) z = _c2r(z) w = _c2r(w) r = ...
def sample_from_model(sess): x_gen = np.random.normal(0.0, 1.0, ((args.sample_batch_size,) + obs_shape)) new_x_gen_np = sess.run(new_x_gen, {x_sample: x_gen}) return new_x_gen_np
def _assert_n_smooth(x, n): x_orig = x if (n < 2): assert False while True: (q, r) = divmod(x, 2) if (r != 0): break x = q for d in range(3, (n + 1), 2): while True: (q, r) = divmod(x, d) if (r != 0): break ...
class BiGRU(BaseBiRNN): def __init__(self, hidden_units, name='BiGRU'): super(BiGRU, self).__init__(name) self.fw_cell = tf.nn.rnn_cell.GRUCell(hidden_units, name=(name + '_fw_cell')) self.bw_cell = tf.nn.rnn_cell.GRUCell(hidden_units, name=(name + '_bw_cell'))
class VariationalAutoencoder(Autoencoder): def __init__(self, encoder, decoder, mean, log_var, len_dim=1, latent_padding=None, mask_latent=True, mask_out=True, out_mask_value=0.0, latent_mask_value=0.0, latent_stochastic=True): super().__init__() self.encoder = encoder self.decoder = decoder...
class DeviceTypeTestBase(TestCase): device_type: str = 'generic_device_type' _stop_test_suite = False _tls = threading.local() _tls.precision = TestCase._precision _tls.rel_tol = TestCase._rel_tol def precision(self): return self._tls.precision def precision(self, prec): self...
def register_Ns3LoopbackNetDevice_methods(root_module, cls): cls.add_constructor([param('ns3::LoopbackNetDevice const &', 'arg0')]) cls.add_constructor([]) cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3...
class MagicModule(nn.Module): def __init__(self, module): nn.Module.__init__(self) self._type = type(module) for (key, value) in module._parameters.items(): if (value is not None): self.register_parameter(('_origin_' + key), value) self.register_bu...
def train_model(space): params_model = {'dropout': 0.5, 'no_latent_features': 200, 'norm_mean': 0.0, 'norm_std': 0.001, 'input_size': 8936, 'output_size': 8936, 'enc1_out': 600, 'enc2_in': 600, 'enc2_out': 400, 'dec1_in': 200, 'dec1_out': 600, 'dec2_in': 600} params_trainer = {'seed': 42, 'normalize_gradients':...
.filterwarnings('ignore:Ignoring n_components with whiten=False.') .parametrize('whiten, n_components, expected_mixing_shape', [('arbitrary-variance', 5, (10, 5)), ('arbitrary-variance', 10, (10, 10)), ('unit-variance', 5, (10, 5)), ('unit-variance', 10, (10, 10)), (False, 5, (10, 10)), (False, 10, (10, 10))]) def test...
def _verify_range(msg, x, vmin, vmax, dtype): assert_equal(x[0], vmin) assert_equal(x[(- 1)], vmax) assert (x.dtype == dtype)
def read_json(filename): with open(filename) as filepoint: data = json.load(filepoint) return data
class TFAutoModelWithLMHead(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def retokenize(sent, tokenizer, subword='##'): tokens = [] abs_char_offsets = [] for i in range(len(sent.words)): toks = tokenizer.tokenize(sent.words[i]) offsets = [sent.abs_char_offsets[i]] for w in toks[0:(- 1)]: offsets.append((len((w if (w[:len(subword)] != subword) ...
class SelectedAtoms(ProcessingPlasmaProperty): outputs = ('selected_atoms',) def calculate(self, abundance): return abundance.index
class MultiDatasetFromFolder(data.Dataset): def __init__(self, image_dir, nFrames, upscale_factor, data_augmentation, file_list, other_dataset, patch_size, future_frame, transform=None): super(MultiDatasetFromFolder, self).__init__() self.nFrames = nFrames self.upscale_factor = upscale_facto...
def exact_match(anaphor, antecedent): match = (anaphor.attributes['tokens_as_lowercase_string'] == antecedent.attributes['tokens_as_lowercase_string']) return ('exact_match', match)
class TrainerState(): epoch: Optional[float] = None global_step: int = 0 max_steps: int = 0 num_train_epochs: int = 0 total_flos: float = 0 log_history: List[Dict[(str, float)]] = None best_metric: Optional[float] = None best_model_checkpoint: Optional[str] = None is_local_process_ze...
def test_initialize_base_classifier(): _bm = BaseBoostedRelationalModel() assert (_bm.target == 'None') assert (_bm.n_estimators == 10)
def mean_pool(input_tensor, sequence_length=None): with tf.name_scope('mean_pool'): input_tensor_sum = tf.reduce_sum(input_tensor, axis=(- 2)) if (sequence_length is None): sequence_length = tf.shape(input_tensor)[(- 2)] expanded_sequence_length = (tf.cast(tf.expand_dims(sequence...
def fullname(o): module = o.__class__.__module__ if ((module is None) or (module == str.__class__.__module__)): return o.__class__.__name__ else: return ((module + '.') + o.__class__.__name__)
def test_1d_ok(): nums = np.arange(7) filtered = gaussian(nums, preserve_range=True) assert np.all((filtered > 0.1))
.service(data={'title': 'Forbidden', 'status': 403, 'detail': 'FORBIDDEN!'}, status=403, method='GET', path=re.compile('/cli/projects/.*/')) .openapi_version('3.0') def test_forbidden(cli, schema_url, service): result = cli.run('my-api', f'--schemathesis-io-token={service.token}', f'--schemathesis-io-url={service.b...