code
stringlengths
101
5.91M
_grad() def evaluation(model, data_loader, tokenizer, device, config): model.eval() metric_logger = utils.MetricLogger(delimiter=' ') header = 'Generate VQA test result:' print_freq = 50 result = [] answer_list = [(answer + config['eos']) for answer in data_loader.dataset.answer_list] answe...
class AnchorGenerator(object): __metaclass__ = ABCMeta def name_scope(self): pass def check_num_anchors(self): return True def num_anchors_per_location(self): pass def generate(self, feature_map_shape_list, **params): if (self.check_num_anchors and (len(feature_map_sh...
def main(): parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') parser.add_argument('data', metavar='DIR', help='path to dataset') parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18', choices=model_names, help=(('model architecture: ' + ' | '.join(model_names)) + ' (...
def fill_parameters(parameters, default_parameters, name='unknown function'): string = '' if ('verbose' not in parameters.keys()): if ('verbose' not in default_parameters.keys()): default_parameters['verbose'] = 0 parameters['verbose'] = default_parameters['verbose'] verbose = pa...
class _DeformConv(Function): def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64): if ((input is not None) and (input.dim() != 4)): raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim())) ...
class _NCEGeneratorState(object): def __init__(self, context_size): self._doc_id = multiprocessing.RawValue('i', 0) self._in_doc_pos = multiprocessing.RawValue('i', context_size) self._lock = multiprocessing.Lock() def update_state(self, dataset, batch_size, context_size, num_examples_in...
def successors(ctree, cerrors, gold): for merror in cerrors.missing: for eerror in cerrors.extra: if (merror[1] == eerror[1]): (yield gen_different_label_successor(ctree, eerror[1], eerror[2], merror[2])) for error in cerrors.missing: (yield gen_missing_successor(ctre...
def test_masked_softmax_nll(): rng = np.random.RandomState(9823174) n_data = 22 data_dim = 45 logits_np = (4 * rng.randn(n_data, data_dim)) mask_np = (rng.randn(n_data, data_dim) > 0.0) while (not np.all(np.sum((mask_np == 1), axis=1))): mask_np = (rng.randn(n_data, data_dim) > 0.0) ...
class LongformerForSequenceClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class ResNetSharingClassifier(SharingClassifier): block = BasicBlock num_blocks = [2, 2, 2, 2] norm_layer = nn.InstanceNorm2d def __init__(self, params, experts): super().__init__(params, experts) self.precursors = [expert.d for expert in self.experts[1:]] first = (len(self.precu...
def write_to_ray(idx, partition, redis_address, redis_password, partition_store_names): init_ray_if_not(redis_address, redis_password) ip = ray._private.services.get_node_ip_address() local_store_name = None for name in partition_store_names: if name.endswith(ip): local_store_name = ...
class TransFuse_L(nn.Module): def __init__(self, num_classes=1, drop_rate=0.2, normal_init=True, pretrained=False): super(TransFuse_L, self).__init__() self.resnet = resnet50() if pretrained: self.resnet.load_state_dict(torch.load('/home/chenfei/.cache/torch/hub/checkpoints/resne...
def get_early_stopping_callback(metric, patience): return EarlyStopping(monitor=f'val_{metric}', mode=('min' if ('loss' in metric) else 'max'), patience=patience, verbose=True)
def predict_compression(predictor, inp_batch_json, margin=0): output = predictor.predict_batch_json(inp_batch_json) rts = [] comps = [] for (idx, out) in enumerate(output): tag_logits = out['tag_logits'] tokens = inp_batch_json[idx]['sentence'] original_len = len(tokens) ...
def get_declarative_equations(model, question, prompt, max_tokens, stop_token, temperature): prompt = prompt.format(question=question) response = openai.Completion.create(model=model, prompt=prompt, max_tokens=max_tokens, stop=stop_token, temperature=temperature, top_p=1) result = response['choices'][0]['te...
class dataset(): def __init__(self, root=None, train=True, example_weight=None): self.root = root self.train = train self.transform = transforms.ToTensor() if self.train: train_data_path = os.path.join(root, 'train_data') train_labels_path = os.path.join(root,...
def convert_cityscapes_instance_only(data_dir, out_dir): sets = ['gtFine_val', 'gtFine_train', 'gtFine_test'] ann_dirs = ['gtFine_trainvaltest/gtFine/val', 'gtFine_trainvaltest/gtFine/train', 'gtFine_trainvaltest/gtFine/test'] json_name = 'instancesonly_filtered_%s.json' ends_in = '%s_polygons.json' ...
def get_tasks(args, task_names, max_seq_len): tasks = [] for name in task_names: assert (name in NAME2INFO), 'Task not found!' task = NAME2INFO[name][0](args, NAME2INFO[name][1], max_seq_len, name) tasks.append(task) logging.info('\tFinished loading tasks: %s.', ' '.join([task.name f...
def EpochModelCheckpoint(*args, **kwargs): callback = pl.callbacks.ModelCheckpoint(*args, **kwargs) _on_validation_end = callback.on_validation_end _on_save_checkpoint = callback.on_save_checkpoint def on_validation_end(*args, **kwargs): return def on_save_checkpoint(trainer, module, *args):...
def conv2d(in_channels, out_channels, kernel_size=3, stride=1, dilation=1, groups=1): return nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=dilation, dilation=dilation, bias=False, groups=groups), nn.BatchNorm2d(out_channels), nn.LeakyReLU(0.2, inplace=True))
class IP(nn.Module): def __init__(self, args): super(IP, self).__init__() self.model_recognition = LightCNN_29Layers_v2(num_classes=346) self.model_recognition = torch.nn.DataParallel(self.model_recognition).cuda() checkpoint = torch.load('lightCNN_pretrain.pth.tar') self.mod...
def analyse_obs_spaces(env_obs_space, model_obs_space): entries_only_in_env = [] entries_only_in_model = [] entries_in_both_but_with_different_values = [] for key in env_obs_space.keys(): if (key not in model_obs_space.keys()): entries_only_in_env.append(key) elif ((key in mo...
class BufferList(torch.nn.Module): def __init__(self, buffers): super(BufferList, self).__init__() self.buffers = [] for (i, b) in enumerate(buffers): name = '_buffer_{}'.format(i) self.register_buffer(name, b) self.buffers.append(getattr(self, name)) ...
def plot_acc(history): plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc=0)
def structure_encoding(atoms): enc = [0 for _ in range(55)] for atom in atoms: enc[atom.GetAtomicNum()] += 1 return enc
class VKITTI(Dataset): def __init__(self, data_dir_root, do_kb_crop=True): import glob self.image_files = glob.glob(os.path.join(data_dir_root, 'test_color', '*.png')) self.depth_files = [r.replace('test_color', 'test_depth') for r in self.image_files] self.do_kb_crop = True ...
class DAPPM(nn.Module): def __init__(self, inplanes, branch_planes, outplanes, BatchNorm=nn.BatchNorm2d): super(DAPPM, self).__init__() bn_mom = 0.1 self.scale1 = nn.Sequential(nn.AvgPool2d(kernel_size=5, stride=2, padding=2), BatchNorm(inplanes, momentum=bn_mom), nn.ReLU(inplace=True), nn.C...
def get_tl_line_values_gt(line, LTRB=True, withTranscription=False, withConfidence=False, imWidth=0, imHeight=0): confidence = 0.0 transcription = '' points = [] if LTRB: raise Exception('Not implemented.') else: if (withTranscription and withConfidence): raise 'not imple...
_grad() def concat_all_gather(tensor): if (get_mpi_size() == 1): return tensor if (not is_hvd_initialized()): tensors_gather = [torch.ones_like(tensor) for _ in range(get_mpi_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) output = torch.cat(tensors_...
class LinearWarmUpScheduler(LRScheduler): def __init__(self, optimizer, warmup, total_steps, last_epoch=(- 1)): self.warmup = warmup self.total_steps = total_steps super(LinearWarmUpScheduler, self).__init__(optimizer, last_epoch) def get_lr(self): progress = (self.last_epoch / s...
class DesiTileFileHandler(DesiDataFileHandler): def __init__(self, analysis_type, use_non_coadded_spectra, logger, input_directory): self.input_directory = input_directory super().__init__(analysis_type, use_non_coadded_spectra, logger) def read_file(self, filename, catalogue): try: ...
def seed_all(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def clip_norm(g, c, n): if (c > 0): g = T.switch(T.ge(n, c), ((g * c) / n), g) return g
def sim_gcn(reps): n = reps.shape[0] sim_mat = np.zeros([n, n]) return cosine_similarity(reps, reps)
class OpWeights(JsonSerializer): def __init__(self, weights_data: dict): super().__init__() self.dtype: str = weights_data.get('dtype', None) self.granularity: str = weights_data.get('granularity', None)
def ProcessLineForNonScoredWords(a): global num_lines, num_correct_lines, ref_change_stats try: assert (len(a) == 8) num_lines += 1 duration = a[3] hyp_word = a[4] ref_word = a[6] edit_type = a[7] if (edit_type == 'ins'): assert (ref_word == '<...
class ImbalanceSVHN(torchvision.datasets.SVHN): cls_num = 10 def __init__(self, root, imb_type='exp', imb_factor=0.01, rand_number=0, split='train', transform=None, target_transform=None, download=False): super(ImbalanceSVHN, self).__init__(root, split, transform, target_transform, download) np....
class VideoRenderer(mp.Process): def __init__(self, display=False, verbose=0, verbose_size=None, output_crop=False, resolution=256, crop_scale=1.2, encoder_codec='mp4v', separate_process=False): super(VideoRenderer, self).__init__() self._display = display self._verbose = verbose sel...
def sample_ddpg_params(trial): gamma = trial.suggest_categorical('gamma', [0.9, 0.95, 0.98, 0.99, 0.995, 0.999, 0.9999]) learning_rate = trial.suggest_loguniform('lr', 1e-05, 1) batch_size = trial.suggest_categorical('batch_size', [16, 32, 64, 128, 256]) buffer_size = trial.suggest_categorical('memory_l...
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=(1.0 / 3), warmup_iters=500, warmup_method='linear', last_epoch=(- 1)): if (not (list(milestones) == sorted(milestones))): raise ValueError('Milestones should be a l...
def _gen_mnasnet_b1(variant, channel_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_c16_noskip'], ['ir_r3_k3_s2_e3_c24'], ['ir_r3_k5_s2_e3_c40'], ['ir_r3_k5_s2_e6_c80'], ['ir_r2_k3_s1_e6_c96'], ['ir_r4_k5_s2_e6_c192'], ['ir_r1_k3_s1_e6_c320_noskip']] model_kwargs = dict(block_args=decode...
def dump_results(results): with open(result_file, 'wb') as f: pickle.dump(dict(results), f)
class TemperatureTanh(nn.Module): def __init__(self, temperature: float=1.0) -> None: super().__init__() assert (temperature != 0.0), 'temperature must be nonzero.' self._T = temperature self.tanh = torch.nn.Tanh() def forward(self, x: Tensor) -> Tensor: return self.tanh(...
class Args(Tap): ckpts_dirs: List[str] split_type: Literal[('random', 'scaffold')] num_folds: int = 10
(kernels.Kernel, TensorLike, TensorLike, TensorLike) def _exact_fallback(kern: kernels.Kernel, Z: TensorLike, u: TensorLike, f: TensorLike, *, L: TensorLike=None, diag: TensorLike=None, basis: AbstractBasis=None, **kwargs): u_shape = tuple(u.shape) f_shape = tuple(f.shape) assert (u_shape[(- 1)] == 1), 'Rec...
class CompositeAudioTransform(AudioTransform): def _from_config_dict(cls, transform_type, get_audio_transform, composite_cls, config=None, return_empty=False): _config = ({} if (config is None) else config) _transforms = _config.get(f'{transform_type}_transforms') if (_transforms is None): ...
class ColumnSample(): basedir = prev_dir(os.getcwd()) def __init__(self, sampletype, column, directory, settings): self.sampletype = sampletype self.column = column self.directory = directory self.settings = settings self.basedir = basedir def featurize(self): ...
class XLNetTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, max_len=None, do_lower_case=False, remove_space=True, keep_accents=False,...
def load_config(args=None, config_file=None, overwrite_fairseq=False): if (args is not None): config_file = args.taskconfig config = recursive_config(config_file) if (config.dataset.subsampling is not None): batch_size = (config.fairseq.dataset.batch_size // config.dataset.subsampling) ...
def prune_outside_window(keypoints, window, scope=None): with tf.name_scope(scope, 'PruneOutsideWindow'): (y, x) = tf.split(value=keypoints, num_or_size_splits=2, axis=2) (win_y_min, win_x_min, win_y_max, win_x_max) = tf.unstack(window) valid_indices = tf.logical_and(tf.logical_and((y >= win...
def print_results(results_path): with open(results_path, 'r') as fp: results = json.load(fp) print('Flags:') for (k, v) in sorted(results['flags'].items()): print('\t{}: {}'.format(k, v)) print('HParams:') for (k, v) in sorted(results['hparams'].items()): print('\t{}: {}'.for...
def log_Logistic_256(x, mean, logvar, average=False, reduce=True, dim=None): bin_size = (1.0 / 256.0) scale = torch.exp(logvar) x = (((torch.floor((x / bin_size)) * bin_size) - mean) / scale) cdf_plus = torch.sigmoid((x + (bin_size / scale))) cdf_minus = torch.sigmoid(x) log_logist_256 = (- torc...
def get_net(input_shape, num_output_channels, net_config): num_input_channels = input_shape[0] if (net_config['type'] == 'mlp'): assert (len(input_shape) == 1) return get_mlp(num_input_channels=num_input_channels, hidden_channels=net_config['hidden_channels'], num_output_channels=num_output_chan...
class ImageParameters(object): def __init__(self): self.width_px = 96 self.height_px = 96 self.arcsec_per_pixel = 0.396 self.world_origin = WorldCoordinate(0, 0) self.band_nelec_per_nmgy = [1000.0 for _ in range(5)] def degrees_per_pixel(self): return (self.arcsec...
def UsesColor(term, color_env_var, color_flag): SetEnvVar('TERM', term) SetEnvVar(COLOR_ENV_VAR, color_env_var) if (color_flag is None): args = [] else: args = [('--%s=%s' % (COLOR_FLAG, color_flag))] p = gtest_test_utils.Subprocess(([COMMAND] + args)) return ((not p.exited) or p...
def ResNet(stack_fn, preact, use_bias, model_name='resnet', include_top=False, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs): if (not ((weights in {'imagenet', None}) or os.path.exists(weights))): raise ValueError('The `weights` argument should be either `Non...
def _is_torch_dtype(x): import torch if isinstance(x, str): if hasattr(torch, x): x = getattr(torch, x) else: return False return isinstance(x, torch.dtype)
def merge_models(shape_size, models_list, out_model_file, avg=True): from keras.models import load_model, save_model, Model from keras.layers import Input, Average if (not os.path.isfile(out_model_file)): models = [] for m_path in models_list: m = load_model(m_path) m...
class FeatureExtractor(): date_time_format_str = '%Y-%m-%d' def __init__(self): self.user_mnr_normalizer = 0 self.prod_mnr_normalizer = 0 self.product_num_ratings = {} self.product_sum_ratings = {} def MNR(self, data, data_type='user'): feature = {} for (i, d)...
def bootstrap_confidence(true, pred, n=10000, confidence=0.9): Rs = [] for _ in range(n): indice = np.random.randint(0, len(pred), len(pred)) t = [true[i] for i in indice] p = [pred[i] for i in indice] (a, b, R, _, std_err) = stats.linregress(t, p) Rs.append(R) Rs = n...
class Conv2d(_ConvBase): def __init__(self, in_size: int, out_size: int, *, kernel_size: Tuple[(int, int)]=(1, 1), stride: Tuple[(int, int)]=(1, 1), padding: Tuple[(int, int)]=(0, 0), activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str=''): ...
def main(): if (not os.path.exists(opt.outf)): os.makedirs(opt.outf) print('Loading dataset ...\n') dataset_train = Dataset(train=True) loader_train = DataLoader(dataset=dataset_train, num_workers=4, batch_size=opt.batchSize, shuffle=True, pin_memory=True) print(('# of training samples: %d\n...
class PaddedAdditiveSelfAttention(snt.AbstractModule): def __init__(self, v_dim, attn_mlp_fn, attn_output_dim, gnn_mlp_fn, max_n_node, train_batch_size, node_embedding_dim, scaling=True, name='padded_additive_self_attention'): super(PaddedAdditiveSelfAttention, self).__init__(name=name) self.v_dim =...
def gen_dis_sample(train_pos_path, train_neg_path, vocab_path, n_dim=100, res_file='discriminator_train_data.npz'): vocab_map = load_vocab(vocab_path) print('vocab length:', len(vocab_map)) train_pos = [] for file in os.listdir(train_pos_path): with open(os.path.join(train_pos_path, file), 'r') ...
_torch _vision class MgpstrProcessorTest(unittest.TestCase): image_processing_class = (ViTImageProcessor if is_vision_available() else None) def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def setUp(self): self.image_size = (3, 32, 128) ...
class ConvLSTM(nn.Module): def __init__(self, input_channels, hidden_channels, kernel_size, step=1, effective_step=[1]): super(ConvLSTM, self).__init__() self.input_channels = ([input_channels] + hidden_channels) self.hidden_channels = hidden_channels self.kernel_size = kernel_size ...
def initialize_dataset_loader(data, stage, params, loader_default_params=None): transform = initialize_transforms(params.pop('transforms'), mean_std=params.pop('mean_std')) dataset = initialize_dataset(data, stage, transform, params.pop('dataset')) loader_params = {**LOADER_DEFAULT_PARAMS, **(loader_default...
def make_fast_softmax_attention(qkv_dim, renormalize_attention=True, numerical_stabilizer=1e-06, nb_features=256, ortho_features=True, ortho_scaling=0.0, redraw_features=True, unidirectional=False, nonnegative_features=True, lax_scan_unroll=1): logging.info('Fast softmax attention: %s features and orthogonal=%s, re...
class TrainingModule(LightningModule): def __init__(self, cfg): super().__init__() if (not logger.isEnabledFor(logging.INFO)): setup_logger() self.cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) self.storage: EventStorage = None self.model = bu...
def plot_numerical_error(): print(f'generating numerical benchmark plots. reading data from {TEST_RESULTS_PICKLE}...') try: with open(TEST_RESULTS_PICKLE, 'rb') as f: results = pickle.load(f) except FileNotFoundError: print('no data of numerical errors found. run the numerical te...
def sum_concat_then_mlp_gnn(make_mlp_fn): node_block = ConcatThenMLPBlock(tf.unsorted_segment_sum, make_mlp_fn) return NodeBlockGNN(node_block)
_loss('bce_kl_combined') class CombinedLoss(nn.Module): def __init__(self, weight_softmax): super().__init__() self.weight_softmax = weight_softmax def forward(self, sample_list, model_output): pred_score = model_output['scores'] target_score = sample_list['targets'] tar_...
class DeadReckoningNodeMultiRobot(DeadReckoningNode): def __init__(self) -> None: super().__init__() def init_node(self, ns='~') -> None: self.imu_pose = rospy.get_param((ns + 'imu_pose')) self.imu_pose = n2g(self.imu_pose, 'Pose3') self.imu_rot = self.imu_pose.rotation() ...
class PerceputalLoss(nn.modules.loss._Loss): def __init__(self, input_range='sigmoid', net_type='vgg_torch', input_preprocessing='corresponding', match=[{'layers': [11, 20, 29], 'what': 'features'}]): if (input_range not in ['sigmoid', 'tanh']): assert False self.net = get_pretrained_net...
def isect_segments__naive(segments): isect = [] if (Real is float): segments = [((s[0], s[1]) if (s[0][X] <= s[1][X]) else (s[1], s[0])) for s in segments] else: segments = [(((Real(s[0][0]), Real(s[0][1])), (Real(s[1][0]), Real(s[1][1]))) if (s[0] <= s[1]) else ((Real(s[1][0]), Real(s[1][1]...
def ts2xy(ts, xaxis, yaxis): if (xaxis == X_TIMESTEPS): x = np.cumsum(ts.l.values) elif (xaxis == X_EPISODES): x = np.arange(len(ts)) elif (xaxis == X_WALLTIME): x = (ts.t.values / 3600.0) else: raise NotImplementedError if (yaxis == Y_REWARD): y = ts.r.values...
def test_statcast_pitchers_expected_stats() -> None: min_pa = 100 result: pd.DataFrame = statcast_pitcher_expected_stats(2019, min_pa) assert (result is not None) assert (not result.empty) assert (len(result.columns) == 18) assert (len(result) > 0) assert (len(result[(result['pa'] < min_pa)]...
def setup_orderdict(): from collections import OrderedDict yaml.add_representer(OrderedDict, represent_dictionary_order)
_model_architecture('dual_input_wav_transformer', 'dualinputs2twavtransformer_base') def dualinputs2twavtransformer_base(args): args.dropout_input = getattr(args, 'dropout_input', 0) args.dropout_features = getattr(args, 'dropout_features', 0) args.speech_mask_length = getattr(args, 'speech_mask_length', 10...
def plot_roc_curve(human_scores, gpt_scores): A = human_scores B = gpt_scores scores = (A + B) labels = (([0] * len(A)) + ([1] * len(B))) (fpr, tpr, thresholds) = roc_curve(labels, scores) roc_auc = auc(fpr, tpr) plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=('ROC curve...
def make_mmcif_features(mmcif_object: mmcif_parsing.MmcifObject, chain_id: str) -> FeatureDict: input_sequence = mmcif_object.chain_to_seqres[chain_id] description = '_'.join([mmcif_object.file_id, chain_id]) num_res = len(input_sequence) mmcif_feats = {} mmcif_feats.update(make_sequence_features(se...
def incorrect_edges_per_graph(true_adj, pred_adj, n_node, abs_tol=0.5): diff = remove_diag(tf.math.abs((true_adj - pred_adj))) num_incorrect = tf.where(tf.greater(diff, abs_tol), tf.ones_like(diff), tf.zeros_like(diff)) num_incorrect = tf.reduce_sum(num_incorrect, axis=0) indices = repeat_1d(tf.range(tf...
def get_caseIDs_from_splitted_dataset_folder(folder): files = subfiles(folder, suffix='.nii.gz', join=False) files = [i[:(- 12)] for i in files] files = np.unique(files) return files
def velocity_of_P_given_A(vel: T2value, omega: float, vec_ap: T2value) -> T2value: return (vel + (omega * (_rot90 vec_ap)))
class Wide_ResNet(nn.Module): def __init__(self, depth, widen_factor, dropout_rate, num_classes): super(Wide_ResNet, self).__init__() self.in_planes = 16 assert (((depth - 4) % 6) == 0), 'Wide-resnet depth should be 6n+4' n = ((depth - 4) / 6) k = widen_factor nStages...
def _make_scratch_ccm(scratch, in_channels, cout, expand=False): out_channels = ([cout, (cout * 2), (cout * 4), (cout * 8)] if expand else ([cout] * 4)) scratch.layer0_ccm = nn.Conv2d(in_channels[0], out_channels[0], kernel_size=1, stride=1, padding=0, bias=True) scratch.layer1_ccm = nn.Conv2d(in_channels[1...
def test(testloader, model, criterion, epoch, use_cuda, optimizer=None): global best_acc batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() live_top1 = AverageMeter() live_top5 = AverageMeter() dead_top1 = Averag...
def difficulty_judgement_ratings(df): ev1_difficulty = df['Question Difficulty_EV_1'].dropna().apply(map_difficulty) ev2_difficulty = df['Question Difficulty_EV_2'].dropna().apply(map_difficulty) ev_difficulty = (ev1_difficulty + ev2_difficulty) print(f'EV1 Difficulty: {ev1_difficulty.mean()} / 4') ...
class PD_Stats(object): def __init__(self, path, columns): self.path = path if os.path.isfile(self.path): self.stats = pd.read_pickle(self.path) assert (list(self.stats.columns) == list(columns)) else: self.stats = pd.DataFrame(columns=columns) def upd...
class EncDecBaseConfig(FairseqDataclass): embed_path: Optional[str] = field(default=None, metadata={'help': 'path to pre-trained embedding'}) embed_dim: Optional[int] = field(default=512, metadata={'help': 'embedding dimension'}) ffn_embed_dim: int = field(default=2048, metadata={'help': 'embedding dimensio...
.parametrize('device', list_devices()) def test_tensormap_modify(device): tm = o3d.t.geometry.TensorMap('positions') tm.a = o3c.Tensor([100], device=device) a_alias = tm.a a_alias[:] = o3c.Tensor([200], device=device) np.testing.assert_equal(a_alias.cpu().numpy(), [200]) np.testing.assert_equal(...
def accuracy(dataset, model): total = 0 for feat in dataset: feature = feat[0] feature = torch.tensor(feature, dtype=torch.float) y_pred = model(feature) y_true = feat[1] loss = custom_loss(y_pred, y_true, model.name) total += loss return (total / len(dataset)...
class QNet(BaseModule): def __init__(self, n_units, n_classes): super(QNet, self).__init__() self.model = nn.Sequential(nn.Linear((2 * n_classes), n_units), nn.ReLU(True), nn.Linear(n_units, n_classes)) def forward(self, zcat): zzt = self.model(zcat) return zzt
def _valid_accuracy_field(key, scope, error): assert (bool(('relative' in scope['accuracy_criterion'])) != bool(('absolute' in scope['accuracy_criterion'])))
.skipif((not hasattr(m, 'has_exp_optional')), reason='no <experimental/optional>') def test_exp_optional(): assert (m.double_or_zero_exp(None) == 0) assert (m.double_or_zero_exp(42) == 84) pytest.raises(TypeError, m.double_or_zero_exp, 'foo') assert (m.half_or_none_exp(0) is None) assert (m.half_or_...
def get_gcc_version(run_lambda): return run_and_parse_first_match(run_lambda, 'gcc --version', 'gcc (.*)')
class BalancedDataParallel(DataParallel): def __init__(self, gpu0_bsz, *args, **kwargs): self.gpu0_bsz = gpu0_bsz super().__init__(*args, **kwargs) def forward(self, *inputs, **kwargs): if (not self.device_ids): return self.module(*inputs, **kwargs) if (self.gpu0_bsz ...
def TreeGeneration(ArgSet, depth: int, equiv: bool, rarity: bool): for LArgSet in range(0, (ArgSet + 1)): if ((ArgSet & LArgSet) == LArgSet): RArgSet = (LArgSet ^ ArgSet) for ldepth in range(0, depth): rdepth = ((depth - 1) - ldepth) for Ltree in TreeD...
class Dataset(data.Dataset): def __init__(self, root, load_bytes=False, transform=None, class_map=''): class_to_idx = None if class_map: class_to_idx = load_class_map(class_map, root) (images, class_to_idx) = find_images_and_targets(root, class_to_idx=class_to_idx) if (le...
def t_integ_attr_(b): res = np.zeros(b.shape) for i in range(b.shape[1]): res[0][i] = integrate.quad(t_attr, 0, b[0][i], points=[0])[0] return res