code
stringlengths
101
5.91M
def write_requirements(cmd, basename, filename): dist = cmd.distribution data = six.StringIO() _write_requirements(data, dist.install_requires) extras_require = (dist.extras_require or {}) for extra in sorted(extras_require): data.write('\n[{extra}]\n'.format(**vars())) _write_requir...
def lift(x): try: return x.lift() except AttributeError: return PowerSeriesRing(Rationals(), 't')(x.list(), x.prec())
def build_configs_and_run(config_files: Sequence[str], executable: Optional[str]=None, kwargs: Dict[(str, Any)]={}) -> Tuple[(List[Dict[(str, Any)]], Callable)]: configs = [] executable = None for config_file in config_files: (seml_config, _, experiment_config) = read_config(config_file) if ...
def spyx_tmp(): global _spyx_tmp if _spyx_tmp: return _spyx_tmp d = tempfile.TemporaryDirectory() _spyx_tmp = os.path.join(d.name, 'spyx') atexit.register((lambda : d.cleanup())) return _spyx_tmp
def check_existed(sample, java_func_dir): couple = sample['url'].split('/')[(- 1)].split('#') class_name = couple[0].split('.java')[0] start = couple[1].split('-')[0].replace('L', '') end = couple[1].split('-')[1].replace('L', '') if ('repo' in sample.keys()): project = sample['repo'].replac...
def build_lr_scheduler(optimizer, optimizer_config, total_step): optimizer_type = optimizer_config.type config = optimizer_config if (optimizer_type == 'rms_prop_optimizer'): lr_scheduler = _create_learning_rate_scheduler(config, optimizer, total_step=total_step) elif (optimizer_type == 'momentu...
def print_epoch_result(train_result, valid_result, epoch, max_epochs): epoch_len = len(str(max_epochs)) (seg_loss, seg_dice) = (train_result['seg_loss'], train_result['seg_dice']) (val_dice, val_loss, val_lge_dice, val_lge_loss, test_lge_dice, test_lge_loss, valid_vert_loss) = (valid_result['val_dice'], val...
class SelfAttention(SelfAttentionBase): def __call__(self, source: Tensor, *, axis: Dim) -> Tensor: (q, k, v) = self.forward_qkv(source) kv_axis = Dim(None, name=f'{axis.name}-kv') (k, _) = rf.replace_dim(k, in_dim=axis, out_dim=kv_axis) (v, _) = rf.replace_dim(v, in_dim=axis, out_di...
class Swish(nn.Module): def __init__(self, inplace): super(Swish, self).__init__() self.sigmoid = nn.Sigmoid() def forward(self, x): return (x * self.sigmoid(x))
_zero_only def print_config(config: DictConfig, fields: Sequence[str]=('trainer', 'model', 'datamodule', 'train', 'eval', 'callbacks', 'logger', 'seed', 'name'), resolve: bool=True) -> None: style = 'dim' tree = rich.tree.Tree('CONFIG', style=style, guide_style=style) for field in fields: branch = t...
def _config_likelihood(forward_dict): input_dict = {} input_dict['conditions'] = forward_dict['prior_draws'].astype(np.float32) input_dict['observables'] = forward_dict['sim_data'].astype(np.float32) return input_dict
class DOMValueEmbeddings(SimpleEmbeddings): def __init__(self, embed_dim): values = DOMValueVocab() embed_matrix = np.random.uniform((- np.sqrt((3.0 / embed_dim))), np.sqrt((3.0 / embed_dim)), size=(len(values), embed_dim)).astype(np.float32) super(DOMValueEmbeddings, self).__init__(embed_ma...
def user_config_dir(appname, roaming=True): if WINDOWS: path = user_data_dir(appname, roaming=roaming) elif (sys.platform == 'darwin'): path = user_data_dir(appname) else: path = os.getenv('XDG_CONFIG_HOME', expanduser('~/.config')) path = os.path.join(path, appname) retu...
.parametrize('return_fitted_val', [False, True], ids=['no_fitval', 'do_fitval']) .parametrize('do_grad', [False, True], ids=['no_grad', 'do_grad']) def test_jax_jit_enable_stitching(caplog, do_grad, return_fitted_val): pyhf.set_backend('jax', 'scipy', precision='64b') pdf = pyhf.simplemodels.uncorrelated_backgr...
def test_cli_example(): with patch_sys_argv_helper(['ti', 'example', 'minimal']) as custom_argv: cli = TaichiMain(test_mode=True) args = cli() assert (args.name == 'minimal') with patch_sys_argv_helper(['ti', 'example', 'minimal.py']) as custom_argv: cli = TaichiMain(test_mode=Tr...
def prepare_onnx_paddings(dim, pad): assert isinstance(dim, int) assert (len(pad) <= (dim * 2)) paddings = (list(pad[:]) + ([0] * ((dim * 2) - len(pad)))) paddings = (paddings[(- 2)::(- 2)] + paddings[(- 1)::(- 2)]) assert (len(paddings) == (dim * 2)) return paddings
def get_doc(infile: TextIO): res = [] for line in infile: if (not line.strip()): (yield res) res = [] res.append(line) (yield res)
def gen_classifier_loader(name, d): def classifier_loader(): TFHider() gpus_list = TFHider.tf.config.experimental.list_physical_devices('GPU') TFHider.tf.config.experimental.set_visible_devices(gpus_list[torch.cuda.current_device()], 'GPU') loaded = TFHider.tf.saved_model.load(('/dat...
class CheckDummiesTester(unittest.TestCase): def test_find_backend(self): no_backend = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")') self.assertIsNone(no_backend) simple_backend = find_backend(' if not is_tokenizers_available():') self.assert...
def test_toarrow_BitMaskedArray(): content = ak.highlevel.Array(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']).layout bitmask = ak.index.IndexU8(np.array([40, 34], dtype=np.uint8)) array = ak.contents.BitMaskedArray(bitmask, content, False, 9, False) assert (array.to_arrow().t...
class _SuiteFilter(object): def __init__(self, name): self._name = name def matches(self, bench): if (self._name == '*'): return True return (bench.suite.name == self._name)
class TestWeightedMedoid(): def test_simple_example_weighted(self): A = torch.tensor([[0.5, 0.3, 0, 0.4], [0.3, 0.2, 0, 0], [0, 0, 0.9, 0.3], [0.4, 0, 0.4, 0.4]], dtype=torch.float32) x = torch.tensor([[(- 10), 10, 10], [(- 1), 1, 1], [0, 0, 0], [10, (- 10), (- 10)]], dtype=torch.float32) me...
def _impl(array, file, line_delimited, num_indent_spaces, num_readability_spaces, nan_string, posinf_string, neginf_string, complex_record_fields, convert_bytes, convert_other): if ((array is None) or isinstance(array, (bool, str, bytes, Number))): out = ak.operations.from_iter([array], highlevel=False) ...
class SimpleFeaturePyramid(nn.Module): def __init__(self, in_channels, out_channels, scale_factors, norm='LN'): super(SimpleFeaturePyramid, self).__init__() self.scale_factors = scale_factors dim = in_channels self.stages = [] use_bias = (norm == '') for (idx, scale) ...
def rule_help(info_finding): descr_short = info_finding.get('descr_short') descr_long = info_finding.get('descr_long') return (descr_long if descr_long else (descr_short if descr_short else ''))
class SourceDistribution(AbstractDistribution): def get_pkg_resources_distribution(self): return self.req.get_dist() def prepare_distribution_metadata(self, finder, build_isolation): self.req.load_pyproject_toml() should_isolate = (self.req.use_pep517 and build_isolation) if shou...
def global_train_once(global_model, client_data_loaders, test_loader, FL_params): device = torch.device(('cuda' if (FL_params.use_gpu * FL_params.cuda_state) else 'cpu')) device_cpu = torch.device('cpu') client_models = [] client_sgds = [] for ii in range(FL_params.N_client): client_models.a...
class GLU(nn.Module): def __init__(self, dim=(- 1), activation='sigmoid'): super().__init__() assert (not activation.startswith('glu')) self.dim = dim self.activation_fn = Activation(activation) def forward(self, x): (x, g) = torch.split(x, (x.size(self.dim) // 2), dim=se...
def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_m...
class VGGBlock(torch.nn.Module): def __init__(self, in_channels, out_channels, conv_kernel_size, pooling_kernel_size, num_conv_layers, input_dim, conv_stride=1, padding=None, layer_norm=False): assert (input_dim is not None), 'Need input_dim for LayerNorm and infer_conv_output_dim' super(VGGBlock, s...
def metrics(X, T, Ns=[2, 5, 10, 20, 30], metrics=['prec', 'recall', 'map', 'ndcg']): n_users = float(len(T)) N_pos = len(Ns) funcs = {'prec': PRECISION, 'recall': RECALL, 'map': MAP, 'ndcg': NDCG} res = {} for m in metrics: re = [] for n in Ns: re.append(0.0) res[...
class graphTypeSub(supermod.graphType): def __init__(self, node=None): supermod.graphType.__init__(self, node)
def _batch_and_pad(sequences): batch_embeddings = [] batch_mask = [] batch_len = max([len(seq) for seq in sequences]) for seq in sequences: (embeddings, mask) = _pad(seq, batch_len) batch_embeddings.append(embeddings) batch_mask.append(mask) return (np.array(batch_embeddings)...
class distill(): def __init__(self, args, model, teacher): self.args = args self.student = model self.teacher = teacher self.student_layer = self.sampled_layer(args.arch, self.student) self.teacher_layer = self.sampled_layer(args.teacher_arch, self.teacher) def kwargs...
_grad() def generate_images_from_latents(H, all_latents, embedding_weight, generator): all_latents = all_latents.cuda() generator = generator.cuda() for (idx, latents) in tqdm(list(enumerate(torch.split(all_latents, H.batch_size)))): latents_one_hot = latent_ids_to_onehot(latents, H.latent_shape, H....
.torch def test_prediction_bert4rec(item_user_sequential_dataset, train_loader): pred = Bert4RecPredictionDataset(item_user_sequential_dataset, max_sequence_length=5) pred_loader = torch.utils.data.DataLoader(pred) trainer = L.Trainer(max_epochs=1) model = Bert4Rec(tensor_schema=item_user_sequential_dat...
def make_algo(): logger = Logger(log_dir, {}) algo = DDPG(state_shape=STATE_SHAPE, action_shape=ACTION_SHAPE, device=args.device, seed=args.seed, logger=logger) return algo
class PyBacktrace(gdb.Command): def __init__(self): gdb.Command.__init__(self, 'py-bt', gdb.COMMAND_STACK, gdb.COMPLETE_NONE) def invoke(self, args, from_tty): frame = Frame.get_selected_python_frame() if (not frame): print('Unable to locate python frame') return ...
class PLMSSampler(object): def __init__(self, model, schedule='linear', **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if (type(attr) == torch.Tensor): ...
def main_func(): arg_parser = _shell_options() (args, remaining_args) = arg_parser.parse_known_args() cpu_info = get_cpu_info() num_cores = cpu_info['count'] result = {} if (args.command == 'minimize'): result = _minimize_noise(num_cores, args.use_nice, args.use_shielding, args.for_profi...
def make_palette(num_classes): palette = np.zeros((num_classes, 3), dtype=np.uint8) for k in xrange(0, num_classes): label = k i = 0 while label: palette[(k, 0)] |= (((label >> 0) & 1) << (7 - i)) palette[(k, 1)] |= (((label >> 1) & 1) << (7 - i)) pale...
def is_reach_goal(context, goal): context = kw_tokenize(context) if (goal in context): return True for wd in context: if is_candiword(wd): rela = calculate_linsim(wd, goal) if (rela > 0.9): return True return False
def parse_subj_obj(f): (subj_obj, score) = f.split(':') score = float(score) (subj, obj) = subj_obj.split('_') (subj_lemma, subj_pos) = subj.split('#') (obj_lemma, obj_pos) = obj.split('#') return (subj_lemma, subj_pos, obj_lemma, obj_pos, score)
class ReshapeModel(torch.nn.Module): def __init__(self): super(ReshapeModel, self).__init__() def forward(self, x): return torch.reshape(x, [1, (- 1)])
def test_examples_from_cli(app, testdir, cli, base_url, schema_with_examples): schema = schema_with_examples.raw_schema app['config'].update({'schema_data': schema}) schema_file = testdir.makefile('.yaml', schema=yaml.dump(schema)) result = cli.run(str(schema_file), f'--base-url={base_url}', '--hypothes...
def _create_learning_rate_scheduler(optimizer, learning_rate_config, total_step): lr_scheduler = None learning_rate_type = learning_rate_config.type config = learning_rate_config if (learning_rate_type == 'multi_phase'): lr_phases = [] mom_phases = [] for phase_cfg in config.phas...
def split_underscores(tree): assert (not tree.is_leaf()), 'Should never reach a leaf in this code path' if tree.is_preterminal(): return tree children = tree.children new_children = [] for child in children: if child.is_preterminal(): if ('_' not in child.children[0].labe...
class Posets(Category): _method def super_categories(self): return [Sets()] def example(self, choice=None): from sage.categories.examples.posets import FiniteSetsOrderedByInclusion, PositiveIntegersOrderedByDivisibilityFacade if (choice == 'facade'): return PositiveIntege...
class MyModule(): lock = threading.Lock() def __init__(self): g_cpu = torch.Generator() g_cpu.manual_seed(0) self.w = torch.rand((3, 3), requires_grad=True, generator=g_cpu) def forward(self, t1): return torch.mm(self.w, t1) def get_w(self): return self.w
def upload_resource(file_path, oss_obj_name, bucket): resource_oss_url = (' % (bucket.bucket_name, bucket.endpoint, oss_obj_name)) bucket.put_object_from_file(oss_obj_name, file_path) return resource_oss_url
def _is_path(name_or_buffer): return (isinstance(name_or_buffer, str) or ((sys.version_info[0] == 3) and isinstance(name_or_buffer, pathlib.Path)))
def trim_midi(mid_orig, start, end, strict=True): eps = 0.001 mid = deepcopy(mid_orig) for ins in mid.instruments: if strict: ins.notes = [note for note in ins.notes if ((note.start >= start) and (note.end <= end))] else: ins.notes = [note for note in ins.notes if ((n...
def add_wd_without_bias(wd, scope=None): scope = (scope or tf.get_variable_scope().name) variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope) counter = 0 with tf.name_scope('weight_decay'): for var in variables: if (len(var.get_shape().as_list()) <= 1): ...
def p_property_decl(s): pos = s.position() s.next() name = p_ident(s) (doc, body) = p_suite_with_docstring(s, Ctx(level='property'), with_doc_only=True) return Nodes.PropertyNode(pos, name=name, doc=doc, body=body)
(base=10) def plot_semilogy(funcs, *args, **kwds): return plot(funcs, *args, scale='semilogy', **kwds)
class LSTM(RNNBase): def __init__(self, *args, **kwargs): super(LSTM, self).__init__('LSTM', *args, **kwargs) def check_forward_args(self, input: Tensor, hidden: Tuple[(Tensor, Tensor)], batch_sizes: Optional[Tensor]): self.check_input(input, batch_sizes) expected_hidden_size = self.get_...
class GumbelVQ(VQModel): def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, temperature_scheduler_config, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, kl_weight=1e-08, remap=None): z_channels = ddconfig['z_channels'] super().__init__(ddconfig, los...
class _PredictManager(): def __init__(self, predictor: Predictor, input_file: str, output_file: Optional[str], batch_size: int, print_to_console: bool, has_dataset_reader: bool) -> None: self._predictor = predictor self._input_file = input_file if (output_file is not None): self....
def combine_sequences(sequences, axis=(- 1), name=None): with tf.name_scope((name or 'combine_sequences')): shapes = [shape_list(seq) for seq in sequences] sl_list = [shp[axis] for shp in shapes] sl_max = tf.reduce_max(tf.stack(sl_list)) def _get_padding_shape(_shape, _sl, _sl_max, _...
def c4_graph(): G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)]) return G
_connect.numpy.implements('nanargmin') def _nep_18_impl_nanargmin(a, axis=None, out=UNSUPPORTED, *, keepdims=False): return nanargmin(a, axis=axis, keepdims=keepdims)
class Predictor(ABC): if Benchmark.bench_predict: def time_predict(self, *args): self.estimator.predict(self.X) def peakmem_predict(self, *args): self.estimator.predict(self.X) if (Benchmark.base_commit is not None): def track_same_prediction(self, *args):...
def test_count_featurizer(tmp_path: pathlib.Path): time_horizon = TimeHorizon(datetime.timedelta(days=0), datetime.timedelta(days=180)) create_database(tmp_path) database_path = os.path.join(tmp_path, 'target') database = femr.datasets.PatientDatabase(database_path) ontology = database.get_ontology(...
class TestAsLinearOperator(): def setup_method(self): self.cases = [] def make_cases(original, dtype): cases = [] cases.append((matrix(original, dtype=dtype), original)) cases.append((np.array(original, dtype=dtype), original)) cases.append((sparse.csr...
class TestStepwiseStore(TestCase): def test_load(self): self.assertGreater(len(store), 0) self.assertIsNotNone(store.get('gelu', 3))
class AnomalyDetector(): def __init__(self, config: AnomalyDetectionConfig): self.anomaly_detector = factory.get_algorithm('detection', config.algo_name.lower(), config) def fit(self, log_features: pd.DataFrame): return self.anomaly_detector.fit(log_features) def predict(self, log_features: ...
def test_replace_in_file_multiline_old_text(test_file, test_file_path, agent: Agent): old_content = 'This is a multi_line\ntest for testing\nhow well this function\nworks when the input\nis multi-lined' expected_content = 'This is a multi_line\nfile. succeeded test\nis multi-lined' test_file.write(old_conte...
_utils.test() def test_ad_reduce_fwd(): N = 16 x = ti.field(dtype=ti.f32, shape=N) loss = ti.field(dtype=ti.f32, shape=()) ti.root.lazy_dual() def func(): for i in x: loss[None] += (x[i] ** 2) total_loss = 0 for i in range(N): x[i] = i total_loss += (i * i...
def isinf(tensor): if (not isinstance(tensor, torch.Tensor)): raise ValueError('The argument is not a tensor', str(tensor)) return (tensor.abs() == math.inf)
class RegressionTask(SingleOutputTask): __metaclass__ = abc.ABCMeta def __init__(self, config: configure_finetuning.FinetuningConfig, name, tokenizer, min_value, max_value): super(RegressionTask, self).__init__(config, name, tokenizer) self._tokenizer = tokenizer self._min_value = min_va...
def get_plot_config(args): assert (args.log in ['all', 'tb', 'wandb']) return ((args.log in ['all', 'tb']), (args.log in ['all', 'wandb']))
class TruncationOpManagerInference(): def __load_quantizer__(self, qtype, qparams): qtype_name = qtype.rstrip('') quant_params = (qparams[qtype_name] if (qtype_name in qparams) else {}) quantizer = qtypes.__dict__[(qtype_name + '_quantizer')](qtype, quant_params) return (quantizer, q...
('warnings.warn') (sdv, 'iter_entry_points') def test__find_addons_missing_object(entry_points_mock, warning_mock, mock_sdv): bad_entry_point = Mock() bad_entry_point.name = 'sdv.submodule:missing_object.new_method' entry_points_mock.return_value = [bad_entry_point] msg = "Failed to set 'sdv.submodule:m...
class classifier(nn.Module): def __init__(self, feadim, classnum): super(classifier, self).__init__() self.fc1 = nn.Linear(feadim, (feadim // 2)) self.fc2 = nn.Linear((feadim // 2), (feadim // 4)) self.fc3 = nn.Linear((feadim // 4), classnum) self.relu = nn.ReLU() sel...
class MPolynomialIdeal_singular_base_repr(): _field def syzygy_module(self): from sage.libs.singular.function_factory import ff syz = ff.syz from sage.matrix.constructor import matrix S = syz(self) return matrix(self.ring(), S) _gb_standard_options def _groebner_b...
def get_bench_net_lstm(input_var, mask_var, inp_dim, rnn_size, classes): l_in = lasagne.layers.InputLayer(shape=(None, None, inp_dim), input_var=input_var) l_mask = lasagne.layers.InputLayer(shape=(None, None), input_var=mask_var) (batch_size, seq_len, _) = input_var.shape h1f = lasagne.layers.LSTMLayer...
def getRoot(): parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse('/home/user/test.xml', parser) return tree.getroot()
def test_index_no_files(): with tempfile.TemporaryDirectory() as tmpdir: empty_dataset = [] source = SingleShardDocumentSource(empty_dataset) cache = TokenizedDocumentCache.build_or_load(f'{tmpdir}/cache', source, tokenizer, flatten_docs=True, enforce_eos=False, override_resources={'num_cpus...
class EdgeConnect(): def __init__(self, config): self.config = config if (config.MODEL == 1): model_name = 'edge' elif (config.MODEL == 2): model_name = 'inpaint' elif (config.MODEL == 3): model_name = 'edge_inpaint' elif (config.MODEL == 4...
def safety_exit(world, margin, state, flat, control): if np.any(np.isinf(control['cmd_motor_speeds'])): return ExitStatus.INF_VALUE if np.any(np.isnan(control['cmd_motor_speeds'])): return ExitStatus.NAN_VALUE if np.any((np.abs(state['v']) > 100)): return ExitStatus.OVER_SPEED if...
def run(): global pool pool1 = JobPool(2) pool2 = JobPool() if (pool1 != pool2): raise Exception("hmmm, I thought JobPool is 'Singleton'") try: JobPool(4) except Exception as e: print(('As expected, making a new JobPool with a different cpu count failed: %s' % e)) poo...
_duration def slide_out(clip, duration, side): (w, h) = clip.size ts = (clip.duration - duration) pos_dict = {'left': (lambda t: (min(0, (w * ((- (t - ts)) / duration))), 'center')), 'right': (lambda t: (max(0, (w * ((t - ts) / duration))), 'center')), 'top': (lambda t: ('center', min(0, (h * ((- (t - ts)) ...
def dump_model(operation='create', redo=False): create_graph() sess = tf.InteractiveSession() deploy_net_file = 'models/inception_v3/inception_v3_deploy.prototxt' model_file = 'models/inception_v3/inception_v3.caffemodel' net = [] if ((operation == 'create') and ((not os.path.exists(deploy_net_f...
class Parent(StackProtocol): def __init__(self, own: 'Node', keysize: int, keynum: int): super().__init__(own, '') self.upper_protocols = [] self.lower_protocols = [] self.keysize = keysize self.keynum = keynum self.keys = [] self.counter = 0 def init(self...
def model_to_graph_def(model, **kwargs): nets = [model.param_init_net, model.net] return nets_to_graph_def(nets, **kwargs)
def matting_inference(model, img, trimap): cfg = model.cfg device = next(model.parameters()).device keys_to_remove = ['alpha', 'ori_alpha'] for key in keys_to_remove: for pipeline in list(cfg.test_pipeline): if (('key' in pipeline) and (key == pipeline['key'])): cfg.t...
class WordPaths_square_grid(WordPaths_all): def __init__(self, alphabet): d = [(1, 0), (0, 1), ((- 1), 0), (0, (- 1))] super().__init__(alphabet, steps=d) _attribute def _element_classes(self): return {'list': FiniteWordPath_square_grid_list, 'str': FiniteWordPath_square_grid_str, 't...
def add_stderr_logger(level=logging.DEBUG): logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(level) logger.debug('Added a stderr logging handler to lo...
class DualObjectsCategory(CovariantConstructionCategory): _functor_category = 'DualObjects' def _repr_object_names(self): return ('duals of %s' % self.base_category()._repr_object_names())
def all_ids(scene_class): with open(osp.join('./datasets/{}'.format(scene_class), 'id_train.txt'), 'r') as fp: ids_train = [s.strip() for s in fp.readlines() if s] rs.shuffle(ids_train) with open(osp.join('./datasets/{}'.format(scene_class), 'id_test.txt'), 'r') as fp: ids_test = [s.strip() ...
class PytorchRandomCropFlipImagePipeline(BaseImagePipeline): def __init__(self, output_image_size: int, extra_pixels: int=0): super(PytorchRandomCropFlipImagePipeline, self).__init__(output_image_size) self.extra_pixels = extra_pixels self.random_crop = RandomCrop(self.output_image_size) ...
class Softmax(BaseActivation): def __init__(self): super(Softmax, self).__init__('Softmax') def output(signal: np.ndarray) -> np.ndarray: return special.softmax(signal, axis=1) def gradient(signal: np.ndarray, direction: np.ndarray) -> np.ndarray: output = Softmax.output(signal) ...
def bn_self_folding_resblock(x, i, maps, kernel=(3, 3), pad=(1, 1), stride=(1, 1), channel_last=False, name='convblock'): h = x with nn.parameter_scope(name): h = PF.convolution(h, maps, kernel=kernel, pad=pad, stride=stride, channel_last=channel_last, with_bias=False) axes = get_channel_axes(h,...
class LFW(FaceDataset): def __init__(self, root: str, mode: str='train', transform=None) -> None: super().__init__(root, mode, transform) identities = self.read_split_file(root, mode) self.reduce_to_sample_identities(identities) self.num_classes = len(np.unique(self.ids)) pri...
_module() class VQAv2Dataset(MInstrDataset): def __init__(self, *args, has_annotation=True, **kwargs): super().__init__(*args, **kwargs, placeholders=(IMAGE_PLACEHOLDER, QUESTION_PLACEHOLDER)) self.has_annotation = has_annotation def __getitem__(self, index): item = self.get_raw_item(ind...
class Partition12(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]/T5LayerSelfAttention[0]/T5LayerNorm[layer_norm]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]/T5LayerSelfAttention[0]/T5Attention[SelfAttention]/Linear[q]', 'T5ForConditionalGeneration/T5Stack[decoder...
def test_array_constructors(): data = np.arange(1, 7, dtype='int32') for i in range(8): np.testing.assert_array_equal(m.test_array_ctors((10 + i)), data.reshape((3, 2))) np.testing.assert_array_equal(m.test_array_ctors((20 + i)), data.reshape((3, 2))) for i in range(5): np.testing.as...
def argsort(items, key=(lambda x: x), reverse=False): (orig_to_sort, sorted_items) = zip(*sorted(enumerate(items), key=(lambda x: key(x[1])), reverse=reverse)) sort_to_orig = tuple((x[0] for x in sorted(enumerate(orig_to_sort), key=operator.itemgetter(1)))) return (sorted_items, sort_to_orig, orig_to_sort)
class Vocab(): def __init__(self, data_config, save_dir, data_filenames=None): self.data_config = data_config self.save_dir = save_dir self.joint_label_lookup_maps = {} self.reverse_maps = {} self.vocab_maps = {} self.vocab_lookups = None self.oovs = {} ...
def analyze_results(results_dir: str, data_path: str, dormant_unit_threshold: float=0.01): parameter_dir_path = os.path.join(results_dir, 'model_parameters') experiment_indices_file_path = os.path.join(results_dir, 'experiment_indices.npy') class_order_dir_path = os.path.join(results_dir, 'class_order') ...