code
stringlengths
101
5.91M
class ProbMPS(nn.Module): def __init__(self, seq_len: int, input_dim: int, bond_dim: int, complex_params: bool=False, use_bias: bool=False, init_method: str='near_eye', embed_fun: Optional[Callable]=None, domain: Optional[DataDomain]=None) -> None: super().__init__() assert (min(seq_len, input_dim, ...
def compose_fieldmap(rf1, rf2): if (rf1 == None): import pdb pdb.set_trace() (offset1, size1, step1) = rf1 (offset2, size2, step2) = rf2 size = tuple(((((size2c - 1) * step1c) + size1c) for (size1c, step1c, size2c) in zip(size1, step1, size2))) offset = tuple((((offset2c * step1c) + ...
def main(prior_name, name, max_samples, diversity_picker, oracle, w_min): prior_model = model_from_json(prior_name) search_model = model_from_json(prior_name) model_weights_path = os.path.join(script_dir, 'results', name, 'weights.pth') search_model.load(model_weights_path) (samples, weights) = get_...
class JNU(object): num_classes = 4 inputchannel = 1 def __init__(self, data_dir, transfer_task, normlizetype='0-1'): self.data_dir = data_dir self.source_N = transfer_task[0] self.target_N = transfer_task[1] self.normlizetype = normlizetype self.data_transforms = {'tr...
class Scatter(object): def forward(target_gpus, input): input_device = get_input_device(input) streams = None if (input_device == (- 1)): streams = [_get_stream(device) for device in target_gpus] outputs = scatter(input, target_gpus, streams) if (streams is not No...
def in_distance_range_pose(ego_center: np.ndarray, pose: np.ndarray, d_min: float, d_max: float) -> bool: dist = float(np.linalg.norm((pose[0:3] - ego_center[0:3]))) return ((dist > d_min) and (dist < d_max))
class AverageMeter(): def __init__(self, *keys): self.__data = dict() for k in keys: self.__data[k] = [0.0, 0] def add(self, dict): for (k, v) in dict.items(): if (k not in self.__data): self.__data[k] = [0.0, 0] self.__data[k][0] += v ...
def adjust_learning_rate_resnet(optimizer): if (C.get()['epoch'] == 90): return torch.optim.lr_scheduler.MultiStepLR(optimizer, [30, 60, 80]) elif (C.get()['epoch'] == 270): return torch.optim.lr_scheduler.MultiStepLR(optimizer, [90, 180, 240]) elif (C.get()['epoch'] == 300): return ...
class Model(nn.Module): def __init__(self): super().__init__() self.block = Block() self.conv = nn.Conv2d(3, 3, 1)
class InstructionParameter(ModelTypeValidator): valid_types = (complex, int, float, str, numpy.integer, numpy.float, sympy.Basic, sympy.Symbol, list, numpy.ndarray) default_error_messages = {'invalid': '{input} cannot be parsed as a parameter.', 'format': '"{input}" cannot be formatted as a parameter.'} def...
class Recorder(): def __init__(self, env, directory, save_stats=True, save_video=True, save_episode=True, video_size=(512, 512)): if (directory and save_stats): env = StatsRecorder(env, directory) if (directory and save_video): env = VideoRecorder(env, directory, video_size) ...
class Item(): mode: str split: str scene: str scan: str stem: str def get_split_file(cls, mode: str, split: str) -> Path: return ((PATHS['diode'] / 'data_list') / f'{mode}_{split}.csv') def load_split(cls, mode: str, split: str) -> list['Item']: lines = io.readlines(cls.get_s...
class TFDPRPretrainedQuestionEncoder(): def __init__(self, *args, **kwargs): requires_tf(self)
def dict_of_list__to__list_of_dicts(dict, n_items): new_dicts = [{} for _ in range(n_items)] for (key, values) in dict.items(): for i in range(n_items): new_dicts[i][key] = values[i] return new_dicts
class exkp(nn.Module): def __init__(self, n, nstack, dims, modules, heads, pre=None, cnv_dim=256, make_tl_layer=None, make_br_layer=None, make_cnv_layer=make_cnv_layer, make_heat_layer=make_kp_layer, make_tag_layer=make_kp_layer, make_regr_layer=make_kp_layer, make_poly_layer=make_poly_layer, make_up_layer=make_lay...
(before=[init], after=[post]) def con_train_wbcluster(): USR.set('dataset', 'data/wb_aligned/') USR.set('decoder', 'crf') USR.set('L', '8') USR.set('layers', '2') USR.set('min_epochs', '8') USR.set('weight_decay', '0.0') USR.set('posterior_reg', '1') command = ('%(S_python_itrptr)s %(S_p...
class Kadid10k(data.Dataset): def __init__(self, root, index, transform, patch_num): refpath = os.path.join(root, 'reference_images') refname = getTIDFileName(refpath, '.png.PNG') imgnames = [] target = [] refnames_all = [] csv_file = os.path.join(root, 'dmos.csv') ...
class ChineseBertDataset(Dataset): def __init__(self, data_path, chinese_bert_path, max_length: int=512): super().__init__() self.vocab_file = os.path.join(chinese_bert_path, 'vocab.txt') self.config_path = os.path.join(chinese_bert_path, 'config') self.data_path = data_path ...
_task('speech_to_text') class SpeechToTextTask(LegacyFairseqTask): def add_args(parser): parser.add_argument('data', help='manifest root path') parser.add_argument('--config-yaml', type=str, default='config.yaml', help='Configuration YAML filename (under manifest root)') parser.add_argument(...
class BertModelTest(unittest.TestCase): class BertModelTester(object): def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hid...
def load_latest_parameters(folder): yaml_file = get_latest_parameter_file(folder) logging.info('using {}'.format(yaml_file)) param = load_from_yaml_file(yaml_file) return param
_torch class ScheduleInitTest(unittest.TestCase): m = (torch.nn.Linear(50, 50) if is_torch_available() else None) optimizer = (AdamW(m.parameters(), lr=10.0) if is_torch_available() else None) num_steps = 10 def assertListAlmostEqual(self, list1, list2, tol): self.assertEqual(len(list1), len(lis...
def train(args): global local_rank data_module = GPTDataModule(data_dir=args.data_dir, batch_size=args.batch_size, block_size=args.block_size) model = Nanogpt(args, ctx=None) checkpoint_callback = pl.callbacks.ModelCheckpoint(save_top_k=1, verbose=True, every_n_train_steps=1000, monitor='train_loss', mo...
def voxelized_pointcloud(model, kdtree, res): occupancies = np.zeros((res ** 3), dtype=np.int8) (_, idx) = kdtree.query(model) occupancies[idx] = 1 compressed_occupancies = np.packbits(occupancies) return compressed_occupancies
class RemoteNXDOManagerClient(NXDOManager): def __init__(self, n_players, port=4545, remote_server_host='127.0.0.1'): self._stub = NXDOManagerStub(channel=grpc.insecure_channel(target=f'{remote_server_host}:{port}', options=[('grpc.max_send_message_length', GRPC_MAX_MESSAGE_LENGTH), ('grpc.max_receive_messa...
def _make_model(args, device): logger.info(f'Using {args.model_type} Model ......') logger.info(f'Use {args.smooth_loss} Smooth Loss') logger.info(f'Use {args.smooth_mask} Smooth Mask') if (args.model_type == 'mask_raft'): model = mask_RAFT(args.smooth_loss, args.smooth_mask, args.semantic_loss,...
def query_task_status(task_id, db_path): res = None if os.path.isfile(db_path): conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute('select status, result, q_model_path from task where id=?', (task_id,)) res = cursor.fetchone() cursor.close() con...
def _setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True
def view_optimized_epoch_diff_of_models(acc_threshold): model_diffs = [] for model in model_names: output_dict = analyze_hp_grid_data(model=model, acc_threshold=acc_threshold) epoch_diff = (output_dict['avg_std_epoch'] - output_dict['avg_new_epoch']) model_diffs.append(epoch_diff) pl...
def dynpEnsemble(cost, data, num_agg_func, true_cp=true_cp): predicted_cp = [] for dataset in data: stsc = StandardScaler() signal = stsc.fit_transform(dataset) algo = rpt.DynpEnsembling(custom_cost=cost, jump=1, ensembling=num_agg_func) single_predicted_cp = pd.Series(data=0, in...
def GetCommandOutput(command): f = os.popen(command, 'r') lines = [line.strip() for line in f.readlines()] f.close() return lines
class KGProcessor(DataProcessor): def __init__(self, data_args, tokenizer, is_world_master, must_load=False): self.data_dir = data_args.data_dir self.data_split = data_args.data_split self.rank = data_args.rank self.num_split = data_args.num_split self.no_mid = data_args.no_m...
def calc_mean_invstddev(feature): if (len(feature.size()) != 2): raise ValueError('We expect the input feature to be 2-D tensor') mean = feature.mean(0) var = feature.var(0) eps = 1e-08 if (var < eps).any(): return (mean, (1.0 / (torch.sqrt(var) + eps))) return (mean, (1.0 / torc...
def get_top_level_modules(num_levels=1): mod_dir = Path(import_mod('fastai').__file__).parent filtered_n = filter((lambda x: (x.count('.') <= num_levels)), get_module_names(mod_dir)) return sorted(filtered_n, key=(lambda s: s.count('.')), reverse=True)
def data_prep(data_path, dataset='MNIST', size=10000): if (dataset == 'MNIST'): X = np.load((data_path + '/mnist_images.npy'), allow_pickle=True).reshape(70000, (28 * 28)) labels = np.load((data_path + '/mnist_labels.npy'), allow_pickle=True) elif (dataset == 'FMNIST'): X = np.load((data...
def get_dict_from_yaml(path): assert os.path.exists(path), f'{path} must exists!' import yaml with open(path, 'r') as f: opt = yaml.load(f) return opt
class CUB200(Dataset): def __init__(self, root='./', train=True, index_path=None, index=None, base_sess=None): self.root = os.path.expanduser(root) self.train = train self._pre_operate(self.root) if train: self.transform = transforms.Compose([transforms.Resize(256), trans...
def information_process(dataset, windowSize1, windowSize2, perclass, batch_size, iteration, K, add_info, Each_class_acc, margin): res = [] for i in range(len(np.mean(Each_class_acc, 0))): str_ = ((str(('%.2f' % np.mean(Each_class_acc, 0)[i])) + '+-') + str(('%.2f' % np.std(Each_class_acc, 0)[i]))) ...
def preprocess_gsm8k(path): train = _preprocess_gsm8k(os.path.join(path, 'train.jsonl')) test = _preprocess_gsm8k(os.path.join(path, 'test.jsonl')) print('GSM8K Train: {}'.format(len(train))) print('GSM8K Test: {}'.format(len(test))) return (train + test)
class TimestepDropout(Dropout): def __init__(self, rate, **kwargs): super(TimestepDropout, self).__init__(rate, **kwargs) self.input_spec = InputSpec(ndim=3) def _get_noise_shape(self, inputs): input_shape = K.shape(inputs) noise_shape = (input_shape[0], input_shape[1], 1) ...
class PatchEncoder(layers.Layer): def __init__(self, num_patches, projection_dim): super().__init__() self.num_patches = num_patches self.projection = layers.Dense(units=projection_dim) self.position_embedding = layers.Embedding(input_dim=num_patches, output_dim=projection_dim) d...
def batting_stats_range(start_dt: Optional[str]=None, end_dt: Optional[str]=None) -> pd.DataFrame: (start_dt_date, end_dt_date) = sanitize_date_range(start_dt, end_dt) if (start_dt_date.year < 2008): raise ValueError('Year must be 2008 or later') if (end_dt_date.year < 2008): raise ValueErro...
def check_box_4c_format(input_data): if isinstance(input_data, np.ndarray): if ((input_data.ndim > 2) or (input_data.shape[(- 1)] != 10)): raise TypeError('Given input does not have valid number of attributes. Should be N x 10 for box_4c.') elif isinstance(input_data, tf.Tensor): if ...
class Tokenizer(): def __init__(self, tok_func: Callable=SpacyTokenizer, lang: str='en', pre_rules: Optional[ListRules]=None, post_rules: Optional[ListRules]=None, special_cases: Optional[Collection[str]]=None, n_cpus: Optional[int]=None): (self.tok_func, self.lang, self.special_cases) = (tok_func, lang, sp...
.script_launch_mode('subprocess') def test_training_3d_1class_single_channel_with_data_augmentation(download_functional_test_files, script_runner): file_config = os.path.join(__data_testing_dir__, 'automate_training_config.json') context = imed_config_manager.ConfigurationManager(file_config).get_config() c...
class SupplyGatherDiscreteEasySingleTargetVision(SupplyGatherDiscreteSingleTarget): def __init__(self, env_config: EnvContext): super().__init__(env_config) def _compute_reward(self, state, action): reward = 0 if (self.running_steps == 1): return reward if (not self.g...
def audio_features(filename): hop_length = 512 n_fft = 2048 (y, sr) = librosa.load(filename) duration = float(librosa.core.get_duration(y)) (tempo, beat_frames) = librosa.beat.beat_track(y=y, sr=sr) beat_times = librosa.frames_to_time(beat_frames, sr=sr) (y_harmonic, y_percussive) = librosa....
def quaddobl_real_sweep(pols, sols, par='s', start=0.0, target=1.0): from phcpy.interface import store_quaddobl_solutions as storesols from phcpy.interface import store_quaddobl_system as storesys nvar = (len(pols) + 1) storesys(pols, nbvar=nvar) storesols(nvar, sols) from phcpy.interface import...
class ExplanationJSONDecoder(JSONDecoder): def __init__(self, *args, **kwargs): JSONDecoder.__init__(self, *args, object_hook=self.object_hook, **kwargs) def object_hook(self, obj): if ('_type' not in obj): return obj _type = obj['_type'] if (_type == 'array'): ...
def parse_sim(): parser = argparse.ArgumentParser(description='') parser.add_argument('--dataset', type=str, default='TCL', help='Dataset to run experiments. Should be TCL or IMCA') parser.add_argument('--method', type=str, default='icebeem', help='Method to employ. Should be TCL, iVAE or ICE-BeeM') par...
def log_sum_exp(x, axis=1): m = T.max(x, axis=axis) return (m + T.log(T.sum(T.exp((x - m.dimshuffle(0, 'x'))), axis=axis)))
def rename_state_dict_key(k): for (pegasus_name, hf_name) in PATTERNS: k = k.replace(pegasus_name, hf_name) return k
class RagTokenForGeneration(): def __init__(self, *args, **kwargs): requires_pytorch(self)
def hash_prepare_optimize(optimize): cls = optimize.__class__ try: h = _HASH_OPTIMIZE_PREPARERS[cls] except KeyError: if isinstance(optimize, list): h = _HASH_OPTIMIZE_PREPARERS[cls] = tuple else: h = _HASH_OPTIMIZE_PREPARERS[cls] = identity return h(optim...
def tree_transpose(list_of_trees: Sequence[T]) -> T: return jax.tree_util.tree_map((lambda *xs: jnp.stack(xs, axis=0)), *list_of_trees)
def convert_modelAtmosphere(**kwargs): modelatm = kwargs.pop('modelatm', None) if (not (modelatm is None)): if (isinstance(modelatm, str) and os.path.exists(modelatm)): modelfilename = modelatm elif isinstance(modelatm, str): raise ValueError('modelatm= input is a non-exi...
def model_parallel_cuda_manual_seed(seed, group='tensor'): offset = (seed + 2718) tensor_model_parallel_seed = (offset + parallel_group_size(group)) data_parallel_seed = seed _CUDA_RNG_STATE_TRACKER.reset() torch.cuda.manual_seed(data_parallel_seed) _CUDA_RNG_STATE_TRACKER.add(_MODEL_PARALLEL_RN...
def output_csv(path, subsets, write): (success, _, task_fail, err_fail) = subsets (success_train_len, success_val_len, success_test_len) = map(len, success) (failure_train_len, failure_val_len, failure_test_len) = map(len, task_fail) (error_train_len, error_val_len, error_test_len) = map(len, err_fail) ...
class LukeForEntityPairClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_records_by_date(start_date, end_date=None): base_url = ' params = {'verb': 'ListRecords', 'metadataPrefix': 'arXiv', 'from': start_date} if end_date: params['until'] = end_date result = {} while True: r = requests.get(base_url, params=params) print('Fetching', r.url) ...
class Choice(Spec): def __init__(self, choices): self._choices = choices def get(self, x): if (x in self._choices): return x raise ValueError('{!r} is not in {!r}'.format(x, self._choices)) def __repr__(self): return 'Choice({!r})'.format(self._choices) def __...
def init(args, model, dummyInput): (dir, writer) = setOutputDirAndWriter(args, model.name) configLayers(model, dummyInput) showArchAsTable(model) print('Output dir: ', dir) raw_flags = sys.argv[1:] saveFlags(dir, raw_flags) saveArchAsTableToReport(model, (dir + '/report.txt')) return (di...
def clip_loss(similarity: torch.Tensor, sentence_sim=None, type_loss='clip') -> torch.Tensor: if ((sentence_sim is not None) and (type_loss == 'weighted_clip')): text_loss = weighted_loss(similarity, sentence_sim) audio_loss = weighted_loss(similarity.T, sentence_sim) else: text_loss = c...
class RunningCellMaskingGenerator(): def __init__(self, input_size, mask_ratio=0.5): (self.frames, self.height, self.width) = input_size self.mask_ratio = mask_ratio num_masks_per_cell = int((4 * self.mask_ratio)) assert (0 < num_masks_per_cell < 4) num_patches_per_cell = (4 ...
class SoundStreamAttentionEncoder(nn.Module): def __init__(self, input_channels: int, hidden_channels: int, output_channels: int, **kwargs): super().__init__() self.encoder = SoundStreamEncoder(input_channels, hidden_channels, output_channels, **kwargs) self.pooling = AttentionPooling(output...
def load_snlp(f, tok_path): full_file_name = os.path.join(tok_path, '{}.story.doc.xml'.format(f)) with open(full_file_name) as fobj: xmlstr = fobj.read() tree = etree.parse(full_file_name) root = tree.getroot() doc_id = root.findall('./document/docId')[0].text corefrences = root.findall(...
def get_optimization_params(): return {'finetune_layer': 'pre_logits', 'initial_learning_rate': 0.01, 'momentum': 0.9, 'lr_decay_factor': 0.1, 'decay_steps': (10, 20, 30), 'max_steps': 10, 'warmup_steps': 0, 'tpu_name': None}
def test_deterministic_numpy(): deterministic.set_seed(22) rand_tensor = np.random.rand(5, 5) deterministic_tensor = np.array([[0., 0., 0., 0.859182, 0.], [0., 0., 0., 0., 0.], [0., 0.5612037, 0., 0.7451003, 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) assert np.allclose(rand_tensor, deterministic_...
def example(): with habitat.Env(config=habitat.get_config('configs/tasks/pointnav.yaml')) as env: print('Environment creation successful') observations = env.reset() print('Agent stepping around inside environment.') count_steps = 0 while (not env.episode_over): o...
def test_constantbeta_selfconsist_dehnencore_rmin_inbounds(setup_constantbeta_dfs_selfconsist): if WIN32: return None pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15) twobetas = [(- 1)] constantbeta_dfs_selfconsist = setup_constantbeta_dfs_selfconsist rmin = 0.5 for (twobeta...
class QLinear(nn.Linear): def __init__(self, in_features, out_features, bias=True, num_bits=8, num_bits_weight=8, num_bits_grad=None, perC=True, biprecision=False, measure=False, cal_qparams=False): super(QLinear, self).__init__(in_features, out_features, bias) self.num_bits = num_bits self....
_torch_or_tf class QuestionAnsweringArgumentHandlerTests(unittest.TestCase): def test_argument_handler(self): qa = QuestionAnsweringArgumentHandler() Q = 'Where was HuggingFace founded ?' C = 'HuggingFace was founded in Paris' normalized = qa(Q, C) self.assertEqual(type(norma...
def create_exp_dir(path, scripts_to_save=None, dict=None, options=None): if (not os.path.exists(path)): os.mkdir(path) else: shutil.rmtree(path) os.mkdir(path) print('Experiment dir : {}'.format(path)) if (scripts_to_save is not None): if (not os.path.exists(os.path.join(...
def run_test(cfg, model, distributed): if distributed: model = model.module torch.cuda.empty_cache() output_folders = ([None] * len(cfg.DATASETS.TEST)) dataset_names = cfg.DATASETS.TEST if cfg.OUTPUT_DIR: for (idx, dataset_name) in enumerate(dataset_names): output_folder ...
class QuantitativeDataFrame(): def __init__(self, dataframe): if (type(dataframe) != pandas.DataFrame): raise Exception('type of dataframe must be pandas.dataframe') self.__dataframe = dataframe self.__preprocessed_columns = self.__preprocess_columns(dataframe) self.__lit...
def register_annotations(line_: str) -> None: line_ = line_.strip() usage = 'Usage: %flow register_annotations <directory_or_file>' if os.path.isdir(line_): modules = register_annotations_directory(line_) elif os.path.isfile(line_): modules = register_annotations_file(line_) else: ...
def load_configs(ex_dir): configs = [] run_nums = get_run_nums(ex_dir) for run_num in run_nums: loc = ((ex_dir + '/') + run_num) try: configs.append(extract_config(loc)) except: warnings.warn('Cannot load config in {}. Consider deleting.'.format(loc), Warning)...
class Recipe100k(BaseData): def __init__(self, data_root: Optional[str]=None) -> None: super().__init__('recipe-100k-v2', data_root) self._content = {'num_classes': 8, 'num_vertices': 101585, 'num_edges': 12387, 'dim_features': 2254, 'features': {'upon': [{'filename': 'features.pkl', 'md5': '4fdd76c...
def get_brats_regions(): regions = {'whole tumor': (1, 2, 3), 'tumor core': (2, 3), 'enhancing tumor': (3,)} return regions
def test_dense_matrix_from_nested_dictionary_square(): d = {'a': {'b': 10}, 'b': {'c': 20}} (X, rows, columns) = dense_matrix_from_nested_dictionary(d, square_result=True) eq_(rows, ['a', 'b', 'c']) eq_(columns, ['a', 'b', 'c']) assert np.isnan(X[(0, 0)]) eq_(X[(0, 1)], 10) assert np.isnan(X...
def extract_tags(module): output = [] for i in dir(module): if (i.startswith('_') or (not isinstance(getattr(module, i), str))): continue output.append(i) return output
class KerasONNXRuntimeQuantization(BaseONNXRuntimeQuantization): def __init__(self, framework='onnxrt_qlinear', **kwargs): kwargs['framework'] = framework self.session_options = kwargs.pop('onnxruntime_session_options', None) super().__init__(**kwargs) self._inc_metric_cls = KerasONN...
class ToTensor_with_RandomZoom(object): def __init__(self, ratio=1): self.ratio = ratio def __call__(self, sample): (image, depth) = (sample['image'], sample['depth']) original_size = image.size applied_zoom = random.uniform(1, self.ratio) (image, depth) = self.zoom(image...
class SampleList(OrderedDict): _TENSOR_FIELD_ = '_tensor_field' def __init__(self, samples=[]): super().__init__(self) if (len(samples) == 0): return if self._check_and_load_dict(samples): return if self._check_and_load_tuple(samples): return ...
def comp_sent_ora(single_file, max_edu_num, beam, path_doc, path_abs, path_write_data): doc_files = os.listdir(path_doc) f_docs = [f for f in doc_files if f.endswith('.doc.merge')] abs_files = os.listdir(path_abs) f_abss = [f for f in abs_files if f.endswith('.abs.merge')] assert (len(f_docs) == len...
class AugInput(): def transform(self, tfm: Transform) -> None: raise NotImplementedError def apply_augmentations(self, augmentations: List[Union[(Augmentation, Transform)]]) -> TransformList: tfms = [] for aug in augmentations: if isinstance(aug, Augmentation): ...
def test_digits_lazy_sparse(): model = MaxCoverageSelection(100, optimizer='lazy') model.fit(X_digits_sparse) assert_array_equal(model.ranking[:3], digits_ranking[:3]) assert_array_almost_equal(model.gains[:3], digits_gains[:3], 4) assert_array_almost_equal(model.subset, X_digits_sparse[model.rankin...
def eval_data_collator(dataset: Dataset, batch_size: int): for i in range((len(dataset) // batch_size)): batch = dataset[(i * batch_size):((i + 1) * batch_size)] batch = {k: np.array(v) for (k, v) in batch.items()} batch = shard(batch) (yield batch)
class ResnetEncoder(nn.Module): def __init__(self, num_layers, pretrained, num_input_images=1): super().__init__() if (num_layers not in RESNETS): raise ValueError(f'{num_layers} is not a valid number of resnet layers') self.encoder = RESNETS[num_layers](pretrained) self....
class SomeOf(BaseCompose): def __init__(self, num_transforms: (int or tuple), transforms, p: float=1.0): super().__init__(transforms, p) self.transform_indexes = [] self.num_transforms = num_transforms self.should_apply = True def randomize_parameters(self, *args, **kwargs): ...
_measure class CorrectAnswer(Measure): def __init__(self, dataset, *args: Any, **kwargs: Any): self._dataset = dataset super().__init__(**kwargs) def _get_uuid(self, *args: Any, **kwargs: Any) -> str: return 'correct_answer' def reset_metric(self, episode, *args: Any, **kwargs: Any):...
def test_rotation_encoding(): test_add_sub_angles(1, 64) test_add_sub_angles(30, 64) test_add_sub_angles(60, 64) test_add_sub_angles(90, 64) test_add_sub_angles(100, 64) test_add_sub_angles(150, 64) test_add_sub_angles(180, 64) test_add_sub_angles(340, 64) test_add_sub_angles(1, 32) ...
class RunFunctionTest(unittest.TestCase): def setUpClass(cls): logging.disable(logging.CRITICAL) conf = yaml.load(open(os.path.join('tests', 'data', 'config.yml'), 'r')) conf['default'] = {'feature_extractor': False, 'discriminator': False, 'generator': 'rdn', 'training_set': 'test', 'test_s...
class Classifier(nn.Module): def __init__(self, num_classes, in_planes=512, visualize=False): super(Classifier, self).__init__() self.in_planes = in_planes self.visualize = visualize self.layer5 = self._make_layer(Bottleneck, 512, 2, stride=2) self.layer6 = self._make_layer(B...
def parse(opt_path, is_train=True): with open(opt_path, mode='r') as f: opt = yaml.load(f, Loader=Loader) gpu_list = ','.join((str(x) for x in opt.get('gpu_ids', []))) opt['is_train'] = is_train for (phase, dataset) in opt['datasets'].items(): phase = phase.split('_')[0] dataset[...
class BaseEvaluator(): def __init__(self): pass def evaluate(self, output_image, truth_image): raise NotImplementedError
_charset('heb') class HebCharSet(BaseCharset): _CHARS = u'#$&-<HSTabdghklmnpqrstwyz' _FEATURES = ['']
def main(): parser = argparse.ArgumentParser() parser.add_argument('--train_file', default='data/conceptual_caption/training', type=str, help='The input train corpus.') parser.add_argument('--validation_file', default='data/conceptual_caption/validation', type=str, help='The input train corpus.') parser...
class TrueRiskEstimator(RiskEstimator): def __init__(self, loss, dataset, model): super().__init__(loss) idxs = dataset.test_idxs y_true = dataset.y[idxs] y_pred = model.predict(dataset.x[idxs], idxs=idxs) self.true_loss_vals = self.loss(y_pred, y_true) self.true_loss...
def remove_b_for_nucl_phys(citation_elements): for el in citation_elements: if ((el['type'] == 'JOURNAL') and (el['title'] == 'Nucl.Phys.Proc.Suppl.') and ('volume' in el) and (el['volume'].startswith('b') or el['volume'].startswith('B'))): el['volume'] = el['volume'][1:] return citation_ele...