code
stringlengths
101
5.91M
class CNNFashion_Mnist(nn.Module): def __init__(self, args): super(CNNFashion_Mnist, self).__init__() self.layer1 = nn.Sequential(nn.Conv2d(1, 16, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2)) self.layer2 = nn.Sequential(nn.Conv2d(16, 32, kernel_size=5, padding=2), nn.ReLU(), nn.Max...
class RandomIdentitySampler_alignedreid(Sampler): def __init__(self, data_source, num_instances): self.data_source = data_source self.num_instances = num_instances self.index_dic = defaultdict(list) for (index, (_, pid, _)) in enumerate(data_source): self.index_dic[pid].a...
def main(): print('DeJPEG generator') jpeg_levels = [int(x) for x in sys.argv[kJPEG_LEVELS].split(',')] input_fld = sys.argv[kINPUT_FLD] all_proc = [] for jpeg_quality in jpeg_levels: all_proc.append(Process(target=genDEJPEG, args=(jpeg_quality, input_fld))) all_proc[(- 1)].start() ...
def zero_module(module): for p in module.parameters(): p.detach().zero_() return module
def massivesumm_extract_from_url(urls): archive = run(urls) dataset = extract(archive) return dataset
class DebugOption(ExplicitEnum): UNDERFLOW_OVERFLOW = 'underflow_overflow' TPU_METRICS_DEBUG = 'tpu_metrics_debug'
def load_lvis_json(json_file, image_root, dataset_name=None): from lvis import LVIS json_file = PathManager.get_local_path(json_file) timer = Timer() lvis_api = LVIS(json_file) if (timer.seconds() > 1): logger.info('Loading {} takes {:.2f} seconds.'.format(json_file, timer.seconds())) if...
def get_elemental_ref_entries(entries: Sequence[EntryLike], verbose: bool=True) -> dict[(str, Entry)]: entries = [(PDEntry.from_dict(e) if isinstance(e, dict) else e) for e in entries] elements = {elems for entry in entries for elems in entry.composition.elements} dim = len(elements) if verbose: ...
def get_dataloader_tiny(datadir, train_bs, test_bs, dataidxs=None, test_idxs=None, cache_train_data_set=None, cache_test_data_set=None, logger=None): (transform_train, transform_test) = _data_transforms_tiny() dataidxs = np.array(dataidxs) logger.info('train_num{} test_num{}'.format(len(dataidxs), len(test...
def load_conf(conf_path): with open(conf_path, 'r', encoding='utf-8') as file: file_data = file.read() all_data = yaml.safe_load(file_data) return all_data
class sensor(): def __init__(self): self.update_cluster = True self.n_reset = (- 1) self.obstacles_dyn = {} self.obstacles_static = {} self.cluster = Clusters() self.obst_topics_dyn = [] self.obst_topics_static = [] self.pub_obst_odom = rospy.Publisher...
class DotDict(dict): def __init__(self, *a, **kw): dict.__init__(self) self.update(*a, **kw) self.__dict__ = self def __setattr__(self, key, value): if (key in dict.__dict__): raise AttributeError('This key is reserved for the dict methods.') dict.__setattr__(...
def main(): dataset = Datasets('tensorflow')['dummy'](shape=(1, 224, 224, 3)) dataloader = DataLoader(framework='tensorflow', dataset=dataset) config = PostTrainingQuantConfig() q_model = fit(model='./mobilenet_v1_1.0_224_frozen.pb', conf=config, calib_dataloader=dataloader)
class SimpleRewardShaper(): def __init__(self): pass def reset(self, env): pass def __call__(self, env, observations, action_dict, rewards, dones): for handle in rewards.keys(): if (rewards[handle] == 1): rewards[handle] = env.max_time_steps return...
def hrnet18(in_channels, num_classes): model = HighResolutionNet(in_channels=in_channels, num_classes=num_classes, extra=extra_18) init_weights(model, 'kaiming') return model
class ClientModel(Model): def __init__(self, seed, lr, num_classes): self.num_classes = num_classes super(ClientModel, self).__init__(seed, lr) def create_model(self): features = tf.placeholder(tf.float32, shape=[None, (IMAGE_SIZE * IMAGE_SIZE)], name='features') labels = tf.plac...
def get_api_defs(lib): assert (lib in ['tf', 'torch']) if (lib == 'tf'): api_def_fn = 'data/api_def_tf.txt' else: api_def_fn = 'data/api_def_torch.txt' return _get_api_defs(api_def_fn)
_model def halonet50ts(pretrained=False, **kwargs): return _create_byoanet('halonet50ts', pretrained=pretrained, **kwargs)
class VoxelResBackBone8x(nn.Module): def __init__(self, model_cfg, input_channels, grid_size, **kwargs): super().__init__() self.model_cfg = model_cfg norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01) self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0]) self.conv_in...
def natural_keys(text: str): def atof(text): try: retval = float(text) except ValueError: retval = text return retval return [atof(c) for c in re.split('[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text)]
def add_decola_deta_config(cfg): _C = cfg _C.MODEL.DECOLA.DETA = CN() _C.MODEL.DECOLA.DETA.USE_DETA = False _C.MODEL.DECOLA.DETA.ASSIGN_FIRST_STAGE = True _C.MODEL.DECOLA.DETA.ASSIGN_SECOND_STAGE = True
def load_c_file(c_file_path): try: with open(c_file_path, encoding='utf-8') as rfile: code_content = rfile.read() return code_content except UnicodeDecodeError: with open(c_file_path, encoding='windows-1252') as rfile: code_content = rfile.read() return co...
def compile_fn(network, net_config, args): base_lr = float(args.lr[0]) l2 = float(args.l2[0]) input_var = net_config['input'].input_var mask_var = net_config['mask'].input_var kspace_var = net_config['kspace_input'].input_var target_var = T.tensor4('targets') pred = lasagne.layers.get_output...
def cosine_similarity(lfs, rhs): dot = tf.reduce_sum((lfs * rhs), axis=1) base = (tf.sqrt(tf.reduce_sum(tf.square(lfs), axis=1)) * tf.sqrt(tf.reduce_sum(tf.square(rhs), axis=1))) return (dot / base)
def mask_heads(args, model, eval_dataloader): (_, head_importance, preds, labels) = compute_heads_importance(args, model, eval_dataloader, compute_entropy=False) preds = (np.argmax(preds, axis=1) if (args.output_mode == 'classification') else np.squeeze(preds)) original_score = compute_metrics(args.task_nam...
class BaseProcessScheduler(object): def __init__(self): self._exit_event = threading.Event() self._error_event = threading.Event() self.all_processes = dict() def start_monitor_thread_subprocess(self): def baby_sitter(): def inner(): while True: ...
def create_markers(marker_type): marker_ids = utils.get_marker_ids(marker_type) if (marker_type == 'robots'): marker_ids = ((5 * marker_ids) + marker_ids[:4]) elif (marker_type == 'cubes'): marker_ids = [marker_id for marker_id in marker_ids[:8] for _ in range(6)] elif (marker_type == 'c...
def create_logger(root_output_path, cfg, image_set): if (not os.path.exists(root_output_path)): os.makedirs(root_output_path) assert os.path.exists(root_output_path), '{} does not exist'.format(root_output_path) cfg_name = os.path.basename(cfg).split('.')[0] config_output_path = os.path.join(roo...
class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.discriminator = nn.ModuleList([nn.Sequential(nn.utils.weight_norm(nn.Conv1d(1, 16, kernel_size=15, stride=1, padding=7)), nn.LeakyReLU()), nn.Sequential(nn.utils.weight_norm(nn.Conv1d(16, 64, kernel_size=4...
class PredictionLossGame(): def __init__(self, extension, sample, label, loss): if (sample.ndim == 1): sample = sample[np.newaxis] if np.isscalar(label): label = np.array([label]) if (loss is utils.crossentropyloss): if ((label.ndim <= 1) or (label.shape[1...
class CpuSampler(ParallelSamplerBase): def __init__(self, *args, CollectorCls=CpuResetCollector, eval_CollectorCls=CpuEvalCollector, **kwargs): super().__init__(*args, CollectorCls=CollectorCls, eval_CollectorCls=eval_CollectorCls, **kwargs) def obtain_samples(self, itr): self.agent.sync_shared_...
class Conv_block(Module): def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1): super(Conv_block, self).__init__() self.conv = Conv2d(in_c, out_channels=out_c, kernel_size=kernel, groups=groups, stride=stride, padding=padding, bias=False) self.bn = BatchNor...
def main(): parser = get_parser() args = parser.parse_args() logging.basicConfig(level=logging.INFO, format='%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s') logging.info(get_commandline_args()) if (not os.path.exists(args.outdir)): os.makedirs(args.outdir) for (idx, (utt...
def visualize_registration(src, dst, transformation=np.eye(4)): src_trans = deepcopy(src) src_trans.transform(transformation) src_trans.paint_uniform_color([1, 0, 0]) dst_clone = deepcopy(dst) dst_clone.paint_uniform_color([0, 1, 0]) o3d.visualization.draw([src_trans, dst_clone])
def get_blocks(num_layers): if (num_layers == 50): blocks = [get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=4), get_block(in_channel=128, depth=256, num_units=14), get_block(in_channel=256, depth=512, num_units=3)] elif (num_layers == 100): blocks ...
class SliceData(Dataset): def __init__(self, root, transform, challenge, sample_rate=1): if (challenge not in ('singlecoil', 'multicoil')): raise ValueError('challenge should be either "singlecoil" or "multicoil"') self.transform = transform self.recons_key = ('reconstruction_esc...
def _test(): import torch pretrained = False models = [shufflenetv2_wd2, shufflenetv2_w1, shufflenetv2_w3d2, shufflenetv2_w2] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_...
def main(args): args = get_parser().parse_args(args) convert(args.json, args.refs, args.hyps, args.num_spkrs)
def compute_histogram(args, dataloader, model, classifier): histogram = np.zeros((args.K_test, args.K_test)) model.eval() classifier.eval() with torch.no_grad(): for (i, (indice, image, label)) in enumerate(dataloader): image = image.cuda(non_blocking=True) feats = model(...
class ExplorationPolicy(abc.ABC): def __init__(self, policy): self.policy = policy def get_action(self, observation): def get_actions(self, observations): def reset(self, dones=None): self.policy.reset(dones) def get_param_values(self): return self.policy.get_param_values() ...
def get_new_network_cell(): args = obtain_decode_args() load_model = Loader(args) (fea_net_paths, fea_net_paths_space, mat_net_paths, mat_net_paths_space) = load_model.decode_architecture() (fea_genotype, mat_genotype) = load_model.decode_cell() print('Feature Net search results:', fea_net_paths) ...
_module() class FormatTrimap(): def __init__(self, to_onehot=False): self.to_onehot = to_onehot def __call__(self, results): trimap = results['trimap'].squeeze() trimap[(trimap == 128)] = 1 trimap[(trimap == 255)] = 2 if self.to_onehot: trimap = F.one_hot(trim...
def get_transform_cub(model_type, train, augment_data): scale = (256.0 / 224.0) target_resolution = model_attributes[model_type]['target_resolution'] assert (target_resolution is not None) if ((not train) or (not augment_data)): transform = transforms.Compose([transforms.Resize((int((target_reso...
.dataclass class FlaxImageClassifierOutputWithNoAttention(ModelOutput): logits: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None
class PygNodePropPredDataset(InMemoryDataset): def __init__(self, name, root='dataset', transform=None, pre_transform=None, meta_dict=None): self.name = name if (meta_dict is None): self.dir_name = '_'.join(name.split('-')) if osp.exists(osp.join(root, (self.dir_name + '_pyg'...
class LeNet(nn.Module): def __init__(self, in_channel=1, out_channel=10): super(LeNet, self).__init__() self.conv1 = nn.Sequential(nn.Conv1d(in_channel, 6, 5), nn.ReLU(), nn.MaxPool1d(kernel_size=2, stride=2)) self.conv2 = nn.Sequential(nn.Conv1d(6, 16, 5), nn.ReLU(), nn.AdaptiveMaxPool1d(5)...
def rand_tree(n, reg, n_out=0, n_hyper_in=0, n_hyper_out=0, d_min=2, d_max=3, seed=None, optimize='greedy'): from .core import ContractionTree (inputs, output, _, size_dict) = rand_equation(n, reg, n_out=n_out, n_hyper_in=n_hyper_in, n_hyper_out=n_hyper_out, d_min=d_min, d_max=d_max, seed=seed) tree = Contr...
class Agent(abc.ABC): def __init__(self, total_batch_size: int): self.total_batch_size = total_batch_size num_devices = jax.local_device_count() assert ((total_batch_size % num_devices) == 0), f'The total batch size must be a multiple of the number of devices, got total_batch_size={total_bat...
def load_f0(f0_dir, nshards): path_to_f0 = {} for rank in tqdm(range(1, (nshards + 1)), desc=f'load f0'): f0_shard_path = f'{f0_dir}/f0_{rank}_{nshards}.pt' shard_path_to_f0 = torch.load(f0_shard_path) path_to_f0.update(shard_path_to_f0) return path_to_f0
def compute_precision_recall(scores, labels, num_gt): if ((not isinstance(labels, np.ndarray)) or (labels.dtype != np.bool) or (len(labels.shape) != 1)): raise ValueError('labels must be single dimension bool numpy array') if ((not isinstance(scores, np.ndarray)) or (len(scores.shape) != 1)): ra...
('NOTICE', colon=False) def _handle_notice(irc: miniirc.IRC, hostmask: Tuple[(str, str, str)], args: List[str]) -> None: log.info('Received NOTICE: hostmask=%s, args=%s', hostmask, args) (user, _ident, _hostname) = hostmask if ((user.casefold() == 'nickserv') and (len(args) >= 2)): (nick, msg) = arg...
def find_tanh(alpha, k, eps=0.0001, positive=True): u = torch.sqrt((1 - (k / alpha))) extreme = ((1 - u) <= 0.01) x1 = inverse_tanh((u - eps)) x2 = inverse_tanh((u + eps)) x2[extreme] = 100 k1 = ((1 - (torch.tanh(x1) ** 2)) * alpha) k2 = ((1 - (torch.tanh(x2) ** 2)) * alpha) k2[extreme] ...
def find_ngrams(token_dict, text, n): if (n <= 1): return text saved_tokens = [] search_tokens = text[:] next_search = [] while (len(search_tokens) >= n): ngram = ' '.join(search_tokens[:n]) if (ngram in token_dict): sub_n = min(len(next_search), (n - 1)) ...
def named_penalties(module, reduction='sum', prefix=''): if ((reduction is not None) and (reduction not in ('mean', 'sum'))): raise ValueError(f'`reduction` must be either `None`, `sum` or `mean`. Got {reduction}.') for (name, mod) in module.named_modules(prefix=prefix): if isinstance(mod, BaseA...
def map_to_list_nn(features, nbidx, srcpos, bs, nv, height, width): return MapToListNn.apply(features, nbidx, srcpos, bs, nv, height, width)
class CallableModule(types.ModuleType): def __init__(self): types.ModuleType.__init__(self, __name__) self.__dict__.update(sys.modules[__name__].__dict__) def __call__(self, x, *args, **kwargs): return __call__(x, *args, **kwargs)
def learn_q_model(model_name): if (control.Settings.REWARD_FUNCTION == 'Continuous'): reward_function = continuous_reward elif (control.Settings.REWARD_FUNCTION == 'Slotted'): reward_function = slotted_reward else: raise ValueError('Invalid reward function {} specified in settings.'....
def CHECKEQ(a, b, s=None): if (s is None): s = '' if (type(a) is list): CHECKEQ(len(a), len(b), s) for i in range(len(a)): CHECKEQ(a[i], b[i], s) elif (type(a) is dict): CHECKEQ(list(a.keys()), list(b.keys()), s) for k in a.keys(): CHECKEQ(a[k]...
def predictor_typeendgame_get(): from phcpy.phcpy2c3 import py2c_get_value_of_continuation_parameter as get return int(get(8))
def cv2_imread(filename, flags=cv2.IMREAD_UNCHANGED, loader_func=None, verbose=True): try: if (loader_func is not None): bytes = bytearray(loader_func(filename)) else: with open(filename, 'rb') as stream: bytes = bytearray(stream.read()) numpyarray = n...
class myBN(nn.Module): def __init__(self, num_channels, eps=1e-05, momentum=0.1): super(myBN, self).__init__() self.momentum = momentum self.eps = eps self.momentum = momentum self.register_buffer('stored_mean', torch.zeros(num_channels)) self.register_buffer('stored_...
def CheckFiles(input_data_dir): for file_name in ['spk2utt', 'text', 'utt2spk', 'feats.scp']: file_name = '{0}/{1}'.format(input_data_dir, file_name) if (not os.path.exists(file_name)): raise Exception('There is no such file {0}'.format(file_name))
def load_files_from_dataset_dir(dataset_dir) -> dict: file_paths = dict() all_files = [f for f in os.listdir(dataset_dir)] return all_files
_FORMAT_LOADER.register('R-50-C4') _FORMAT_LOADER.register('R-50-C5') _FORMAT_LOADER.register('R-101-C4') _FORMAT_LOADER.register('R-101-C5') _FORMAT_LOADER.register('R-50-FPN') _FORMAT_LOADER.register('R-50-FPN-RETINANET') _FORMAT_LOADER.register('R-101-FPN') _FORMAT_LOADER.register('R-101-FPN-RETINANET') _FORMAT_LOAD...
class L1Norm(nn.Module): def __init__(self): super(L1Norm, self).__init__() def forward(self, x): return torch.norm(x, 1, 1).sum()
class FixedLRScheduleConfig(FairseqDataclass): force_anneal: Optional[int] = field(default=None, metadata={'help': 'force annealing at specified epoch'}) lr_shrink: float = field(default=0.1, metadata={'help': 'shrink factor for annealing, lr_new = (lr * lr_shrink)'}) warmup_updates: int = field(default=0, ...
class CompletionChunk(TypedDict): id: str object: Literal['text_completion'] created: int model: str choices: List[CompletionChoice]
def gptneox_sample_token(ctx: gptneox_context_p, candidates) -> gptneox_token: return _lib.gptneox_sample_token(ctx, candidates)
def display_first_plan(folder, ruler=None): targetfname = (('results/vtk_files/' + folder) + '/Target.vtk') modelfname = (('results/vtk_files/' + folder) + '/Descent/Models/Model_1.vtk') planfname = (('results/vtk_files/' + folder) + '/Descent/Plans/Plan_1.vtk') outfname = (('results/images/firstplan_' ...
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, **kwargs): (rank, world_size) = get_dist_info() if dist: if shuffle: sampler = DistributedGroupSampler(dataset, samples_per_gpu, world_size, rank) else: sampler...
def CalculateKeypointCenters(boxes): return tf.divide(tf.add(tf.gather(boxes, [0, 1], axis=1), tf.gather(boxes, [2, 3], axis=1)), 2.0)
def get_model_tester_from_test_class(test_class): test = test_class() if hasattr(test, 'setUp'): test.setUp() model_tester = None if hasattr(test, 'model_tester'): if (test.model_tester is not None): model_tester = test.model_tester.__class__ return model_tester
class LogWriter(object): def __init__(self, path, args): if ('' in args): del args[''] self.path = path self.args = args with open(self.path, 'w') as f: f.write('Training Log\n') f.write('Specifications\n') for argname in self.args: ...
class SequenceTagger(TextKerasModel): def __init__(self, num_pos_labels, num_chunk_labels, word_vocab_size, char_vocab_size=None, word_length=12, feature_size=100, dropout=0.2, classifier='softmax', optimizer=None): classifier = classifier.lower() invalidInputError((classifier in ['softmax', 'crf'])...
def sync_record(filename, duration, fs, channels): print('recording') myrecording = sd.rec(int((duration * fs)), samplerate=fs, channels=channels) sd.wait() sf.write(filename, myrecording, fs) print('done recording')
def batch_to(tensor: Tensor, batch_shape: tuple, num_nonbatch: int): batch_ref = torch.empty(batch_shape) (out_tensor, _) = batch_broadcast((tensor, batch_ref), (num_nonbatch, 0)) return out_tensor
_module() class FPN(nn.Module): def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=(- 1), add_extra_convs=False, extra_convs_on_inputs=True, relu_before_extra_convs=False, no_norm_on_lateral=False, conv_cfg=None, norm_cfg=None, act_cfg=None, upsample_cfg=dict(mode='nearest')): ...
def _empty_iterator(tensor) -> bool: from collections.abc import Iterable if isinstance(tensor, Iterable): if (len(tensor) == 0): return True return False
_features_generator('ecfp4') def ecfp4_features_generator(mol: Molecule) -> np.ndarray: smiles = (Chem.MolToSmiles(mol, isomericSmiles=True) if (type(mol) != str) else mol) mapping_filepath = os.path.join(PRETRAINED_SMILES_PATH, 'smiles2ecfp4.pkl') with open(mapping_filepath, 'rb') as reader: mappin...
def normalize_digraph(A): Dl = np.sum(A, 0) num_node = A.shape[0] Dn = np.zeros((num_node, num_node)) for i in range(num_node): if (Dl[i] > 0): Dn[(i, i)] = (Dl[i] ** (- 1)) AD = np.dot(A, Dn) return AD
def extract_threads(): print('====Extract threads and save to Avocado.json====') threads = {} lens = [] with open('subjects.json', 'r') as f: subjects = json.load(f) datestr = '%d %b %Y %H:%M:%S UTC' for subject in tqdm(subjects): thread = [] for file in subjects[subject]...
def test_feature_importances_tabnet(): tab_preprocessor = TabPreprocessor(cat_embed_cols=cat_cols, continuous_cols=cont_cols) X_tr = tab_preprocessor.fit_transform(df_tr).astype(float) X_te = tab_preprocessor.transform(df_te).astype(float) tabnet = TabNet(column_idx=tab_preprocessor.column_idx, cat_embe...
def test_batchify_fn(data): error_msg = 'batch must contain tensors, tuples or lists; found {}' if isinstance(data[0], (str, torch.Tensor)): return list(data) elif isinstance(data[0], (tuple, list)): data = zip(*data) return [test_batchify_fn(i) for i in data] raise TypeError(err...
class VideoQABuilder(BaseDatasetBuilder): train_dataset_cls = VideoQADataset eval_dataset_cls = VideoQADataset def build(self): datasets = super().build() ans2label = self.config.build_info.annotations.get('ans2label') if (ans2label is None): raise ValueError('ans2label i...
def _get_rpn_stage(arch_def, num_blocks): rpn_stage = arch_def.get('rpn') ret = mbuilder.get_blocks(arch_def, stage_indices=rpn_stage) if (num_blocks > 0): logger.warn('Use last {} blocks in {} as rpn'.format(num_blocks, ret)) block_count = len(ret['stages']) assert (num_blocks <= bl...
_KEYPOINT_PREDICTOR.register('KeypointRCNNPredictor') class KeypointRCNNPredictor(nn.Module): def __init__(self, cfg, in_channels): super(KeypointRCNNPredictor, self).__init__() input_features = in_channels num_keypoints = cfg.MODEL.ROI_KEYPOINT_HEAD.NUM_CLASSES deconv_kernel = 4 ...
def test_d1_mean(barrel): m = barrel.first_derivative_mean() assert isinstance(m, np.ndarray)
class Request(): def __init__(self, method: str, operation: str, data: dict) -> None: self.method: str = method self.operation: str = operation self.data: dict = data
def demo(word): print('[code-vectors] 5 closest words to "{}"'.format(word)) for (i, (n, _)) in enumerate(kv.most_similar(word, topn=5)): print('[code-vectors] #{}. {}'.format(i, n)) print()
class TimedRule(abstract_rule.AbstractRule): def __init__(self, step_interval, rules): if (not callable(step_interval)): self._step_interval = (lambda : step_interval) else: self._step_interval = step_interval if (not isinstance(rules, (list, tuple))): rul...
def evaluate_model(data_loader, model, idx2attr, device, topk=5): model.eval() test_num = 0 prediction = {} for (images, asins) in tqdm.tqdm(data_loader): with torch.no_grad(): images = images.to(device) outs = model(images) (top_scores, top_outs) = outs.topk(...
class SimpleGaussianGRUModel(Model): def __init__(self, output_dim, hidden_dim, name='SimpleGaussianGRUModel', *args, **kwargs): super().__init__(name) self.output_dim = output_dim self.hidden_dim = hidden_dim def network_input_spec(self): return ['full_input', 'step_input', 'ste...
def _dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None): _Pickler(file, protocol, fix_imports=fix_imports, buffer_callback=buffer_callback).dump(obj)
def CheckCheck(filename, clean_lines, linenum, error): lines = clean_lines.elided (check_macro, start_pos) = FindCheckMacro(lines[linenum]) if (not check_macro): return (last_line, end_line, end_pos) = CloseExpression(clean_lines, linenum, start_pos) if (end_pos < 0): return if (...
class testset_pytable_with_soft_label(Dataset): def __init__(self, test_h5file_name, show=False, outname=None): self.outname = outname self.ratio_list = [0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2] self.test_h5file_name = test_h5file_name self.return_dict = {} i...
class SARPN(nn.Module): def __init__(self, args): super(SARPN, self).__init__() print('backbone:', args.backbone) self.feature_extraction = get_models(args) if (args.backbone in ['ResNet18', 'ResNet34']): adff_num_features = 640 rpd_num_features = 512 ...
class SFUniDADataset(Dataset): def __init__(self, args, data_dir, data_list, d_type, preload_flg=True) -> None: super(SFUniDADataset, self).__init__() self.d_type = d_type self.dataset = args.dataset self.preload_flg = preload_flg self.shared_class_num = args.shared_class_num...
_grad() def convert_owlvit_checkpoint(pt_backbone, flax_params, attn_params, pytorch_dump_folder_path, config_path=None): repo = Repository(pytorch_dump_folder_path, clone_from=f'google/{pytorch_dump_folder_path}') repo.git_pull() if (config_path is not None): config = OwlViTConfig.from_pretrained(c...
def RRSE_torch(pred, true, mask_value=None): if (mask_value != None): mask = torch.gt(true, mask_value) pred = torch.masked_select(pred, mask) true = torch.masked_select(true, mask) return (torch.sqrt(torch.sum(((pred - true) ** 2))) / torch.sqrt(torch.sum(((pred - true.mean()) ** 2))))
class VideoDownloader(VideoCompressor): def __getitem__(self, idx): video_path = self.csv['video_path'].values[idx] output_file = self.csv['feature_path'].values[idx] if (not os.path.isfile(output_file)): os.makedirs(os.path.dirname(output_file), exist_ok=True) cmd = ...