code
stringlengths
101
5.91M
def main(): import argparse parser = argparse.ArgumentParser(description='The MSD provides data as 4D Niftis with the modality being the first dimension. We think this may be cumbersome for some users and therefore expect 3D niftixs instead, with one file per modality. This utility will convert 4D MSD data into...
_torch class SelectiveCommonTest(unittest.TestCase): all_model_classes = ((MBartForConditionalGeneration,) if is_torch_available() else ()) test_save_load__keys_to_ignore_on_save = ModelTesterMixin.test_save_load__keys_to_ignore_on_save def setUp(self): self.model_tester = ModelTester(self)
def train(epoch, model, optimizer, train_loader, grapher, prefix='train'): return execute_graph(epoch, model, train_loader, grapher, optimizer, prefix='train')
class Radiopaedia(Repository): case_class = RadiopaediaCase cache_class = RadiopaediaMetadataCache external_search_limiter = 'site:radiopaedia.org/cases/' def is_end_of_results(cls, browser): return ('No results were found with these refinement filters applied.' in browser.page_source) def f...
def configure_metadata(metadata_root): metadata = mch() metadata.image_ids = join(metadata_root, 'image_ids.txt') metadata.image_ids_proxy = join(metadata_root, 'image_ids_proxy.txt') metadata.class_labels = join(metadata_root, 'class_labels.txt') metadata.image_sizes = join(metadata_root, 'image_si...
def advtest_fast(model, loader, adversary, args): advDataset = torch.load(args.adv_data_dir) test_loader = torch.utils.data.DataLoader(advDataset, batch_size=4, shuffle=False, num_workers=0, pin_memory=False) model.eval() total_ce = 0 total = 0 top1 = 0 total = 0 top1_clean = 0 top1_...
def parse_to_prune_tf(config, model): modules = {} classifier_head_name = parse_last_linear_tf(model) if (classifier_head_name is not None): config['excluded_op_names'].append(classifier_head_name) if ((config['op_names'] is None) or (config['op_names'] == [])): config['op_names'] = ['.*...
class TestSCEModel(unittest.TestCase): def setUp(self) -> None: self.trunk_cfg = DictConfig({'_target_': 'eztorch.models.trunks.create_resnet', 'name': 'resnet18', 'num_classes': 0, 'small_input': True}) self.projector_cfg = DictConfig({'_target_': 'eztorch.models.heads.MLPHead', 'input_dim': 512, '...
def _assign_device_option(predict_net: caffe2_pb2.NetDef, init_net: caffe2_pb2.NetDef, tensor_inputs: List[torch.Tensor]): def _get_device_type(torch_tensor): assert (torch_tensor.device.type in ['cpu', 'cuda']) assert (torch_tensor.device.index == 0) return torch_tensor.device.type def ...
def rw_update(new_observation, new_response, current_belief, current_action_probability, learning_rate): action_probability = (1 / (1 + pt.exp((- current_belief)))) error = ((new_response * pt.log(action_probability)) + ((1 - new_response) * pt.log((1 - action_probability)))) transformed_old_value = (1 / (1...
class ToTensor(object): def __init__(self): self.worker = (lambda x: (F.to_tensor(x) * 255)) def __call__(self, img_group): img_group = [self.worker(img) for img in img_group] return torch.stack(img_group, 0)
class RingBuffer(object): def __init__(self, maxlen, shape, dtype='float32'): self.maxlen = maxlen self.start = 0 self.length = 0 self.data = np.zeros(((maxlen,) + shape)).astype(dtype) def __len__(self): return self.length def __getitem__(self, idx): if ((idx...
def create_emitter_tests(out): out = Writer(out) includes = ['handler_test.h', 'yaml-cpp-0.7.0/yaml.h', 'gmock/gmock.h', 'gtest/gtest.h'] for include in includes: out.writeln(('#include "%s"' % include)) out.writeln('') usings = ['::testing::_'] for using in usings: out.writeln((...
class DSpritesTestXPositionGrouped(data_testing_lib.BaseVTABDataTest): def setUp(self): super(DSpritesTestXPositionGrouped, self).setUp(data_wrapper=dsprites.DSpritesData('label_x_position', 15), num_classes=15, expected_num_samples=dict(train=589824, val=73728, trainval=663552, test=73728, train800val200=1...
class TorchDataloader(Dataset): def __init__(self, dataset=None, preprocess=None, transform=None, sampler=None, use_cache=True, steps_per_epoch=None, **kwargs): self.dataset = dataset self.preprocess = preprocess self.steps_per_epoch = steps_per_epoch if ((preprocess is not None) and...
def PrintModelBase(mbIndi): (m, n) = mbIndi.shape for i in xrange(m): for j in xrange(n): if (not np.isnan(mbIndi[(i, j)])): print(('[%d, %d]\t%f' % (i, j, mbIndi[(i, j)]))) print('\n')
class ClusterInfo(): def ip_addr(self): return ray._private.services.get_node_ip_address() def set_cpu_affinity(self, core_list): proclist_str = f"[{','.join([str(i) for i in core_list])}]" os.environ['OMP_NUM_THREADS'] = str(len(core_list)) os.environ['OMP_SCHEDULE'] = 'STATIC' ...
class TestMXNetSymbol(TestCase): def test_symbol(self): config = create_config(log_interval=2, seed=42) estimator = Estimator.from_mxnet(config=config, model_creator=get_model, validation_metrics_creator=get_metrics, eval_metrics_creator=get_metrics) estimator.fit(get_train_data_iter, valida...
def validate_minibatch_size_str(minibatch_size_str): if (not isinstance(minibatch_size_str, str)): return False a = minibatch_size_str.split('/') assert (len(a) != 0) for elem in a: b = elem.split('=') if (len(b) != 2): if ((len(a) == 1) and (len(b) == 1)): ...
class HighResolutionNet(nn.Module): def __init__(self, norm_layer=nn.BatchNorm2d): super(HighResolutionNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False) self.bn1 = norm_layer(64) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2,...
class Grayscale(FeatureBase): def dim(self): return 1 def stride(self): return self.pool_stride def extract(self, im: torch.Tensor): return torch.mean(((im / 255) - 0.5), 1, keepdim=True)
class AdaboostRegressor(AutotabularRegressionAlgorithm): def __init__(self, n_estimators, learning_rate, loss, max_depth, random_state=None): self.n_estimators = n_estimators self.learning_rate = learning_rate self.loss = loss self.random_state = random_state self.max_depth =...
class ConvNorm2D(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=None, dilation=1, bias=True, w_init_gain='linear'): super(ConvNorm2D, self).__init__() self.conv = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_...
def softmax(logits, temp=1.0): y = np.minimum(np.exp((logits * temp)), 10000.0) st = (y / np.sum(y)) return st
_loss def cosine_similarity_loss(pred, target, cos_func): assert isinstance(cos_func, nn.Module) assert ((pred.size() == target.size()) and (target.numel() > 0)) loss = cos_func(pred, target, torch.tensor(1, device=pred.device)) return loss
def genCOCOJson(movie_list, img_root, json_path, min_json_path): movie_ids = {} with open(movie_list) as movief: for (idx, line) in enumerate(movief): name = line[:line.find('.')] movie_ids[name] = idx movie_infos = {} for movie_name in tqdm(movie_ids): movie_info...
def gen_load_func(parser, func): def load(args, cmdline): (sub_args, cmdline) = parser.parse_known_args(cmdline) for (k, v) in sub_args.__dict__.items(): args.__dict__[k] = v return (func(**sub_args.__dict__), cmdline) return load
def get_seg_model(cfg, imgnet_pretrained): if ('s' in cfg.MODEL.NAME): model = PIDNet(m=2, n=3, num_classes=cfg.DATASET.NUM_CLASSES, planes=32, ppm_planes=96, head_planes=128, augment=True) elif ('m' in cfg.MODEL.NAME): model = PIDNet(m=2, n=3, num_classes=cfg.DATASET.NUM_CLASSES, planes=64, ppm...
def save_checkpoint(args, epoch, model, optimizer, scheduler): logger.info('==> Saving...') state = {'opt': args, 'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict(), 'epoch': epoch} torch.save(state, os.path.join(args.output_dir, 'current.pth')) if ((ep...
def check_accuracy(true_mean, true_cov, var_param, approx): (approx_mean, approx_cov) = approx.mean_and_cov(var_param) true_std = np.sqrt(np.diag(true_cov)) approx_std = np.sqrt(np.diag(approx_cov)) mean_error = np.linalg.norm((true_mean - approx_mean)) cov_error_2 = np.linalg.norm((true_cov - appro...
def str2list(v): if (('[' in v) and (']' in v)): return list(map(int, v.strip('[]').split(','))) else: raise argparse.ArgumentTypeError('Input expected in the form [b1,b2,b3,...]')
def pnasnet_large_arg_scope(weight_decay=4e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): return nasnet.nasnet_large_arg_scope(weight_decay, batch_norm_decay, batch_norm_epsilon)
class TruncationStrategy(ExplicitEnum): ONLY_FIRST = 'only_first' ONLY_SECOND = 'only_second' LONGEST_FIRST = 'longest_first' DO_NOT_TRUNCATE = 'do_not_truncate'
def main(): parser = argparse.ArgumentParser(fromfile_prefix_chars='') parser.add_argument('--word-dim', required=True, type=int) parser.add_argument('--hidden-dim', required=True, type=int) parser.add_argument('--clf-hidden-dim', required=True, type=int) parser.add_argument('--clf-num-layers', requ...
class IdObsFilter(ObsFilter): def sense(self, scenario: DgScenario, full_obs: SimObservations, pov: PlayerName) -> SimObservations: return full_obs
def get_answer_text(example, feature, pred, args): tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)] orig_doc_start = feature.token_to_orig_map[pred.start_index] orig_doc_end = feature.token_to_orig_map[pred.end_index] orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)] ...
def make_image(map, ns: str): img = Image.fromarray((((map - 1) ** 2) * 255).astype('uint8')) imgrgb = img.convert('RGB') map_name = 'random_map' dir_path = os.path.dirname(os.path.realpath(__file__)) try: os.mkdir(((dir_path + '/') + map_name)) except: pass imgrgb.save((dir_...
def main(): args = docopt(__doc__, version='Wikt2Dict - Find anomalies 1.0') if args['unigram']: read_unigrams(args['<unigram_file>']) scan_stdin(args)
def _create_fake_setuptools_pkg_info(placeholder): if ((not placeholder) or (not os.path.exists(placeholder))): log.warn('Could not find the install location') return pyver = ('%s.%s' % (sys.version_info[0], sys.version_info[1])) setuptools_file = ('setuptools-%s-py%s.egg-info' % (SETUPTOOLS...
def syntax_fix_remove_last_line(original): code = original while (len(code) > 0): syntax_error = False try: o_ast = ast.parse(code) node = ast.fix_missing_locations(o_ast) code = astunparse.unparse(node).strip() node = ast.parse(code) excep...
class NNServiceServicer(object): def train(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def evaluate(self, request, context): context.set_code(grpc.Stat...
def deconv_bn(batchNorm, in_planes, out_planes, kernel_size=4, stride=2, padding=1, output_padding=0, bias=True): if batchNorm: return nn.Sequential(nn.ConvTranspose2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, output_padding=output_padding, bias=bias), nn.BatchNorm2d(ou...
class NNClassifierModel(NNModel, HasThreshold): def __init__(self, model, feature_preprocessing=None, jvalue=None, bigdl_type='float'): super(NNClassifierModel, self).__init__(model, feature_preprocessing, jvalue, bigdl_type) def load(path): jvalue = callZooFunc('float', 'loadNNClassifierModel',...
def save_pred(pred, root): with open(os.path.join(root, 'prediction.pkl'), 'wb') as f: pickle.dump(pred, f)
class TransposeLast(nn.Module): def __init__(self, deconstruct_idx=None, tranpose_dim=(- 2)): super().__init__() self.deconstruct_idx = deconstruct_idx self.tranpose_dim = tranpose_dim def forward(self, x): if (self.deconstruct_idx is not None): x = x[self.deconstruct...
def get_auto_reg_predictions(model, row, window, teacher_forcing=True, exponentiate=False, predict_deaths=True): if predict_deaths: key = 'deaths' else: key = 'cases' deaths = row[key] predictions = [0] if teacher_forcing: for i in range((len(deaths) - window)): x...
def load_dataset(dataset): base_path = join(realpath(dirname(__file__)), 'data', dataset) if (not exists(base_path)): print('Please download OTB dataset into `data` folder!') exit() json_path = join(realpath(dirname(__file__)), 'data', (dataset + '.json')) info = json.load(open(json_path...
class StandardScaler(): def __init__(self, means: np.ndarray=None, stds: np.ndarray=None, replace_nan_token: Any=None): self.means = means self.stds = stds self.replace_nan_token = replace_nan_token def fit(self, X: List[List[float]]) -> 'StandardScaler': X = np.array(X).astype(f...
def parse_args(): parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--weight', dest='weight', help='initialize with pretrained model weights', type=str) parser...
class DocSceneGraphTrainer(ModifiedDefaultTrainer): def __init__(self, cfg): super(DocSceneGraphTrainer, self).__init__(cfg) def build_train_loader(cls, cfg): return build_detection_train_loader(cfg, mapper=SceneGraphDatasetMapper(cfg, True)) def build_test_loader(cls, cfg, dataset_name): ...
def _remove_flat_installation(placeholder): if (not os.path.isdir(placeholder)): log.warn('Unkown installation at %s', placeholder) return False found = False for file in os.listdir(placeholder): if fnmatch.fnmatch(file, 'setuptools*.egg-info'): found = True b...
def test_CRN_encoder(pickle_map, models_dir, encoder_model_name, encoder_hyperparams_file, b_encoder_hyperparm_tuning): training_data = pickle_map['training_data'] validation_data = pickle_map['validation_data'] test_data = pickle_map['test_data'] scaling_data = pickle_map['scaling_data'] training_p...
class KeyPoint2DAnnotationList(Annotation): def __init__(self, ontology, pointlist): super().__init__(ontology) assert isinstance(self._ontology, KeyPointOntology), 'Trying to load annotation with wrong type of ontology!' for point in pointlist: assert isinstance(point, KeyPoint2...
class ModelTest(tf.test.TestCase): def assertLen(self, container, expected_len): self.assertEqual(expected_len, len(container)) def testDNN(self): predictor = _build_model() z = tf.constant([1, 2, 3, 4], dtype=tf.float32) z = tf.reshape(z, [1, 2, 2, 1]) predictor(z) ...
class InjectorGenerator(Generator): def __init__(self, solutions: List[Solution]): super(InjectorGenerator, self).__init__() self.population = copy.deepcopy(solutions) def new(self, problem: Problem): if (len(self.population) > 0): return self.population.pop() else: ...
def main(args): path = os.path.join('../tcgnn-ae-graphs', (args.dataset + '.npz')) data = TCGNN_dataset(path, args.dim, args.num_classes, load_from_txt=False) g = data.g.int().to(args.gpu) features = data.x labels = data.y in_feats = features.size(1) n_classes = data.num_classes degs = g...
def test_snapshotKeplerPotential_eval_naz(): s = pynbody.new(star=1) s['mass'] = 1.0 s['eps'] = 0.0 sp = potential.SnapshotRZPotential(s, num_threads=1) spaz = potential.SnapshotRZPotential(s, num_threads=1, nazimuths=12) assert (numpy.fabs((sp(1.0, 0.0) - spaz(1.0, 0.0))) < (10.0 ** (- 8.0))), ...
.register_measure class EpisodeInfoExample(habitat.Measure): def __init__(self, sim, config, **kwargs: Any): self._config = config super().__init__() def _get_uuid(self, *args: Any, **kwargs: Any) -> str: return 'episode_info' def reset_metric(self, *args: Any, episode, **kwargs: Any...
class TimeDistributed(Layer): def __init__(self, model, bigdl_type='float'): super(TimeDistributed, self).__init__(None, bigdl_type, model)
def test_iter_path_splits(): assert (list(iter_path_splits('foo.bar.baz')) == [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')])
def train_input_fn(data_dir, batch_size, epochs, **kargs): filenames = [os.path.join(data_dir, ('train/train-%05d-of-01024' % i)) for i in range(1024)] for path in filenames: if (not os.path.exists(path)): raise ValueError((path + ' not found')) dataset = tf.data.Dataset.list_files(filen...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, dat...
def conv1d(in_, filter_size, height, padding, is_train=None, keep_prob=1.0, scope=None): with tf.variable_scope((scope or 'conv1d')): num_channels = in_.get_shape()[(- 1)] filter_ = tf.get_variable('filter', shape=[1, height, num_channels, filter_size], dtype='float') bias = tf.get_variable(...
def add_capacity_constraints(routing, data, prize_evaluator): capacity = 'Capacity' routing.AddDimension(prize_evaluator, 0, data.vehicle.capacity, True, capacity)
def process_in_parallel(tag, total_range_size, binary, output_dir, load_ckpt, load_detectron, opts=''): cfg_file = os.path.join(output_dir, '{}_range_config.yaml'.format(tag)) with open(cfg_file, 'w') as f: yaml.dump(cfg, stream=f) subprocess_env = os.environ.copy() processes = [] NUM_GPUS =...
class Element(Param): def __init__(self, xml_var, value_type, required=True, default=None, var=None, is_raw=False): Param.__init__(self, xml_var, value_type, required, default, var) self.type = 'element' self.is_raw = is_raw def set_from_xml(self, obj, node, path): value = self.v...
def cache_sample(iteration, data): with open((dirname_samples + ('/%d' % iteration)), 'wb') as f: cPickle.dump(data, f)
class MViT(Backbone): def __init__(self, img_size=224, patch_kernel=(7, 7), patch_stride=(4, 4), patch_padding=(3, 3), in_chans=3, embed_dim=96, depth=16, num_heads=1, last_block_indexes=(0, 2, 11, 15), qkv_pool_kernel=(3, 3), adaptive_kv_stride=4, adaptive_window_size=56, residual_pooling=True, mlp_ratio=4.0, qkv_...
def input_fn_builder(features, seq_length, max_predictions_per_seq, tokenizer): all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_masked_lm_positions = [] all_masked_lm_ids = [] all_masked_lm_weights = [] all_next_sentence_labels = [] for feature in features: all_in...
class ResnetDownsampleBlock2D(nn.Module): def __init__(self, in_channels: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, output_scale_fa...
def cachedmethod(method, *args, **kwargs): key = ('_' + method.__name__) args_name = (key + '_args') kwargs_name = (key + '_kwargs') def cached_method(self, *args, **kwargs): clear_data = kwargs.pop('clear', False) if clear_data: clear(self) return recalc ...
def _make_scheduler(args, optimizer): logger.info(f'Using {args.scheduler} Scheduler ......') if (args.scheduler == 'StepLR'): scheduler = lr_scheduler.StepLR(optimizer, step_size=50, gamma=args.lr_decay) elif (args.scheduler == 'OneCycleLR'): scheduler = lr_scheduler.OneCycleLR(optimizer, a...
class ConvNet(nn.Module): def __init__(self, opt, momentum=0.1, affine=True, track_running_stats=True): super(ConvNet, self).__init__() self.in_planes = opt['in_planes'] self.out_planes = opt['out_planes'] self.num_stages = opt['num_stages'] if (type(self.out_planes) == int):...
def test(test_loader, input_dim=1024): model = Net(input_dim=input_dim) criterion = nn.BCELoss() if train_on_gpu: model.cuda() model.load_state_dict(torch.load('model.pt')) test_loss = 0.0 num_correct = 0 y_true = np.array([]) y_pred = np.array([]) y_pred_proba = np.array([])...
def psnr(img, ref): psnr_slices = [] ref_abs = np.abs(ref) img_abs = np.abs(img) for i in range(ref_abs.shape[0]): psnr_i = compare_psnr(ref_abs[i], img_abs[i], data_range=ref_abs[i].max()) psnr_slices.append(np.mean(psnr_i)) return np.mean(psnr_slices)
def clone_and_find(nodes): return_list = True if (not isinstance(nodes, list)): return_list = False nodes = [nodes] paths = [] for node in nodes: paths.append([]) tree = node while (tree.parent is not None): prev = tree tree = tree.parent ...
class CaptionDedupProcessor(object): def __init__(self, pkl_file): with open(pkl_file, 'rb') as fd: self.data = pickle.load(fd) self.stat = {'t_clip_len': [], 'video_len': [], 'clip_tps': [], 'video_tps': [], 'clip_len': []} def __call__(self): for (idx, video_id) in enumerat...
def train(log_interval, model, device, train_loader, optimizer, epoch): model.train() for (batch_idx, (data, target)) in enumerate(train_loader): (data, target) = (data.to(device), target.to(device)) N = data.shape[0] data = data.view(N, model.time_step, (- 1)) optimizer.zero_gra...
def wash_and_repair_reference_line(line): line = repair_broken_urls(line) line = replace_undesirable_characters(line) line = re.sub('"([^"]+),"', '"\\g<1>",', line) line = replace_undesirable_characters(line) line = re_multiple_space.sub(u' ', line) return line
def stop_flops_count(self): remove_batch_counter_hook_function(self) self.apply(remove_flops_counter_hook_function)
def initialize_dataloader(train_config, train_dataset, val_dataset): batch_size = train_config['batch_size'] num_workers = train_config['num_workers'] pin_memory = train_config['pin_memory'] train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=...
def broadcast_object(obj: Any, src_rank: int, group: object, dist_device: Optional[torch.device]=None) -> Any: if (dist_device is None): if (torch.distributed.get_backend(group) == 'nccl'): dist_device = torch.device('cuda') else: dist_device = torch.device('cpu') if (get...
def sent_metric_detect(preds, targs): assert (len(preds) == len(targs)), f'{len(preds)},{len(targs)}' (tp, targ_p, pred_p, hit) = (0, 0, 0, 0) for (pred_item, targ_item) in zip(preds, targs): assert (pred_item[0] == targ_item[0]) (pred, targ) = (sorted(pred_item[1:]), sorted(targ_item[1:])) ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, base_width=64, stride=1, groups=1, dilation=1, norm_layer=None, downsample=None): super().__init__() if (stride not in [1, 2]): raise ValueError(f'Bottlenet of ResNet only supports `stride=1` and `stride=...
.parametrize('dataset', ['CocoDataset', 'VOCDataset', 'CityscapesDataset']) def test_custom_classes_override_default(dataset): dataset_class = DATASETS.get(dataset) dataset_class.load_annotations = MagicMock() if (dataset in ['CocoDataset', 'CityscapesDataset']): dataset_class.coco = MagicMock() ...
class TestPruning(unittest.TestCase): def test_pruning_basic(self): hidden_size = 32 model = NaiveMLP(hidden_size) from neural_compressor.compression.pruner.model_slim.pattern_analyzer import ClassifierHeadSearcher searcher = ClassifierHeadSearcher(model) layer = searcher.sea...
def expand_argument_values(argument_values: Sequence[TensorValue]) -> List[TensorValue]: has_slot_var = False for arg in argument_values: if isinstance(arg, TensorValue): for var in arg.batch_variables: if (var == '??'): has_slot_var = True ...
class TCCA(MCCA): def fit(self, views: Iterable[np.ndarray], y=None, **kwargs): views = self._validate_data(views) self._check_params() (whitened_views, covs_invsqrt) = self._setup_tensor(views) for (i, el) in enumerate(whitened_views): if (i == 0): M = el...
def getDomain(idx, log, domains, last_domain): if (idx == 1): active_domains = get_summary_bstate(log[idx]['metadata'], True) crnt_doms = (active_domains[0] if (len(active_domains) != 0) else domains[0]) return crnt_doms else: ds_diff = get_ds_diff(log[(idx - 2)]['metadata'], log...
class BertGenerationTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES prefix_tokens: List[int] = [] model_input_names = ['input_ids', 'attention_mask'] def _...
def create_log(name, model_name): log_dir = './log/{}'.format(model_name) if (not os.path.exists(log_dir)): os.makedirs(log_dir) csv_name = os.path.join(log_dir, '{}.csv'.format(name)) log = '{}_log'.format('name') log = open(csv_name, 'w') if (name == 'train'): log.write('epoch,...
def get_test_loader(root, img_size=256, batch_size=32, shuffle=True, num_workers=4): print('Preparing DataLoader for the generation phase...') transform = transforms.Compose([transforms.Resize([img_size, img_size]), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])]) dat...
def tokenize_dataset(args, model, raw_datasets, tokenizer): def tokenize_function(examples): return tokenizer(examples[text_column_name]) embedding_size = model.get_input_embeddings().weight.shape[0] if (len(tokenizer) > embedding_size): model.resize_token_embeddings(len(tokenizer)) colu...
def get_pairs(word): pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char pairs = set(pairs) return pairs
def uniform(shape, scale=0.05, name=None): initial = tf.random_uniform(shape, minval=(- scale), maxval=scale, dtype=tf.float32) return tf.Variable(initial, name=name)
def EfficientNetB4(include_top=False, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, stride_size=2, classifier_activation='softmax', **kwargs): return EfficientNet(1.4, 1.8, 380, 0.4, model_name='efficientnetb4', include_top=include_top, weights=weights, input_tensor=input_tens...
def pad_width(img, stride, pad_value, min_dims): (h, w, _) = img.shape h = min(min_dims[0], h) min_dims[0] = (math.ceil((min_dims[0] / float(stride))) * stride) min_dims[1] = max(min_dims[1], w) min_dims[1] = (math.ceil((min_dims[1] / float(stride))) * stride) pad = [] pad.append(int(math.fl...
def test_accellsrframe_funcomegaz_2d(): lp = potential.LogarithmicHaloPotential(normalize=1.0) omega = lp.omegac(1.0) omegadot = 0.02 omega_func = (lambda t: (lp.omegac(1.0) + (0.02 * t))) omegadot_func = (lambda t: 0.02) diskpot = lp framepot = potential.NonInertialFrameForce(Omega=omega_fu...
def generate_reverberated_wav_scp(wav_scp, durations, output_dir, room_dict, pointsource_noise_list, iso_noise_dict, foreground_snr_array, background_snr_array, num_replicas, include_original, prefix, speech_rvb_probability, shift_output, isotropic_noise_addition_probability, pointsource_noise_addition_probability, max...
class LSTMModel(nn.Module): def __init__(self, ntoken=10, ninp=512, nhid=256, nlayers=5, dropout=0.5): super(LSTMModel, self).__init__() self.drop = nn.Dropout(dropout) self.encoder = nn.Embedding(ntoken, ninp) self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout) self.dec...