code
stringlengths
101
5.91M
def test(model, test_loader, theta, device): top_1 = 0 top_10 = 0 len_test = len(test_loader) for triplets in tqdm(test_loader): batch_text = [] batch_img = [] for i in range(len(triplets[1])): (subject, predicate, object) = triplets[1][i].split('--') batc...
def show_ae(autoencoder, data): x_test = data.x_test decoded_imgs = autoencoder.predict(x_test) print(decoded_imgs.shape, data.x_test.shape) if (backend.image_data_format() == 'channels_first'): (N, n_ch, n_i, n_j) = x_test.shape else: (N, n_i, n_j, n_ch) = x_test.shape x_test = ...
def modify_tilt(path, bin_factor, exclude_angles=[]): f = open(path, 'r') content = [l.strip() for l in f] f.close() if (not ('UseGPU 0' in content)): content.insert((len(content) - 1), 'UseGPU 0') binned_idx = [i for (i, s) in enumerate(content) if ('IMAGEBINNED' in s)][0] content[binne...
class Decoder(nn.Module): def __init__(self, layers, norm_layer=None, projection=None): super(Decoder, self).__init__() self.layers = nn.ModuleList(layers) self.norm = norm_layer self.projection = projection def forward(self, x, cross, x_mask=None, cross_mask=None, tau=None, delt...
class Transformer(AbstractTransformer): def __init__(self, translation_x=8, translation_y=8): self.max_tx = translation_x self.max_ty = translation_y super().__init__() def _create_transformation_list(self): transformation_list = [] for (is_flip, tx, ty, k_rotate) in iter...
def _get_default_logging_level(): env_level_str = os.getenv('DIFFUSERS_VERBOSITY', None) if env_level_str: if (env_level_str in log_levels): return log_levels[env_level_str] else: logging.getLogger().warning(f"Unknown option DIFFUSERS_VERBOSITY={env_level_str}, has to be ...
def _construct_agent(algo): if algo.isdigit(): agent = None agent_type = 'nn' net_dir = (('./train_package/' + algo) + '/netfile') elif (algo in ALGOS): agent = ALGOS[algo]() agent_type = 'traditional' net_dir = None else: message = ((('The algorithm n...
def write_vocab(word2idx, idx2word, path): f = open(os.path.join(OUTPUT_PATH, 'vocab.pkl'), 'wb') pickle.dump([word2idx, idx2word], f) f.close()
def load_csv(path): df = pd.read_csv(path, compression='gzip', dtype='str', header=None) return list(df[0].values)
def seedj(epoch, j, cycle, conts): return ((int(os.environ['MYSEED']) + ((epoch + j) * conts)) + ((cycle + 1) * 10))
def run_test(rank, world_size, tmp_file): set_seed(42) os.environ['RANK'] = f'{rank}' os.environ['WORLD_SIZE'] = f'{world_size}' atorch.init_distributed('nccl') torch.cuda.set_device(rank) device = torch.device(f'cuda:{rank}') model_params = ModelArgs(dim=64, n_layers=4, n_heads=8, vocab_siz...
class DetectionEvaluator(object): __metaclass__ = ABCMeta def __init__(self, categories): self._categories = categories def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): pass def add_single_detected_image_info(self, image_id, detections_dict): pass def...
def get_grad_step_data(args, labels, wandb_username, wandb_project): data_experiments_auc = [] data_experiments_ap = [] for (runs, label) in zip(labels.get('experiments_key'), labels.get('experiments_name')): if (len(runs[0]) > 0): for exp_key in runs: try: ...
class BratsDataset(Dataset): def __init__(self, data: list, sampling_method, patch_size: tuple, compute_patch: bool=False, transform=None): self.data = data self.sampling_method = sampling_method self.patch_size = patch_size self.compute_patch = compute_patch self.transform =...
def remap_edge_list(e_list: List[tuple], bipartite_graph: bool=False, ret_map: bool=False) -> Union[(List[tuple], tuple)]: e_list = [[str(v) for v in e] for e in e_list] if bipartite_graph: (u_set, v_set) = (set(), set()) for (u, v) in e_list: u_set.add(u) v_set.add(v) ...
def run(): logging_GOCD.init_logging(log_file_path=param_log_file_path, log_file_mode=param_log_mode) logging.info('Preparing before training.') sys.path.append('..') from symbol_farm import symbol_10_560_25L_8scales_v1 as net (net_symbol, data_names, label_names) = net.get_net_symbol() net_init...
_grad() def copy_params_and_buffers(src_module, dst_module, require_all=False): assert isinstance(src_module, torch.nn.Module) assert isinstance(dst_module, torch.nn.Module) src_tensors = dict(named_params_and_buffers(src_module)) for (name, tensor) in named_params_and_buffers(dst_module): asser...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x1(inplanes, planes, stride) self.bn1 = nn.BatchNorm1d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = c...
class Cat(Dataset): def __init__(self, dataset_path, output_size, **kwargs): super().__init__() self.data = glob.glob(dataset_path) assert (len(self.data) > 0), "Can't find data; make sure you specify the path to your dataset" self.transform = transforms.Compose([transforms.CenterCro...
class AGNN(nn.Module): def __init__(self, g, in_feats, n_hidden, n_classes, n_layers, init_beta=1, learn_beta=1): super(AGNN, self).__init__() self.g = g self.proj = nn.Sequential(nn.Linear(in_feats, n_hidden), nn.ReLU()) self.layers = nn.ModuleList([AGNNConv(init_beta, learn_beta, a...
class InitializeParams(WorkDoneProgressParams): processId: (integer | null) clientInfo: NotRequired[ClientInfo] locale: NotRequired[string] rootPath: NotRequired[(string | null)] rootUri: (DocumentUri | null) initializationOptions: NotRequired[LSPAny] capabilities: ClientCapabilities tra...
('/signup', methods=['POST']) def signup(): if g.loggedIn: flash('You can not sign up while you are already logged in.', 'danger') return redirect(url_for('articles.index')) user_dict = request.form.to_dict() try: user = User(user_dict) except ValidationError as e: flash(...
class CDCM(nn.Module): def __init__(self, in_channels, out_channels): super(CDCM, self).__init__() self.relu1 = nn.ReLU() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, padding=0) self.conv2_1 = nn.Conv2d(out_channels, out_channels, kernel_size=3, dilation=5, paddin...
.parametrize('parallel', [False, True]) def test_hyper_reconf(parallel): if parallel: pytest.importorskip('distributed') pytest.importorskip('opt_einsum') import opt_einsum as oe (eq, shapes) = oe.helpers.rand_equation(30, reg=5, seed=42, d_max=3) optimizer = ctg.HyperOptimizer(max_repeats=1...
def id2trainId(label, reverse=False): label_copy = label.copy() if reverse: for (v, k) in id_to_trainid.items(): label_copy[(label == k)] = v else: for (k, v) in id_to_trainid.items(): label_copy[(label == k)] = v return label_copy
def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): end_points = {} if (depth_multiplier <= 0): raise ValueError('depth_multiplier is not greater than zero.') depth = (lambda d: max(int((d * depth_multiplier)), min_depth)) with tf.variable_sc...
.parametrize('dist', ['normal', 'binary']) def test_dense_model(dist): shape = (1,) units = 20 feature_size = 20 layers = 5 batch_size = 2 features = torch.randn((batch_size, feature_size)) try: dense = DenseModel(feature_size, shape, layers, units, dist) except NotImplementedErr...
def main(n_splits=10, random_state=1): logger = util.get_logger('log.txt') logger.info('timestamp: {}'.format(datetime.now())) start = time.time() df = pd.read_csv('file2ed11cebe25.csv') print('\ntime to read in data...{:.3f}s'.format((time.time() - start))) columns = list(df.columns) remove...
def wrap_action(self, action): action = np.squeeze(action) out = (((action * (self.action_high - self.action_low)) / 2) + ((self.action_high + self.action_low) / 2.0)) return out
class InputHook(object): def __init__(self): super(InputHook, self).__init__() self.inputs = None def hook(self, module, input, output): self.inputs = input def clear(self): self.inputs = None
def test_log_volume() -> None: box1 = BoxTensor(torch.tensor([[[1, 1], [3, 5]], [[1, 1], [3, 3]]]).float()) box2 = BoxTensor(torch.tensor([[[2, 0], [6, 2]], [[3, 2], [4, 4]]]).float()) volume_layer = HardVolume(log_scale=True) expected1 = torch.tensor([2.07944, 1.3862]).float() expected2 = torch.ten...
def conv3d(inputs, num_output_channels, kernel_size, scope, stride=[1, 1, 1], padding='SAME', use_xavier=True, stddev=0.001, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: (kernel_d, kernel_h, kernel_w) = kernel_size num_i...
class STL(nn.Module): def __init__(self, hp): super().__init__() self.embed = nn.Parameter(torch.FloatTensor(hp.token_num, (hp.E // hp.num_heads))) d_q = (hp.E // 2) d_k = (hp.E // hp.num_heads) self.attention = MultiHeadAttention(query_dim=d_q, key_dim=d_k, num_units=hp.E, n...
class Optimizer(): def __init__(self, para, target): trainable = target.parameters() optimizer_name = para.optimizer lr = para.lr module = import_module('torch.optim') self.optimizer = getattr(module, optimizer_name)(trainable, lr=lr) try: if (para.lr_sche...
def powell_bs(x): return (((((10000.0 * x[0]) * x[1]) - 1) ** 2) + ((((- x[0]).exp() + (- x[1]).exp()) - 1.0001) ** 2))
class DNN(models.Sequential): def __init__(self, Nin, Nh_l, Nout): super().__init__() self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1')) self.add(layers.Dropout(0.01)) self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2')) sel...
def run_wrapper(submit_config: SubmitConfig) -> None: is_local = (submit_config.submit_target == SubmitTarget.LOCAL) if is_local: logger = util.Logger(file_name=os.path.join(submit_config.run_dir, 'log.txt'), file_mode='w', should_flush=True) else: logger = util.Logger(file_name=None, should...
def main_defense_script(): classifier_net = cifar_loader.load_pretrained_cifar_resnet(flavor=32) classifier_net.eval() cifar_normer = utils.DifferentiableNormalize(mean=config.CIFAR10_MEANS, std=config.CIFAR10_STDS) if True: FGSM_L_INF = (8.0 / 255.0) FGSM_TRAINING_ATTACK_PROPORTION = 0....
class InPlane(ReSampleDomain): def do_re_sample(self): self.points = sc.Variables(in_line.sample_boundary(param_ranges=param_ranges, density=DENSITY, low_discrepancy=True)).to_torch_tensor_() self.constraints = {'T': torch.ones_like(self.points['x'])}
class SPVCNN(nn.Module): def __init__(self, **kwargs): super().__init__() self.dropout = kwargs['dropout'] cr = kwargs.get('cr', 1.0) cs = [32, 64, 128, 96, 96] cs = [int((cr * x)) for x in cs] if (('pres' in kwargs) and ('vres' in kwargs)): self.pres = kw...
('Please use `bigdl.orca.automl.hp` instead.') class MTNetGridRandomRecipe(Recipe): def __init__(self, num_rand_samples=1, epochs=5, training_iteration=10, time_step=[3, 4], long_num=[3, 4], cnn_height=[2, 3], cnn_hid_size=[32, 50, 100], ar_size=[2, 3], batch_size=[32, 64]): super(self.__class__, self).__in...
def strip_tokenizer_prefix(model_config, token, ellipsis_partial_tokens=False): token = token.lstrip(model_config['token_prefix']) token = token.lstrip(model_config['partial_token_prefix']) token = token.lstrip(' ') return token
class Exponential(Scheduler): def __init__(self, decay_step: int, decay_rate: float, stair_case: bool=False) -> None: from bigdl.dllib.optim.optimizer import Exponential as BExponential self.scheduler = BExponential(decay_step, decay_rate, stair_case) def get_scheduler(self) -> 'optimizer.Expone...
def find_sub_seq(seq_a, seq_b, shift=0, uncased=False, lemmatizer=None): if uncased: seq_a = [token.lower() for token in seq_a] seq_b = [token.lower() for token in seq_b] if (lemmatizer is not None): seq_a = [lemmatizer.lemmatize(token) for token in seq_a] seq_b = [lemmatizer.lem...
class NormLayer(nn.Module): def __init__(self, mu=0.1307, std=0.3081): super(NormLayer, self).__init__() self.mean = mu self.std = std def forward(self, x): return ((x - self.mean) / self.std)
def main(opts): hvd.init() n_gpu = hvd.size() device = torch.device('cuda', hvd.local_rank()) torch.cuda.set_device(hvd.local_rank()) rank = hvd.rank() opts.rank = rank LOGGER.info('device: {} n_gpu: {}, rank: {}, 16-bits training: {}'.format(device, n_gpu, hvd.rank(), opts.fp16)) if (op...
def configure_setup(dataset_name, split_seed): logger.info('Evaluating dataset: {} split seed: {}'.format(dataset_name, split_seed)) setup = get_setup() setup['datasets'] = [dataset_name] setup['split_seed'] = split_seed dump_yaml(setup, os.getcwd(), 'setup.yml')
def test_osipkovmerritt_nfw_dens_massprofile(): pot = potential.NFWPotential(amp=2.3, a=1.3) ras = [2.3, 5.7] for ra in ras: dfh = osipkovmerrittNFWdf(pot=pot, ra=ra) numpy.random.seed(10) samp = dfh.sample(n=100000) tol = (5 * 0.001) check_spherical_massprofile(samp,...
class NormalizeVideo(object): def __init__(self, mean, std, inplace=False): self.mean = mean self.std = std self.inplace = inplace def __call__(self, clip): return F.normalize(clip, self.mean, self.std, self.inplace) def __repr__(self): return (self.__class__.__name__...
def get_windows_from_folder(folder, width=56, compressed=True): lvls = get_lvls(folder) (str2index, index2str, types) = build_indeces(lvls, compressed) windows = get_windows(lvls, width, str2index) return (windows, types, index2str)
class IMSATTrainer(_Trainer): def __init__(self, model: Model, train_loader: DataLoader, val_loader: DataLoader, max_epoch: int=1, save_dir: str='./runs/IMSAT', checkpoint_path: str=None, device='cpu', config: dict=None) -> None: super().__init__(model, train_loader, val_loader, max_epoch, save_dir, checkpo...
def get_1x_lr_params(model): b = [model.xception_features] for i in range(len(b)): for k in b[i].parameters(): if k.requires_grad: (yield k)
def make_builder(out_file, impl, vocab_size=None): if (impl == 'mmap'): return MMapIndexedDatasetBuilder(out_file, dtype=__best_fitting_dtype(vocab_size)) else: return IndexedDatasetBuilder(out_file)
def test_fuse_conv_bn(): inputs = torch.rand((1, 3, 5, 5)) modules = nn.ModuleList() modules.append(nn.BatchNorm2d(3)) modules.append(ConvModule(3, 5, 3, norm_cfg=dict(type='BN'))) modules.append(ConvModule(5, 5, 3, norm_cfg=dict(type='BN'))) modules = nn.Sequential(*modules) fused_modules =...
class Evaluation(object): def __init__(self, split_tag, instrType, mapFile=''): self.error_margin = 3.0 self.splits = split_tag bboxDir = osp.join(file_path, 'data', 'BBox') (self.objProposals, self.obj2viewpoint) = self.loadObjProposals(bboxDir) self.gt = {} self.ins...
class INFALL(object): def __init__(self, t, sfr): self.t = t self.sfr = sfr def constant(self, paramet=1): amount = paramet self.infall = (np.zeros(len(self.t)) + amount) def linear(self, paramet=(6.3, (- 0.5))): (start, slope) = paramet def polynomial(self, param...
class FactorGNNZinc(nn.Module): def __init__(self, g, num_layers, in_dim, num_hidden, num_latent, feat_drop, residual, num_atom_type, num_bond_type): super(FactorGNNZinc, self).__init__() self.g = g self.layers = nn.ModuleList() self.BNs = nn.ModuleList() self.feat_drop = fea...
_module(force=True) class DiceLoss(nn.Module): def __init__(self, use_sigmoid=True, activate=True, reduction='mean', naive_dice=False, loss_weight=1.0, eps=0.001): super(DiceLoss, self).__init__() self.use_sigmoid = use_sigmoid self.reduction = reduction self.naive_dice = naive_dice ...
def str2bool(v): if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.ArgumentTypeError('Unsupported value encountered.')
def test_captured_utf8_4byte_offset1(capsys): msg = '\U0010ffff' msg = ('1' + (msg * ((1024 // len(msg)) + 1))) m.captured_output_default(msg) (stdout, stderr) = capsys.readouterr() assert (stdout == msg) assert (stderr == '')
def get_compiler() -> str: compiler = 'gcc' if (shutil.which(compiler) is None): compiler = 'cc' if (shutil.which(compiler) is None): raise ValueError('compiler (`gcc` or `cc`) not present. install one first.') return compiler
class WatchModel(Callback): def __init__(self, log: str='gradients', log_freq: int=100): self.log = log self.log_freq = log_freq _zero_only def on_train_start(self, trainer, pl_module): logger = get_wandb_logger(trainer=trainer) logger.watch(model=trainer.model, log=self.log,...
def build_tokenizer(args): global tokenizer if (tokenizer is None): tokenizer = AutoTokenizer.from_pretrained(args.pretrained_model) logger.info('Build tokenizer from {}'.format(args.pretrained_model))
class KITTI_RAW(object): def __init__(self, data_dir, static_frames_txt, test_scenes_txt): self.data_dir = data_dir self.static_frames_txt = static_frames_txt self.test_scenes_txt = test_scenes_txt def __len__(self): raise NotImplementedError def collect_static_frame(self): ...
class Chebbase_prop(MessagePassing): def __init__(self, K, q, bias=True, **kwargs): super(Chebbase_prop, self).__init__(aggr='add', **kwargs) self.K = K self.temp = Parameter(torch.Tensor((self.K + 1))) self.reset_parameters() self.q = q def reset_parameters(self): ...
class runningScore_recall(object): def __init__(self, n_classes): self.n_classes = n_classes self.confusion_matrix = np.zeros((n_classes, n_classes)) def _fast_hist(self, label_true, label_pred, n_class): mask = ((label_true >= 0) & (label_true < n_class)) hist = np.bincount(((n_...
class A2CModel(): def __init__(self, max_time_steps, *args, **kwargs): super().__init__(*args, **kwargs) self.entropy_coefficient = 0.01 self.value_coefficient = 0.5 self.max_gradient_norm = 0.5 self.rms_alpha = 0.99 self.rms_epsilon = 1e-05 self.data_parallel...
class OutFile(object): def __init__(self, outfile=None, silent=False, overwrite=False): if (outfile is None): self.f = sys.stdout self.open = False return self.open = isinstance(outfile, file) if (not self.open): filename = os.path.expanduser(o...
def main_worker(gpu, args): args.gpu = gpu args.rank = gpu print(f'Process Launching at GPU {gpu}') if args.distributed: torch.cuda.set_device(args.gpu) dist.init_process_group(backend='nccl') print(f'Building train loader at GPU {gpu}') train_loader = get_loader(args, split=args...
def adagrad(loss_or_grads, params, learning_rate=1.0, epsilon=1e-06): grads = get_or_compute_grads(loss_or_grads, params) updates = OrderedDict() for (param, grad) in zip(params, grads): value = param.get_value(borrow=True) accu = theano.shared(np.zeros(value.shape, dtype=value.dtype), broad...
def unzip_dataset(data_name): if (data_name == 'cora'): subprocess.call(['unzip', 'datasets/cora.zip', '-d', 'datasets/cora']) subprocess.call(['rm', 'datasets/cora.zip']) print('Downloaded the cora dataset!\n') elif (data_name == 'ppi'): subprocess.call(['unzip', 'datasets/ppi.z...
def test_wasserstein_bounds(): np.random.seed(341) d2 = 5.0 stdev = 3.5 samples = norm.rvs(scale=stdev, size=MC_SAMPLES) res = viabel.wasserstein_bounds(d2, samples=samples) np.testing.assert_allclose(res['W1'], ((2 * stdev) * np.sqrt(np.expm1(d2))), rtol=MC_TOL, err_msg='incorrect W1 value') ...
def fuse_source_reference_output(output_mp4_path, src_img_paths, ref_img_paths, out_img_paths, audio_path=None, image_size=512, pad=10, fps=25, pool_size=15): global default_ffmpeg_vcodec, default_ffmpeg_pix_fmt, default_ffmpeg_exe_path ffmpeg_exc_path = os.environ.get('ffmpeg_exe_path', default_ffmpeg_exe_path...
class TFSegformerEncoder(tf.keras.layers.Layer): def __init__(self, config: SegformerConfig, **kwargs): super().__init__(**kwargs) self.config = config drop_path_decays = [x.numpy() for x in tf.linspace(0.0, config.drop_path_rate, sum(config.depths))] embeddings = [] for i in...
def wt_xxz_output_to_disk(dir, fname_list, full_docs, decision): for (output, doc, dec) in zip(fname_list, full_docs, decision): sent_picked = [doc[idx] for idx in dec] wt_content = '\n'.join(sent_picked) with open(os.path.join(dir, (output + '.txt')), 'w') as fd: fd.write(wt_con...
def MiDaS_small(pretrained=True, **kwargs): model = MidasNet_small(None, features=64, backbone='efficientnet_lite3', exportable=True, non_negative=True, blocks={'expand': True}) if pretrained: checkpoint = ' state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=torch.device('c...
def fully_connected(x, units, use_bias=True, sn=False, scope='fully_0'): with tf.variable_scope(scope): x = flatten(x) shape = x.get_shape().as_list() channels = shape[(- 1)] if sn: w = tf.get_variable('kernel', [channels, units], tf.float32, initializer=weight_init, regu...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) 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, data_args,...
def index(x, start=None, end=None): if isinstance(x, list): return [index_numpy(x_i, start, end) for x_i in x] else: return index_numpy(x, start, end)
class PatchEmbed(nn.Module): def __init__(self, patch_size=16, stride=16, padding=0, in_chans=3, embed_dim=768, norm_layer=None): super().__init__() patch_size = to_2tuple(patch_size) stride = to_2tuple(stride) padding = to_2tuple(padding) self.proj = nn.Conv2d(in_chans, embe...
def train_net(args, config): (logger, final_output_path) = create_logger(config.OUTPUT_PATH, args.cfg, config.DATASET.TRAIN_IMAGE_SET, split='train') model_prefix = os.path.join(final_output_path, config.MODEL_PREFIX) if (args.log_dir is None): args.log_dir = os.path.join(final_output_path, 'tensorb...
def chunk_pad(it, size, padval=None): it = chain(iter(it), repeat(padval)) return iter((lambda : tuple(islice(it, size))), ((padval,) * size))
def move_cache(old_cache_dir: Optional[str]=None, new_cache_dir: Optional[str]=None) -> None: if (new_cache_dir is None): new_cache_dir = DIFFUSERS_CACHE if (old_cache_dir is None): old_cache_dir = old_diffusers_cache old_cache_dir = Path(old_cache_dir).expanduser() new_cache_dir = Path(...
def run_task(arg_vv, log_dir, exp_name): if (arg_vv['algorithm'] == 'planet'): from planet.config import DEFAULT_PARAMS else: raise NotImplementedError vv = DEFAULT_PARAMS vv.update(**arg_vv) vv = update_env_kwargs(vv) vv['max_episode_length'] = vv['env_kwargs']['horizon'] lo...
class MSGMSLoss(Module): def __init__(self, num_scales: int=3, in_channels: int=3) -> None: super().__init__() self.num_scales = num_scales self.in_channels = in_channels (self.prewitt_x, self.prewitt_y) = self._create_prewitt_kernel() self.mean_filter = (torch.ones((1, 1, 21...
def test_stack_fusion_new(): fusion_module = CrossAttentionNew(32, 2, (- 1)) print('CrossAttention init success!') fake_img = Variable(torch.randn(16, 49, 32)) fake_txt = Variable(torch.randn(8, 14, 32)) score = fusion_module(fake_img, fake_txt, get_score=True) print(score.size()) print('---...
def triplet_loss(q_vec, pos_vecs, neg_vecs, margin): best_pos = best_pos_distance(q_vec, pos_vecs) num_neg = neg_vecs.get_shape()[1] batch = q_vec.get_shape()[0] query_copies = tf.tile(q_vec, [1, int(num_neg), 1]) best_pos = tf.tile(tf.reshape(best_pos, ((- 1), 1)), [1, int(num_neg)]) m = tf.fil...
def combine_datasets(config, output_file_name='combined.tsv'): filedir = config['file_directory'] output_file = os.path.join(filedir, output_file_name) combined_df = pd.DataFrame() for dataset in __filter_datasets_from_config(config): for ds_file in dataset.files: try: ...
def generate_ring_data(smiles, n_pos, n_neg): ring_data = {} mol = Chem.MolFromSmiles(smiles) ssr = [list(x) for x in Chem.GetSymmSSSR(mol)] n_rings = len(ssr) ring_indices = list(range(n_rings)) if (n_rings <= 1): return ring_data for idx in range(n_pos): ring_idx = random.s...
def build_molecules(one_hot, x, node_mask, is_geom, margins=const.MARGINS_EDM): molecules = [] for i in range(len(one_hot)): mask = (node_mask[i].squeeze() == 1) atom_types = one_hot[i][mask].argmax(dim=1).detach().cpu() positions = x[i][mask].detach().cpu() mol = build_molecule(...
class Bretschneider2016lol(dataset.Dataset): name = 'bretschneider2016lol' url = ' hash = '901e0d51428f34b94bf6b3f59b0e9cf71dabe94fc74fd81fd1e9be199d2902bc' files = [{'name': 'bretschneider2016en_lol.csv', 'language': 'en', 'type': 'training', 'platform': 'League of Legends'}] comment = ' ' lice...
class ResConvBlock(nn.Module): def __init__(self, n_in, n_state): super().__init__() self.model = nn.Sequential(nn.ReLU(), nn.Conv2d(n_in, n_state, 3, 1, 1), nn.ReLU(), nn.Conv2d(n_state, n_in, 1, 1, 0)) def forward(self, x): return (x + self.model(x))
def load_train_labels(data_folder: Path, city: str, competition: str): train_label_frames = [] train_label_files = sorted((((data_folder / 'train') / city) / 'labels').glob(f'{competition}_labels_*.parquet')) for train_label_file in tqdm.tqdm(train_label_files, total=len(sorted(train_label_files))): ...
class ATLoss(nn.Module): def __init__(self): super().__init__() self.mode = 'code' if (self.mode not in ('code', 'paper')): raise ValueError('mode `{}` is not expected'.format(self.mode)) def attention_transfer_paper(feature_map): return normalize(feature_map.pow(2).s...
def _get_max_epoch_model(output_dir): fn_model_list = glob.glob(os.path.join(output_dir, 'model.*.bin')) fn_optim_list = glob.glob(os.path.join(output_dir, 'optim.*.bin')) if ((not fn_model_list) or (not fn_optim_list)): return None both_set = (set([int(Path(fn).stem.split('.')[(- 1)]) for fn in...
def test_initialization(): d = [Exponential(), Exponential()] model = SparseHMM(d) assert (model.inertia == 0.0) assert (model.frozen == False) assert (model.n_distributions == 2) assert_raises(AttributeError, getattr, model, '_xw_sum') assert_raises(AttributeError, getattr, model, '_xw_star...
class FFTOp(gof.Op): __props__ = () def output_type(self, inp): return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim)) def make_node(self, a, s=None): a = T.as_tensor_variable(a) if (a.ndim < 3): raise TypeError((('%s: input must have dimension >= 3, wit...
class PSI(JavaValue): def __init__(self, jvalue=None, *args): self.bigdl_type = 'float' super().__init__(jvalue, self.bigdl_type, *args) def get_salt(self, secure_code=''): return callBigDlFunc(self.bigdl_type, 'psiGetSalt', self.value, secure_code) def upload_set(self, ids, salt): ...
def make_model(): inputs = tf.keras.Input(shape=(None,), dtype='int64') x = layers.Embedding(max_features, embedding_dim)(inputs) predictions = make_backbone()(x) model = Model(inputs, predictions) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model
class SubsetSampler(Sampler): def __init__(self, indices): self.indices = indices def __iter__(self): return iter(self.indices) def __len__(self): return len(self.indices)