code
stringlengths
101
5.91M
class DistanceMetric(object): def __init__(self, algorithm='euclidean', *args, **kwargs): super(DistanceMetric, self).__init__() self.algorithm = algorithm self.metric = get_metric(algorithm, *args, **kwargs) def train(self, model, data_loader): if (self.algorithm == 'euclidean')...
def sql_functions_d_example(spark): df = spark.createDataFrame([('2015-04-08',)], ['dt']) df.select(date_add(df.dt, 1).alias('next_day')).show() print('date_add API finished') df = spark.createDataFrame([('2015-04-08',)], ['dt']) df.select(date_format('dt', 'MM/dd/yyy').alias('date')).show() pri...
class MLPBoston(): base = MLPBase base.log_noise = nn.Parameter(torch.log((torch.ones(1) * 7))) args = list() kwargs = {'in_dim': 13, 'layers': 1, 'hidden': 50} transform_train = transforms.ToTensor() transform_test = transforms.ToTensor()
class NCEDataTest(TestCase): def setUp(self): self.dataset = load_dataset('example.csv') def test_num_examples_for_different_batch_sizes(self): len_1 = self._num_examples_with_batch_size(1) for batch_size in range(2, 100): len_x = self._num_examples_with_batch_size(batch_size...
def _get_module_flops(module): s = module.__flops__ for child in module.children(): s += _get_module_flops(child) return s
class State(): problem: Array position: jnp.int32 capacity: jnp.float32 visited_mask: Array order: Array num_total_visits: jnp.int32
def get_argument(): parser = argparse.ArgumentParser() parser.add_argument('--quantize', action='store_true') parser.add_argument('--equalize', action='store_true') parser.add_argument('--distill_range', action='store_true') parser.add_argument('--correction', action='store_true') parser.add_arg...
class HeadSelectionTransformerDecoder(TransformerDecoder): def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, output_projection=None): self.num_tasks = args.decoder_tasks self.num_layers = args.decoder_layers self.total_num_heads = args.total_decoder_attention_heads ...
def input_fn(is_training, data_dir, batch_size, num_epochs=1): dataset = record_dataset(get_filenames(is_training, data_dir)) if is_training: dataset = dataset.shuffle(buffer_size=NUM_IMAGES['train']) dataset = dataset.map(parse_record) dataset = dataset.map((lambda image, label: (preprocess_ima...
class JaccardLoss(nn.Module): def __init__(self): super().__init__() def forward(self, pred, target): pred = pred.squeeze(dim=1) smooth = 1 dice = ((pred * target).sum(dim=1).sum(dim=1).sum(dim=1) / (((pred.pow(2).sum(dim=1).sum(dim=1).sum(dim=1) + target.pow(2).sum(dim=1).sum(di...
def _make_pretrained_swin2t16_256(pretrained, hooks=None): model = timm.create_model('swinv2_tiny_window16_256', pretrained=pretrained) hooks = ([1, 1, 5, 1] if (hooks == None) else hooks) return _make_swin_backbone(model, hooks=hooks, patch_grid=[64, 64])
class GradedSpikes(torch.nn.Module): def __init__(self, size, constant_factor): super().__init__() self.size = size if constant_factor: weights = (torch.ones(size=[size, 1]) * constant_factor) self.weights = torch.nn.Parameter(weights) else: weight...
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): if (len(gpu_ids) > 0): assert torch.cuda.is_available() net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) init_weights(net, init_type, init_gain=init_gain) return net
(version='2.3.0', reason='Please use spark engine and ray engine.') class TorchModel(Layer): def __init__(self, jvalue, module_bytes, bigdl_type='float'): self.value = jvalue self.module_bytes = module_bytes self.bigdl_type = bigdl_type def from_value(model_value): model_bytes = ...
def get_end_to_end_prefix_allowed_tokens_fn_hf(model, sentences: List[str], start_mention_token='{', end_mention_token='}', start_entity_token='[', end_entity_token=']', mention_trie: Trie=None, candidates_trie: Trie=None, mention_to_candidates_dict: Dict[(str, List[str])]=None): return _get_end_to_end_prefix_allow...
_tokenizers class GPTNeoXJapaneseTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = GPTNeoXJapaneseTokenizer test_rust_tokenizer = False from_pretrained_kwargs = {'do_clean_text': False, 'add_prefix_space': False} def setUp(self): super().setUp() vocab_tokens = ...
def crossentropy_with_threshold(labels, logits, weights, threshold): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) entropies = ((- tf.reduce_sum((probabilities * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) costs = ((- tf.reduce_sum((labels * logits), a...
class StanleyController(object): def __init__(self, control_params: StanleyParams=StanleyParams(), vehicle_body: VehicleBody=VehicleBody(), vehicle_config: VehicleConfig=VehicleConfig()): super().__init__() self.k = control_params.k self.Kp = control_params.Kp self.Kp_braking = contr...
class k8sClient(object): _instance_lock = threading.Lock() def __init__(self, namespace): try: if os.getenv('KUBERNETES_SERVICE_HOST'): config.load_incluster_config() logger.info('Load the incluster config.') else: config.load_kube_...
def is_alphabet(uchar): if (((uchar >= u'A') and (uchar <= u'Z')) or ((uchar >= u'a') and (uchar <= u'z'))): return True else: return False
def render_pep440_pre(pieces): if pieces['closest-tag']: if pieces['distance']: (tag_version, post_version) = pep440_split_post(pieces['closest-tag']) rendered = tag_version if (post_version is not None): rendered += ('.post%d.dev%d' % ((post_version + 1),...
def read(in_files, l_files, input_file): if os.path.isdir(input_file): for file in os.listdir(input_file): (in_files, l_files) = read(in_files, l_files, ((input_file + '/') + file)) elif input_file.endswith('.text'): in_files.append(input_file) l_files.append(input_file.repla...
def mobilenetv3_small_minimal_100(pretrained=False, **kwargs): model = _gen_mobilenet_v3('mobilenetv3_small_minimal_100', 1.0, pretrained=pretrained, **kwargs) return model
class BatchResolver(Resolver): def __init__(self, enable_tracking: bool=False, round_limit: Optional[int]=None, shuffle_batches: bool=False) -> None: super().__init__(enable_tracking) self.round_limit = round_limit self.shuffle_batches = shuffle_batches self.messages: DefaultDict[(Ag...
def instanciate_transformation(cmd_line): if (not isinstance(cmd_line, str)): return cmd_line cmd_line = ('tvf.Compose([%s])' % cmd_line) try: return eval(cmd_line) except Exception as e: print(('Cannot interpret this transform list: %s\nReason: %s' % (cmd_line, e)))
class Blip2ForConditionalGeneration(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_lr_and_max_steps(examples_per_epoch, batch_size, num_gpus, lr_decay_factor, epochs_per_decay, initial_lr, global_step, staircase, max_epochs): num_batches_per_epoch = ((examples_per_epoch / batch_size) / num_gpus) if isinstance(lr_decay_factor, float): decay_steps = int((num_batches_per_epoch * ...
def discriminator_gradient_penalty(d_result_real, reals, r1_gamma=10.0): real_loss = d_result_real.sum() real_grads = torch.autograd.grad(real_loss, reals, create_graph=True, retain_graph=True)[0] r1_penalty = torch.sum(real_grads.pow(2.0), dim=[1, 2, 3]) loss = (r1_penalty * (r1_gamma * 0.5)) retur...
class LlavaMetaModel(): def __init__(self, config): super(LlavaMetaModel, self).__init__(config) if hasattr(config, 'mm_vision_tower'): self.vision_tower = build_vision_tower(config, delay_load=True) self.mm_projector = build_vision_projector(config) def get_vision_tower(...
class NormalizedDegree(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, data): deg = degree(data.edge_index[0], dtype=torch.float) deg = ((deg - self.mean) / self.std) data.x = deg.view((- 1), 1) return data
def save_segmask_as_nifi_volume(seg_mask: np.ndarray, aff_func, path: str): img = nib.Nifti1Image(seg_mask, aff_func) img.to_filename(path)
def fft2c(x): axes = ((- 2), (- 1)) res = fftshift(fft2(ifftshift(x, axes=axes), norm='ortho'), axes=axes) return res
def calculate_number_of_labels_distribution(data_dir, filtered_by=None): answers = get_all_answers(data_dir, filtered_by=filtered_by).values() lengths = [len(ans_set) for ans_set in answers] return Counter(lengths).items()
def tgasPath(dr=1, old=False): if old: return [os.path.join(_GAIA_TOOLS_DATA, 'Gaia', 'tgas_source', 'fits', ('TgasSource_000-000-%03i.fits' % ii)) for ii in range(16)] else: return [os.path.join(_GAIA_TOOLS_DATA, 'Gaia', 'gdr1', 'tgas_source', 'fits', ('TgasSource_000-000-%03i.fits' % ii)) for ...
def parse_url(url): tokens = url.split('/') folder = tokens[4] tokens = tokens[5].split('?') tokens.reverse() file = '.'.join(tokens) return ((('/dccstor/extrastore/Neural-Naturalist/data/resized_images/' + folder) + '.') + file)
def test_modelcheckpoint_mode_options(): fpath = 'tests/test_model_functioning/modelcheckpoint/weights_out' model_checkpoint_1 = ModelCheckpoint(filepath=fpath, monitor='val_loss', mode='min') model_checkpoint_2 = ModelCheckpoint(filepath=fpath, monitor='val_loss') model_checkpoint_3 = ModelCheckpoint(f...
class CosineWarmupLR(lr_sched._LRScheduler): def __init__(self, optimizer, T_max, eta_min=0, last_epoch=(- 1)): self.T_max = T_max self.eta_min = eta_min super(CosineWarmupLR, self).__init__(optimizer, last_epoch) def get_lr(self): return [(self.eta_min + (((base_lr - self.eta_mi...
class A2CPipeline(BasicPipeline): def __init__(self, name, net, abstractor, train_batcher, val_batcher, optim, grad_fn, reward_fn, gamma, stop_reward_fn, stop_coeff): self.name = name self._net = net self._train_batcher = train_batcher self._val_batcher = val_batcher self._op...
def build_pnasnet_mobile(images, num_classes, is_training=True, final_endpoint=None, config=None): hparams = (copy.deepcopy(config) if config else mobile_imagenet_config()) nasnet._update_hparams(hparams, is_training) if (tf.test.is_gpu_available() and (hparams.data_format == 'NHWC')): tf.logging.in...
class TestEqualize(unittest.TestCase): def setUp(self): self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', 'gt_ignore_flags', 'gt_seg_map') self.results_mask = construct_toy_data(poly2mask=True) def test_equalize(self): transform = Equalize(prob=0.0) results_w...
def input_handler(data, context): data_str = data.read().decode('utf-8') jsonlines = data_str.split('\n') session = json.loads(jsonlines[0])['instances'] return json.dumps({'instances': [session[(- 1)]]})
def find_lemmata(tokens): for token in tokens: (word, pos, lemma) = (token[0], token[1], token[0]) if pos.startswith(('DT',)): lemma = singularize(word, pos='DT') if pos.startswith('JJ'): lemma = predicative(word) if (pos == 'NNS'): lemma = singula...
def communicate_gather(tensors, rank, gsize, communication_op, group, dst=0, attention=False): flat_tensor = flatten_tensors(tensors) if (rank == 0): gather_list = [flat_tensor.clone() for _ in range(gsize)] else: gather_list = [] communication_op(tensor=flat_tensor, gather_list=gather_l...
_model def hrnet_w44(pretrained=True, **kwargs): return _create_hrnet('hrnet_w44', pretrained, **kwargs)
def test_Combined15(): (l, b, d) = (10.0, 1.0, 2.0) combined_ebv = mwdust.Combined15(filter='E(B-V)') ebv = combined_ebv(l, b, d) del combined_ebv combined_b = mwdust.Combined15(filter='Landolt B') ab = combined_b(l, b, d) del combined_b combined_v = mwdust.Combined15(filter='Landolt V')...
def build_features_t5(examples, data_type, out_file, tokenizer, max_input_length, max_output_length): print('Processing {} examples...'.format(data_type)) total = 0 (input_inputs, output_inputs, turn_inputs, ids) = ([], [], [], []) for example in tqdm(examples): total += 1 input_input = ...
def get_setup_file(): parser = argparse.ArgumentParser() parser.add_argument('-f') args = parser.parse_args() return args.f
def test(model, data_loader): model.eval() loss = 0 acc = 0 with torch.no_grad(): for (iter, (batch_graphs, batch_targets, batch_snorm_n, batch_snorm_e)) in enumerate(data_loader): batch_x = batch_graphs.ndata['feat'].cuda() batch_e = batch_graphs.edata['feat'].cuda() ...
class ASPP(nn.Module): def __init__(self, C, depth, num_classes, conv=nn.Conv2d, norm=nn.BatchNorm2d, momentum=0.0003, mult=1, phase='train'): super(ASPP, self).__init__() self._C = C self._depth = depth self._num_classes = num_classes self.phase = phase self.global_p...
def _elementwise_flops_compute(input, other): if (not torch.is_tensor(input)): if torch.is_tensor(other): return (_prod(other.shape), 0) else: return (1, 0) elif (not torch.is_tensor(other)): return (_prod(input.shape), 0) else: dim_input = len(input.s...
class _MultiPageVIPSReader(_VIPSReader): def _load_levels(self, vips_image: Optional['vips.Image']): log.debug('Attempting to read levels from non-standard multi-page TIFF') self.level_count = int(self.properties['n-pages']) self.levels = [] for lev in range(self.level_count): ...
def tfidf(name, analyzer=None, ngram_range=None, stop_words=None, lowercase=None, max_df=1.0, min_df=1, max_features=None, binary=None, norm=None, use_idf=False, smooth_idf=False, sublinear_tf=False): def _name(msg): return ('%s.%s_%s' % (name, 'tfidf', msg)) max_ngram = scope.int(hp.quniform(_name('max...
def np_to_creator(data): def data_creator(config, batch_size): return DataLoader(TensorDataset(torch.from_numpy(data[0]).float(), torch.from_numpy(data[1]).float()), batch_size=batch_size, shuffle=True) return data_creator
class FocalLoss(tf.keras.losses.Loss): def __init__(self, gamma=2.0, alpha=4.0, reduction=tf.keras.losses.Reduction.AUTO, name='focal_loss'): super(FocalLoss, self).__init__(reduction=reduction, name=name) self.gamma = float(gamma) self.alpha = float(alpha) def call(self, y_true, y_pred)...
class SingleImageWrapper(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) template = env.observation_space[0].spaces[0] shape = ((6,) + template.shape[1:]) self.observation_space = gym.spaces.Box(template.low.min(), template.high.max(), shape, template.dtype) ...
class SentencePredictionConfig(FairseqDataclass): classification_head_name: str = field(default='sentence_classification_head', metadata={'help': 'name of the classification head to use'}) regression_target: bool = field(default=False) report_mcc: bool = False report_acc_and_f1: bool = False report_...
def check_bool(value, original_var_name): if (not isinstance(value, bool)): raise ValueError(f"'{original_var_name}' must be a boolean, got '{type(value)}'.")
def resnet110(pretrained: bool=False, progress: bool=True, num_classes: int=10, layer_config: dict=None) -> ResNet: print('Converting ResNet-110 to {} mode'.format(MODE_STRING)) return create_torchvision_biomodel(small_resnet.resnet110, MODE, layer_config, pretrained, progress, num_classes)
class Minitaur(object): def __init__(self, pybullet_client, urdf_root=os.path.join(os.path.dirname(__file__), '../data'), time_step=0.01, self_collision_enabled=False, motor_velocity_limit=np.inf, pd_control_enabled=False, accurate_motor_model_enabled=False, motor_kp=1.0, motor_kd=0.02, torque_control_enabled=False...
class common_solver(solver.solver): def __init__(self, models, optimizers, kernel_processer, model_name, save_path='checkpoints'): super(common_solver, self).__init__(models, optimizers, kernel_processer, model_name, save_path) def test_model(self, param_dict, mode='test'): loader_choice = {'tes...
def _convert_dataset(split_name, filenames, class_names_to_ids, dataset_dir): assert (split_name in ['train', 'validation']) num_per_shard = int(math.ceil((len(filenames) / float(_NUM_SHARDS)))) with tf.Graph().as_default(): image_reader = ImageReader() with tf.Session('') as sess: ...
def propagate_through_subgraph(node, new_sharding_spec, sharding_specs, contracted_graph, nx_graph): agg_nodes = contracted_graph.nodes[node]['aggregated_nodes'] prop_spec = dict(((k, sharding_specs[k]) for k in sharding_specs.keys() if ((k in agg_nodes) and (k != node)))) if (new_sharding_spec == sharding_...
def test_get_kbs_invalidates_cache_if_input_changes(): journals = {'Journal of Testing': 'J.Testing'} first_cache = get_kbs(custom_kbs={'journals': journals}).copy() journals = journals = {'Journal of Testing': 'J.Test.'} second_cache = get_kbs(custom_kbs={'journals': journals}) assert all(((cached_...
def gen_mask(corr_dict): mask_AB = torch.max(corr_dict['corr_AB'], dim=1, keepdim=True)[0] mask_BA = torch.max(corr_dict['corr_BA'], dim=1, keepdim=True)[0] mask_dict = {'mask_AB': mask_AB, 'mask_BA': mask_BA} return mask_dict
class FMClassifier(sklearn.base.BaseEstimator): def __init__(self, embedding_size=20, nb_iterations=40): super().__init__() self.embedding_size = embedding_size self.nb_iterations = nb_iterations def fit(self, X, y): fm = pywFM.FM(task='classification', num_iter=self.nb_iteration...
def get_data(data_name): if (data_name == 'bmnist'): from fuel.datasets.binarized_mnist import BinarizedMNIST x_dim = (28 * 28) data_train = BinarizedMNIST(which_sets=['train'], sources=['features']) data_valid = BinarizedMNIST(which_sets=['valid'], sources=['features']) data...
def gptneox_set_state_data(ctx: gptneox_context_p, src) -> int: return _lib.gptneox_set_state_data(ctx, src)
def param_name_dict(): layer = caffe_pb2.LayerParameter() param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')] param_type_names = [type(getattr(layer, s)).__name__ for s in param_names] param_names = [s[:(- len('_param'))] for s in param_names] param_type_names = [s[:...
class TabPerceiver(BaseTabularModelWithAttention): def __init__(self, column_idx: Dict[(str, int)], cat_embed_input: Optional[List[Tuple[(str, int)]]]=None, cat_embed_dropout: float=0.1, use_cat_bias: bool=False, cat_embed_activation: Optional[str]=None, full_embed_dropout: bool=False, shared_embed: bool=False, add...
class EuroRadCase(Case): def _in(self, metadata): return (self.url in list(metadata['url'])) def to_standard(self, eurorad_record): standard_patient = {'sex': eurorad_record['sex'], 'age': eurorad_record['age'], 'clinical_history': eurorad_record.get('CLINICAL HISTORY'), 'finding': eurorad_recor...
class RealmTokenizerFast(metaclass=DummyObject): _backends = ['tokenizers'] def __init__(self, *args, **kwargs): requires_backends(self, ['tokenizers'])
def get_query_based_summarization_set(dataset: SummDataset, size=1) -> Tuple[(List, List, List)]: subset = [] for i in range(size): subset.append(next(dataset.train_set)) (src, tgt, queries) = zip(*list(map((lambda x: (x.source, x.summary, x.query)), subset))) return (list(src), list(tgt), list(...
class TFRobertaMainLayer(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class KNeighborsAlgorithm(KNNFit): algorithm_name = 'k-Nearest Neighbors' algorithm_short_name = 'Nearest Neighbors' def __init__(self, params): super(KNeighborsAlgorithm, self).__init__(params) logger.debug('KNeighborsAlgorithm.__init__') self.library_version = sklearn.__version__ ...
class TacotronSTFT(torch.nn.Module): def __init__(self, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0, mel_fmax=8000.0): super(TacotronSTFT, self).__init__() self.n_mel_channels = n_mel_channels self.sampling_rate = sampling_rate ...
def compose_transformations(*args: Callable[([GraphModule], Optional[GraphModule])], inplace: bool=False) -> GraphModule: args = list(args) if (not inplace): args.insert(0, deepcopy_graph) for (i, transformation) in enumerate(args[:(- 1)]): sig = signature(transformation) if getattr(...
class Mul(ZooKerasLayer): def __init__(self, input_shape=None, **kwargs): super(Mul, self).__init__(None, (list(input_shape) if input_shape else None), **kwargs)
class TestTrain(unittest.TestCase): def setUp(self): self.p = pctsp.Pctsp() self.p.prize = np.array([0, 4, 8, 3]) self.p.penal = np.array([1000, 7, 11, 17]) self.p.cost = np.array([[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]]) def test_quality(self): s = soluti...
class Data(): def __init__(self, train, valid): self.train = train self.valid = valid
class ResNet(nn.Module): def __init__(self, block, num_blocks, class_num=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 6...
class AccLossProbe(StatsProbe): def __init__(self, **kwargs): super(AccLossProbe, self).__init__() self.type = kwargs['type'] assert ((self.type == 'train') or (self.type == 'test')) self.last_epoch_stats = {} def get_last_epoch_stats(self): return self.last_epoch_stats ...
_cache(1) def get_kahypar_profile_dir(): import kahypar import re m = re.compile('(\\d+)\\.(\\d+)\\.(\\d+)').match(kahypar.__version__) path_components = [abspath(dirname(__file__)), 'kahypar_profiles'] if (m is not None): version = tuple(map(int, m.groups())) if (version <= (1, 1, 6...
def get_latent_vectors(model, set, device, params): if DEBUG: embeddings = np.random.rand(len(set), 256) return embeddings model.eval() embeddings_l = [] for elem_ndx in set: x = load_data_item(set[elem_ndx]['query'], params) with torch.no_grad(): batch = {} ...
def initialize_lr_scheduler(train_config, optimizer): learning_rate = train_config['learning_rate'] warmup_epochs = train_config['warmup_epochs'] scheduler_strategy = train_config['lr_scheduler'] scheduler_config = train_config['scheduler_config'] lr_scheduler = None if (scheduler_strategy in sc...
_GENERATOR_REGISTRY.register() class RPN(nn.Module): def __init__(self, *, in_features: List[str], head: nn.Module, anchor_generator: nn.Module, anchor_matcher: Matcher, box2box_transform: Box2BoxTransform, batch_size_per_image: int, positive_fraction: float, pre_nms_topk: Tuple[(float, float)], post_nms_topk: Tupl...
class A2CTrainer(SingleTrainer, A2CModel): def __init__(self, name, env_kwargs, model_kwargs, max_time_steps, **kwargs): super().__init__(max_time_steps=max_time_steps, env_kwargs=env_kwargs, model_kwargs=model_kwargs) self.max_time_steps = max_time_steps self.name = name self.num_st...
def MusicTaggerCRNN(weights='msd', input_tensor=None, include_top=True): if (weights not in {'msd', None}): raise ValueError('The `weights` argument should be either `None` (random initialization) or `msd` (pre-training on Million Song Dataset).') if (K.image_dim_ordering() == 'th'): input_shape...
def get_hash(in_str): hash_object = hashlib.sha512(in_str.encode('utf-8')) return str(hash_object.hexdigest())
def test_double_double_system(vrblvl=0): polynomials = ['x^3 + 2*x*y - 1;', 'x + y - 1/3;', 'x - 1;'] dim = number_of_symbols(polynomials, vrblvl) print('number of symbols :', dim) if (dim == len(polynomials)): print('The system is square.') else: print('number of polynomials :', len...
def parse_args(): parser = argparse.ArgumentParser(description='Video Classification') parser.add_argument('--mode', type=str, default='test', help='train/test') parser.add_argument('--model', type=str, default='r21d', help='c3d/r3d/r21d') parser.add_argument('--dataset', type=str, default='K400', help=...
def cplx_batch_norm(input, running_mean, running_var, weight=None, bias=None, training=True, momentum=0.1, eps=1e-05): assert (((running_mean is None) and (running_var is None)) or ((running_mean is not None) and (running_var is not None))) assert (((weight is None) and (bias is None)) or ((weight is not None) ...
class OrnsteinUhlenbeckActionNoise(ActionNoise): def __init__(self, mu, sigma, theta=0.15, dt=0.01, x0=None): self.theta = theta self.mu = mu self.sigma = sigma self.dt = dt self.x0 = x0 self.reset() def __call__(self): x = ((self.x_prev + ((self.theta * (...
class ByClassDataset(Dataset): def __init__(self, ds): self.dataset = ds self.idx_by_class = {} for (idx, (_, c)) in enumerate(ds): self.idx_by_class.setdefault(c, []) self.idx_by_class[c].append(idx) def __len__(self): return min([len(d) for d in self.idx...
def run(): drop_table() create_table() info_path = Task.parse(project_dir) parse_data(info_path) clear_dataset() export_data() project_name = os.path.basename(os.path.normpath(project_dir)) sql_query = "\n SELECT id FROM method WHERE project_name='{}';\n ".format(project_name) ...
class DefaultInitFun(): _target_: str = 'dynamics.init_coordinates.DefaultInitFun' h_dims: Tuple[int] = field(default_factory=(lambda : (II('dataset.N_CLASSES'),))) param_map: Optional[Any] = MISSING
class Boxban_Env0(BoxobanEnv): metadata = {'render.modes': ['human', 'rgb_array', 'tiny_human', 'tiny_rgb_array']} def __init__(self): super(Boxban_Env0, self).__init__(max_steps=200, difficulty='unfiltered', split='train')
def encode_huffman_tree(root, dtype): converter = {'float32': float2bitstr, 'int32': int2bitstr} code_list = [] def encode_node(node): if (node.value is not None): code_list.append('1') lst = list(converter[dtype](node.value)) code_list.append(lst) else: ...
class VitHgface(torch.nn.Module): transform = transforms.Lambda(vit_transform) name = 'ViT_hgface' def __init__(self): super().__init__() self.vit = ViTModel.from_pretrained(VIT_MODEL) def forward(self, x): x = x.view((- 1), 3, 224, 224) with torch.no_grad(): ...
def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distributed: if ((args.dist_url == 'env://') and (args.rank == (- 1))): args.rank = int(os.environ['RANK']) ...
_module() class CityscapesDataset(CocoDataset): CLASSES = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') PALETTE = [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)] def _filter_imgs(self, min_size=32): valid_in...