code
stringlengths
101
5.91M
def _create_losses(input_queue, create_model_fn): detection_model = create_model_fn() (images, groundtruth_boxes_list, groundtruth_classes_list, groundtruth_masks_list) = _get_inputs(input_queue, detection_model.num_classes) images = [detection_model.preprocess(image) for image in images] images = tf.co...
def var(xNp, volatile=False, cuda=False): x = Variable(t.from_numpy(xNp), volatile=volatile) if cuda: x = x.cuda() return x
class TarDataset(data.Dataset): def download_or_unzip(cls, root): path = os.path.join(root, cls.dirname) if (not os.path.isdir(path)): tpath = os.path.join(root, cls.filename) os.makedirs(root, exist_ok=True) if (not os.path.isfile(tpath)): print('...
def prod(iterable): if (len(list(iterable)) > 0): return reduce(operator.mul, iterable) else: return 1
class AvgPool2dSame(nn.AvgPool2d): def __init__(self, kernel_size: int, stride=None, padding=0, ceil_mode=False, count_include_pad=True): kernel_size = tup_pair(kernel_size) stride = tup_pair(stride) super(AvgPool2dSame, self).__init__(kernel_size, stride, (0, 0), ceil_mode, count_include_pa...
class SkipConnectRNNCell(VarRNNCellBase): def __init__(self, input_size, hidden_size, bias=True, nonlinearity='tanh', p=(0.5, 0.5)): super(SkipConnectRNNCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.nonlinearity = non...
class r2plus1d_18(nn.Module): def __init__(self, pretrained=True, num_classes=500, dropout_p=0.5): super(r2plus1d_18, self).__init__() self.pretrained = pretrained self.num_classes = num_classes model = torchvision.models.video.r2plus1d_18(pretrained=self.pretrained) modules ...
def mandelbrot(render_size, center, zoom, cycles): f = (zoom / render_size[0]) real_start = (center[0] - ((render_size[0] / 2) * f)) real_end = (real_start + (render_size[0] * f)) imag_start = (center[1] - ((render_size[1] / 2) * f)) imag_end = (imag_start + (render_size[1] * f)) real_range = tf...
def dump_result(args, sample_id, feat_pred): out_root = Path(args.results_path) feat_dir = (out_root / 'feat') feat_dir.mkdir(exist_ok=True, parents=True) np.save((feat_dir / f'{sample_id}.npy'), feat_pred.transpose(1, 0))
def test_eval_hmean(): metrics = set(['hmean-iou', 'hmean-ic13']) results = [{'boundary_result': [[50, 70, 80, 70, 80, 100, 50, 100, 1], [120, 140, 200, 140, 200, 200, 120, 200, 1]]}] img_infos = [{'file_name': 'sample1.jpg'}] ann_infos = _create_dummy_ann_infos() with pytest.raises(AssertionError):...
def node_name_from_input(node_name): if node_name.startswith('^'): node_name = node_name[1:] m = re.search('(.*):\\d+$', node_name) if m: node_name = m.group(1) return node_name
class UVTrianglesRenderer(): def __init__(self, ctx: MGL.Context, output_size: Tuple[(int, int)]): self.ctx = ctx self.output_size = output_size self.shader = self.ctx.program(vertex_shader=VERTEX_SHADER, fragment_shader=FRAGMENT_SHADER) self.fbo = self.ctx.framebuffer(self.ctx.rende...
class FMASmall(Dataset): _ext_audio = '.mp3' def __init__(self, root: Union[(str, Path)], audio_transform: Callable=None, subset: Optional[str]='training') -> None: super().__init__() self.subset = subset self.random_crop = (self.subset != 'testing') assert ((subset is None) or (...
class PixelNormLayer(nn.Module): def __init__(self): super(PixelNormLayer, self).__init__() def forward(self, x): return (x * torch.rsqrt((torch.mean((x ** 2), dim=1, keepdim=True) + 1e-08))) def __repr__(self): return self.__class__.__name__
def train(loader_src, loader_tgt, net, opt_net, opt_dis, epoch): log_interval = 100 N = min(len(loader_src.dataset), len(loader_tgt.dataset)) joint_loader = zip(loader_src, loader_tgt) net.train() last_update = (- 1) for (batch_idx, ((data_s, _), (data_t, _))) in enumerate(joint_loader): ...
class TextModelTrainer(object): def __init__(self, hparams, name=''): self.hparams = hparams print(hparams) self.name = name random.seed(0) (self.train_loader, self.valid_loader, self.test_loader, self.classes, self.vocab) = get_text_dataloaders(hparams['dataset_name'], valid...
class TestOffPolicyVectorizedSampler(TfGraphTestCase): .mujoco def test_no_reset(self): with LocalTFRunner(snapshot_config, sess=self.sess) as runner: env = GarageEnv(normalize(gym.make('InvertedDoublePendulum-v2'))) policy = ContinuousMLPPolicy(env_spec=env.spec, hidden_sizes=[6...
class PrioritizedReplayBuffer(): def __init__(self, max_length, task_ids, p1=0.8): self.task_ids = task_ids self.memory_task = dict(((task_id, {0: [], 1: []}) for task_id in self.task_ids)) self.stack = [] self.max_length = max_length self.p1 = p1 def get_memory_length(se...
class CriterionAdvForG(nn.Module): def __init__(self, adv_type): super(CriterionAdvForG, self).__init__() if ((adv_type != 'wgan-gp') and (adv_type != 'hinge')): raise ValueError('adv_type should be wgan-gp or hinge') self.adv_loss = adv_type def forward(self, d_out_S): ...
def aggregate(X, G, F, Y=None): device = X.device if (Y is None): Y = torch.zeros((F.shape + (X.shape[(- 1)],)), device=device, dtype=X.dtype) else: Y.zero_() if (device.type == 'cpu'): aggregate_cpu(X, G, F, Y) else: aggregate_gpu(X, G, F, Y) return Y
def json_dump(obj): import json return json.dumps(obj, sort_keys=True, separators=(',', ':'))
class TestPytorchWeightOnlyAdaptor(unittest.TestCase): approach = 'weight_only' def setUpClass(self): self.dataloader = SimpleDataLoader() self.gptj = transformers.AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-GPTJForCausalLM', torchscript=True) self.gptj_no_jit =...
class SIDER(MoleculeCSVDataset): def __init__(self, smiles_to_graph=smiles_2_dgl, load=False, log_every=1000, cache_file_path='./sider_dglgraph.bin', n_jobs=1): self._url = 'dataset/sider.zip' data_path = (get_download_dir() + '/sider.zip') dir_path = (get_download_dir() + '/sider') ...
class LastLevelP6(nn.Module): def __init__(self, in_channels, out_channels, in_features='res5'): super().__init__() self.num_levels = 1 self.in_feature = in_features self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) for module in [self.p6]: weight_init.c2_xa...
class GetDataFrameCallable(Protocol): def __call__(self, filename: str, parse_dates: _ParseDates=False) -> pd.DataFrame: ...
class SoftminusFlow(Flow): def __init__(self, set_restrictions=False) -> None: super(SoftminusFlow, self).__init__() self.softplus = torch.nn.Softplus() self.set_restrictions = False def forward(self, f0: torch.tensor, X: torch.tensor=None) -> torch.tensor: return gpytorch.utils....
def build_linknet(backbone, decoder_block, skip_connection_layers, decoder_filters=(256, 128, 64, 32, 16), n_upsample_blocks=5, classes=1, activation='sigmoid', use_batchnorm=True, dropout=None): input_ = backbone.input x = backbone.output skips = [(backbone.get_layer(name=i).output if isinstance(i, str) el...
_faiss _datasets _torch class RagTokenizerTest(TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() self.retrieval_vector_size = 8 vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] dp...
def split_data(data, output_file, days_test=DAYS_TEST, last_nth=None): data_end = datetime.fromtimestamp(data.Time.max(), timezone.utc) test_from = (data_end - timedelta(days_test)) session_max_times = data.groupby('SessionId').Time.max() session_train = session_max_times[(session_max_times < test_from....
class TextDatasetSplitter(DatasetSplitter): STORAGE_TYPE = 'text' def __init__(self, dataset_name, dataset_size, shard_size, num_epochs, shuffle=False): super(TextDatasetSplitter, self).__init__(dataset_name, dataset_size, shard_size, num_epochs) self._dataset_name = dataset_name self._s...
class PosAttTextualResEncoder(nn.Module): def __init__(self, input_nc=3, ngf=32, z_nc=256, img_f=256, L=6, layers=5, norm='none', activation='ReLU', use_spect=True, use_coord=False, image_dim=256, text_dim=256, multi_peak=True, pool_attention='max'): super(PosAttTextualResEncoder, self).__init__() s...
def gen_save_feat(audio_model, val_loader, save_path): device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) if (not isinstance(audio_model, nn.DataParallel)): audio_model = nn.DataParallel(audio_model) audio_model = audio_model.to(device) audio_model.eval() with torch.no_g...
class GraphConvolution(object): def __init__(self, input_dim, output_dim, placeholders, dropout=0.0, sparse_inputs=False, act=tf.nn.relu, bias=False, **kwargs): allowed_kwargs = {'name', 'logging'} for kwarg in kwargs.keys(): assert (kwarg in allowed_kwargs), ('Invalid keyword argument: ...
def VGG(input_shape, nbstages, nblayers, nbfilters, nbclasses, weight_decay=0.0, kernel_constraint=None, kernel_initializer='glorot_uniform', include_top=True, use_batchnorm=True, batchnorm_training=True, use_bias=True, act='relu', dropout=0.0, kernel_size=(3, 3), batchnorm_momentum=0.99, use_skips=False): if (K.im...
def main(config): model = Classifier(10, classifier_name='lenet', dataset='mnist', pretrained=False) data_classifier_state = torch.load(os.path.join(config.path, 'Classifier.pth'), map_location=None) if ('state_dict' in data_classifier_state): data_classifier_state = data_classifier_state['state_dic...
def main(_): tf.logging.set_verbosity(tf.logging.INFO) if ((not FLAGS.do_train) and (not FLAGS.do_eval) and (not FLAGS.do_predict)): raise ValueError("At least one of `do_train`, `do_eval` or `do_predict' must be True.") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if...
def process_single_pred(args): (target, pred, file) = args pred = upsample(pred, target) pred = align(pred, target) save_depth_image(file, pred)
def ensure_list(s: Optional[Union[(str, List[str], Tuple[str], Set[str])]]) -> List[str]: return (s if isinstance(s, list) else (list(s) if isinstance(s, (tuple, set)) else ([] if (s is None) else [s])))
def name_parts(name): assert isinstance(name, str), 'name must be a str' a = name.split('/') ff = a[(- 1)] b = ff.split(':') if (len(b) == 1): f = ff ext = '' else: f = ':'.join(b[:(- 1)]) ext = (':' + b[(- 1)]) p = '/'.join(a[:(- 1)]) return (p, f, ext)
def get_dataloader(batch_size=64, dataset='co3dv1', category=('apple',), split='train', shuffle=True, num_workers=8, debug=False, num_images=2): if debug: num_workers = 0 if (dataset == 'co3dv1'): dataset = Co3dv1Dataset(category=category, split=split, num_images=num_images, debug=debug) eli...
class KernelPCA(AutotabularPreprocessingAlgorithm): def __init__(self, n_components, kernel, degree=3, gamma=0.25, coef0=0.0, random_state=None): self.n_components = n_components self.kernel = kernel self.degree = degree self.gamma = gamma self.coef0 = coef0 self.rand...
class MetaConvModel(MetaModule): def __init__(self, in_channels, out_features, hidden_size=64, feature_size=64, drop_p=0.0): super(MetaConvModel, self).__init__() self.in_channels = in_channels self.out_features = out_features self.hidden_size = hidden_size self.feature_size ...
def create_loader(dataset, input_size, batch_size, is_training=False, use_prefetcher=True, no_aug=False, re_prob=0.0, re_mode='const', re_count=1, re_split=False, scale=None, ratio=None, hflip=0.5, vflip=0.0, color_jitter=0.4, auto_augment=None, num_aug_repeats=0, num_aug_splits=0, interpolation='bilinear', mean=IMAGEN...
def require_tf2onnx(test_case): return unittest.skipUnless(is_tf2onnx_available(), 'test requires tf2onnx')(test_case)
def check_optimizer_lr_wd(optimizer, gt_lr_wd): assert isinstance(optimizer, torch.optim.AdamW) assert (optimizer.defaults['lr'] == base_lr) assert (optimizer.defaults['weight_decay'] == base_wd) param_groups = optimizer.param_groups print(param_groups) assert (len(param_groups) == len(gt_lr_wd)...
class ROIPool3d(nn.Module): def __init__(self, output_size, spatial_scale): super(ROIPool3d, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale def forward(self, input, rois): return roi_pool_3d(input, rois, self.output_size, self.spatial_scale) ...
def _get_entity_spans(model, input_sentences, prefix_allowed_tokens_fn, redirections=None): output_sentences = model.sample(get_entity_spans_pre_processing(input_sentences), prefix_allowed_tokens_fn=prefix_allowed_tokens_fn) output_sentences = get_entity_spans_post_processing([e[0]['text'] for e in output_sente...
_torch class SelectiveCommonTest(unittest.TestCase): all_model_classes = ((MarianMTModel,) if is_torch_available() else ()) test_save_load__keys_to_ignore_on_save = ModelTesterMixin.test_save_load__keys_to_ignore_on_save def setUp(self): self.model_tester = ModelTester(self)
def check_col_str_list_exists(df: 'SparkDataFrame', column: Union[(List[str], str)], arg_name: str) -> None: if isinstance(column, str): invalidInputError((column in df.columns), (((column + ' in ') + arg_name) + ' does not exist in Table')) elif isinstance(column, list): for single_column in co...
def namespace2dict(namespace): d = dict(**namespace) for (k, v) in d.items(): if isinstance(v, NamespaceMap): d[k] = namespace2dict(v) return d
class LinearSpectStepper(SpectStepper): def RightHandItemsSpect(self, u_spect, **kw): if (self.dim != 2): raise NotImplementedError coe = self.coe rhi = 0 for k in range(3): for j in range((k + 1)): if isinstance(coe[(j, (k - j))], (int, float)...
class GraphModule(object): def __init__(self, name): self.name = name self._template = tf.make_template(name, self._build, create_scope_now_=True) self.__doc__ = self._build.__doc__ self.__call__.__func__.__doc__ = self._build.__doc__ def _build(self, *args, **kwargs): ra...
class DNN(models.Sequential): def __init__(self, Nin, Nh_l, Pd_l, Nout): super().__init__() self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1')) self.add(layers.Dropout(Pd_l[0])) self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2')) ...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)) 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_arg...
class GroupedEpochBatchIterator(EpochBatchIterator): def __init__(self, dataset, collate_fn, batch_samplers, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0, mult_rate=1, buffer_size=0, skip_remainder_batch=False): super().__init__(dataset, collate_fn, batch_samplers, seed, num_shards, shard_id, nu...
_pruner('pt_pattern_lock') class PytorchPatternLockPruner(PytorchBasePruner): def __init__(self, config, modules): super().__init__(config, modules) self.pattern = get_pattern(self.config, modules) assert (self.config.end_step == self.config.start_step), 'pattern_lock pruner only supports on...
def test_get_mseg_label_map_fpath_from_image_info() -> None: label_maps_dir = '/path/to/label/maps' log_id = 'abc__2020_06_01' camera_name = 'ring_rear_left' img_fname_stem = 'ring_rear_left_9999' label_map_fpath = mseg_interface.get_mseg_label_map_fpath_from_image_info(label_maps_dir, log_id, camer...
class ConvertTo32Bit(object): def __init__(self, env): self._env = env def __getattr__(self, name): return getattr(self._env, name) def step(self, action): (observ, reward, done, info) = self._env.step(action) observ = self._convert_observ(observ) reward = self._conve...
def compute_tflops(elapsed_time, accelerator, args): config_model = accelerator.unwrap_model(model).config checkpoint_factor = (4 if args.gradient_checkpointing else 3) batch_size = ((args.train_batch_size * accelerator.state.num_processes) * args.gradient_accumulation_steps) factor = (((((24 * checkpoi...
def worker_num_per_node(): if use_coworker(): return (nproc_per_node() - coworker_num_per_node()) else: return nproc_per_node()
def list_models(filter='', module='', pretrained=False, exclude_filters=''): if module: models = list(_module_to_models[module]) else: models = _model_entrypoints.keys() if filter: models = fnmatch.filter(models, filter) if exclude_filters: if (not isinstance(exclude_filt...
def fanin_init_weights_like(tensor): size = tensor.size() if (len(size) == 2): fan_in = size[0] elif (len(size) > 2): fan_in = np.prod(size[1:]) else: raise Exception('Shape must be have dimension at least 2.') bound = (1.0 / np.sqrt(fan_in)) new_tensor = FloatTensor(tens...
class QueryResponseDataset(Dataset): def __init__(self, df: pd.DataFrame, prompt_dict: dict, tokenizer: transformers.PreTrainedTokenizer, query_len: int, df_postprocessor: Optional[Callable]=None): super(QueryResponseDataset, self).__init__() if (df_postprocessor is not None): df = df_po...
def get_events(instrument, filter='note'): ret = [] for item in instrument: if ((filter == 'note') and (type(item) == miditoolkit.midi.containers.Note)): ret += [item] elif ((filter == 'pitch_bends') and (type(item) == miditoolkit.midi.containers.PitchBend)): ret += [item...
def getHyper_bolT(): hyperDict = {'weightDecay': 0, 'lr': 0.0002, 'minLr': 2e-05, 'maxLr': 0.0004, 'nOfLayers': 4, 'dim': 400, 'numHeads': 36, 'headDim': 20, 'windowSize': 20, 'shiftCoeff': (2.0 / 5.0), 'fringeCoeff': 2, 'focalRule': 'expand', 'mlpRatio': 1.0, 'attentionBias': True, 'drop': 0.1, 'attnDrop': 0.1, 'l...
def generate_dummy_code_boost(nclasses=10): decl = '' bindings = '' for cl in range(nclasses): decl += ('class cl%03i;\n' % cl) decl += '\n' for cl in range(nclasses): decl += ('class cl%03i {\n' % cl) decl += 'public:\n' bindings += (' py::class_<cl%03i>("cl%03i")...
def main(): (cfg, training_args) = prepare_args() (model, preprocessor) = load_pretrained(cfg.model_args, training_args) (model, preprocessor) = smart_prepare_target_processor(model, preprocessor, cfg.model_args, training_args) print_trainable_params(model) collator_kwargs = cfg.data_args.collator_k...
class NystromformerForMaskedLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class BasicMultiUpdateBlock(nn.Module): def __init__(self, args, hidden_dims=[]): super().__init__() self.args = args self.encoder = BasicMotionEncoder(args) encoder_output_dim = 128 self.gru08 = ConvGRU(hidden_dims[2], (encoder_output_dim + (hidden_dims[1] * (args.n_gru_laye...
def _test(): import torch pretrained = False models = [zfnet, zfnetb] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != zfnet) or (weight_coun...
def main(): args = parser.get_args() args.use_gpu = torch.cuda.is_available() if args.use_gpu: torch.backends.cudnn.benchmark = True if (args.launcher == 'none'): args.distributed = False else: args.distributed = True dist_utils.init_dist(args.launcher) (_, wo...
(frozen=True) class SynthesisResult(JsonSerializable): hunk: (str | None) is_pruned_halfway: bool is_unfinished: bool def to_json(self) -> Any: return {'hunk': self.hunk, 'is_pruned_halfway': self.is_pruned_halfway, 'is_unfinished': self.is_unfinished} def from_json(cls, d: Any) -> 'Synthesi...
def load_pretrained(cfg, Module, stage, **kwargs): save_path = Path(cfg.paths.pretrained.load) filename = BEST_CHCKPNT.format(stage=stage) chckpnt = get_latest_match((save_path / filename)) loaded_module = Module.load_from_checkpoint(chckpnt, **kwargs) return loaded_module
def compute_possible_shapes(low, high, depth): possible_shapes = {} for shape in range(low, (high + 1)): shapes = compute_max_depth(shape, max_depth=depth, print_out=False) if (len(shapes) == depth): possible_shapes[shape] = shapes return possible_shapes
def getBestFont(): e = wx.FontEnumerator() e.EnumerateFacenames() fontnames = e.GetFacenames(fixedWidthOnly=True) for name in ['DejaVu Sans Mono', 'Courier New']: if (name in fontnames): return name return None
def resnet101_ibn_a(pretrained=False, **kwargs): model = ResNet_IBN(block=Bottleneck_IBN, layers=[3, 4, 23, 3], ibn_cfg=('a', 'a', 'a', None), **kwargs) if pretrained: model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet101_ibn_a'])) return model
def evaluate(data_source): model.eval() total_loss = 0 ntokens = len(corpus.dictionary) hidden = model.init_hidden(eval_batch_size) for i in range(0, (data_source.size(0) - 1), args.bptt): (data, targets) = get_batch(data_source, i, evaluation=True) (output, hidden) = model(data, hid...
def string_tuple_to_string(strings): if (len(strings) == 0): string = '' elif (len(strings) == 1): string = strings[0] else: string = ' '.join([str(s) for s in strings]) return string
class EarlyStopping(Callback): def __init__(self, monitor: str='val_loss', min_delta: float=0.0, patience: int=10, verbose: int=0, mode: str='auto', baseline: Optional[float]=None, restore_best_weights: bool=False): super(EarlyStopping, self).__init__() self.monitor = monitor self.min_delta ...
def _dist_train(model, dataset, cfg, validate=False): data_loaders = [build_dataloader(dataset, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, dist=True)] model = MMDistributedDataParallel(model.cuda()) optimizer = build_optimizer(model, cfg.optimizer) runner = Runner(model, batch_processor, optimizer...
(reuse_venv=True) def docs(session: nox.Session) -> None: session.install('-r', 'docs/requirements.txt') session.chdir('docs') if ('pdf' in session.posargs): session.run('sphinx-build', '-M', 'latexpdf', '.', '_build') return session.run('sphinx-build', '-M', 'html', '.', '_build') i...
def load_gin_dataset(args): dataset = GINDataset(args.dataset, self_loop=True) return GraphDataLoader(dataset, batch_size=args.batch_size, collate_fn=collate, seed=args.seed, shuffle=True, split_name='fold10', fold_idx=args.fold_idx).train_valid_loader()
class ResBase(nn.Module): def __init__(self, res_name, pretrained=True): super(ResBase, self).__init__() model_resnet = res_dict[res_name](pretrained=pretrained) self.conv1 = model_resnet.conv1 self.bn1 = model_resnet.bn1 self.relu = model_resnet.relu self.maxpool = m...
def _create_Siamese_network(A, P, N, NOT_FISRT_CLONE): if NOT_FISRT_CLONE: featA = _image_to_feat(A, is_training=True, reuse=True) featP = _image_to_feat(P, is_training=True, reuse=True) featN = _image_to_feat(N, is_training=True, reuse=True) else: featA = _image_to_feat(A, is_tr...
def render(pieces, style): if pieces['error']: return {'version': 'unknown', 'full-revisionid': pieces.get('long'), 'dirty': None, 'error': pieces['error'], 'date': None} if ((not style) or (style == 'default')): style = 'pep440' if (style == 'pep440'): rendered = render_pep440(piece...
class Market1501(dataset.Dataset): def id(file_path): return int(file_path.split('/')[(- 1)].split('_')[0]) def camera(file_path): return int(file_path.split('/')[(- 1)].split('_')[1][1]) def ids(self): return [self.id(path) for path in self.imgs] def unique_ids(self): re...
def get_model(args, eval=False, eval_path_weights=''): p = Dict2Obj(args.model) encoder_weights = p.encoder_weights if (encoder_weights == 'None'): encoder_weights = None classes = args.num_classes (encoder_depth, decoder_channels) = get_encoder_d_c(p.encoder_name) spec_mth = [constants....
class Classifier_Concat(nn.Module): def __init__(self, cls_num): super(Classifier_Concat, self).__init__() self.fc1 = nn.Linear(1024, cls_num) def forward(self, feat_img, feat_sound): feat = torch.cat((feat_img, feat_sound), dim=(- 1)) g = self.fc1(feat) return g
def find_labels(model_class): model_name = model_class.__name__ base_classes = str(inspect.getmro(model_class)) if ('keras.engine.training.Model' in base_classes): signature = inspect.signature(model_class.call) elif ('torch.nn.modules.module.Module' in base_classes): signature = inspect...
def window_func(x, y, window, func): yw = rolling_window(y, window) yw_func = func(yw, axis=(- 1)) return (x[(window - 1):], yw_func)
def note_representation_processor_chain(features, codec: Codec, note_representation_config: NoteRepresentationConfig): tie_token = codec.encode_event(Event('tie', 0)) state_events_end_token = (tie_token if note_representation_config.include_ties else None) features = extract_sequence_with_indices(features, ...
class MountainCarEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30} def __init__(self): self.min_position = (- 1.2) self.max_position = 0.6 self.max_speed = 0.07 self.goal_position = 0.5 self.low = np.array([self.min_position,...
class TestBarrierBeforeMeasuremetsWhenABarrierIsAlreadyThere(QiskitTestCase): def test_handle_redundancy(self): qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr, cr) expected = QuantumC...
def load_progress(progress_csv_path): print(('Reading %s' % progress_csv_path)) entries = dict() with open(progress_csv_path, 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: for (k, v) in row.items(): if (k not in entries): ...
def run(args): if (not os.path.exists(args.output_dir)): os.makedirs(args.output_dir) output_path = os.path.join(args.output_dir, 'submission.csv') with open(args.testpkl_path, 'rb') as fin: pdbs = pickle.load(fin)[1] with open(args.dcalphas_path, 'rb') as fin: dcalphas = pickle....
def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed)
class EqualizedLinear(ConstrainedLayer): def __init__(self, nChannelsPrevious, nChannels, bias=True, **kwargs): ConstrainedLayer.__init__(self, nn.Linear(nChannelsPrevious, nChannels, bias=bias), **kwargs)
def assign_tp_fp_fn_tn(y_true: np.ndarray, y_pred: np.ndarray) -> Tuple[(int, int, int, int)]: is_TP = np.logical_and((y_true == y_pred), (y_pred == 1)) is_FP = np.logical_and((y_true != y_pred), (y_pred == 1)) is_FN = np.logical_and((y_true != y_pred), (y_pred == 0)) is_TN = np.logical_and((y_true == y...
class Roomba(object): def __init__(self): self.tty = None self.sci = None self.safe = True def start(self, tty='/dev/ttyUSB0', baudrate=57600): self.tty = tty self.sci = SerialCommandInterface(tty, baudrate) self.sci.add_opcodes(ROOMBA_OPCODES) def change_baud...
def quad_double_newton_at_series(pols, lser, idx=1, maxdeg=4, nbr=4, checkin=True, vrblvl=0): nbsym = number_of_symbols(pols) if (vrblvl > 0): print('the polynomials :') for pol in pols: print(pol) print('Number of variables :', nbsym) if checkin: if (not checkin_...