code
stringlengths
101
5.91M
class AlternateSequentialWeaveGraph(SequentialGraph): def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14): self.graph = tf.Graph() self.batch_size = batch_size self.max_atoms = max_atoms self.n_atom_feat = n_atom_feat self.n_pair_feat = n_pair_feat ...
class TestOptions(): def initialize(self): parser = argparse.ArgumentParser(description='test segmentation network') parser.add_argument('--model', type=str, default='DeepLab', help='available options : DeepLab and VGG') parser.add_argument('--GPU', type=str, default='0', help='which GPU to ...
def requires_submit(func): (func) def _wrapper(self, *args, **kwargs): if (self._future is None): raise JobError('Job not submitted yet!. You have to .submit() first!') return func(self, *args, **kwargs) return _wrapper
class SEMlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, linear=False, use_se=True): super().__init__() out_features = (out_features or in_features) hidden_features = (hidden_features or in_features) self.fc1 = nn.L...
def convert_pt_checkpoint_to_tf(model_type, pytorch_checkpoint_path, config_file, tf_dump_path, compare_with_pt_model=False, use_cached_models=True): if (model_type not in MODEL_CLASSES): raise ValueError('Unrecognized model type, should be one of {}.'.format(list(MODEL_CLASSES.keys()))) (config_class, ...
class VGG(nn.Module): arch_settings = {11: (1, 1, 2, 2, 2), 13: (2, 2, 2, 2, 2), 16: (2, 2, 3, 3, 3), 19: (2, 2, 4, 4, 4)} def __init__(self, depth, with_bn=False, num_classes=(- 1), num_stages=5, dilations=(1, 1, 1, 1, 1), out_indices=(0, 1, 2, 3, 4), frozen_stages=(- 1), bn_eval=True, bn_frozen=False, ceil_mo...
def evaluations(ty, pv): if (len(ty) != len(pv)): raise ValueError('len(ty) must equal to len(pv)') total_correct = total_error = 0 sumv = sumy = sumvv = sumyy = sumvy = 0 for (v, y) in zip(pv, ty): if (y == v): total_correct += 1 total_error += ((v - y) * (v - y)) ...
def order_terms(term_features, *args): if (len(term_features) == 0): if (len(args) == 0): return [] else: return tuple(([] for _ in range((len(args) + 1)))) keys = (([len(feature_idxs)] + sorted(feature_idxs)) for feature_idxs in term_features) sorted_items = sorted(z...
class NonLinearPredictor(nn.Module): def __init__(self, in_feats, out_feats, config): super().__init__() self.dropout = nn.Dropout(config['predictor_dropout']) self.linear1 = nn.Linear(in_feats, config['predictor_hidden_feats']) self.activation = nn.GELU() self.batch_normal =...
def convert_context(params, ctx): new_params = dict() for (k, v) in params.items(): new_params[k] = v.as_in_context(ctx) return new_params
def probability_to_one_hot(tensor, stochastic=False): if stochastic: prob = tensor.data.cpu().numpy().ravel().astype(np.float64) prob = (prob / np.sum(prob)) norm = np.sum(prob) prob = [(prob[i] / norm) for i in range(len(prob))] idx = int(np.random.choice(len(prob), 1, p=pro...
def Lambda_with_lambda(): from keras.layers import Lambda, Input from keras.models import Model x = Input((1,)) y = Lambda((lambda x: (x + 1)))(x) m = Model(x, y) yp = m.predict_on_batch([1, 2, 3]) print('np.array([1,2,3]) + 1:') print(yp)
class LabelSmoothingCrossEntropy(nn.Module): def __init__(self, smoothing=0.1): super(LabelSmoothingCrossEntropy, self).__init__() assert (smoothing < 1.0) self.smoothing = smoothing self.confidence = (1.0 - smoothing) def forward(self, x, target): logprobs = F.log_softma...
class DetDataSet(Dataset): def __init__(self, config, logger, mode): dataset_conf = config[mode]['dataset'] self.base_dir = dataset_conf['data_base_dir'] self.mode = mode self.logger = logger self.data_lines = self.get_image_info_list(dataset_conf['ano_file_path']) se...
class DilatedContraction(GraphRewriterBase): _elapsed_time('Pass DilatedContraction') def do_transformation(self): cur_graph = GraphAnalyzer() cur_graph.graph = self.model graph_info = cur_graph.parse_graph() target_nodes = cur_graph.query_fusion_pattern_nodes(['SpaceToBatchND', ...
def get_phantom_from_mhd(filename, range_file, material_file=None): (numpyImage, numpyOrigin, numpySpacing) = read_mhd(filename) phantom = phantoms.Phantom() phantom.mhd_file = filename phantom.range_file = range_file phantom.material_file = material_file phantom.phantom = numpyImage phantom...
def revert_reorientation(image: str) -> None: assert image.endswith('.nii.gz') expected_pkl = (image[:(- 7)] + '_originalAffine.pkl') assert isfile(expected_pkl), ('Must have a file with the original affine, as created by reorient_to_ras. Expected filename: %s' % expected_pkl) (original_affine, original...
class SpotClipSamplerDistributedSamplerWrapper(DistributedSampler): def __init__(self, sampler: SpotClipSampler, *args: Any, **kwargs: Any) -> None: shuffle = sampler.shuffle sampler.set_shuffle(False) super().__init__(_DatasetSamplerWrapper(sampler), *args, seed=sampler.seed, shuffle=shuffl...
class FeaturesNet(nn.Module): def __init__(self, feature_layers=[0, 3, 5], use_normalization=False): super().__init__() model = models.squeezenet1_1(pretrained=True) model.float() model.eval() self.model = model self.feature_layers = feature_layers self.mean =...
def fixed_padding(inputs, kernel_size, data_format): pad_total = (kernel_size - 1) pad_beg = (pad_total // 2) pad_end = (pad_total - pad_beg) if (data_format == 'channels_first'): padded_inputs = tf.pad(tensor=inputs, paddings=[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]]) else: ...
def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: torch.nn.utils.clip_grad_value_(group['params'], grad_clip)
def gen_nnsmith_rules(inst): lib = ('torch' if ('torch' in inst.name_index) else 'tf') try: with open(os.path.join(RULE_DIR, f'{lib}_nnsmith_reuse', f'{inst.name_index}.pkl'), 'rb') as f: res = pickle.load(f) except: res = [] return res
class OpenAIGPTConfig(PretrainedConfig): pretrained_config_archive_map = OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP model_type = 'openai-gpt' def __init__(self, vocab_size=40478, n_positions=512, n_ctx=512, n_embd=768, n_layer=12, n_head=12, afn='gelu', resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_n...
def load_adapter(pipe, ckpt_dir, adapter_name): unet_sub_dir = os.path.join(ckpt_dir, 'unet') text_encoder_sub_dir = os.path.join(ckpt_dir, 'text_encoder') pipe.unet.load_adapter(unet_sub_dir, adapter_name=adapter_name) if os.path.exists(text_encoder_sub_dir): pipe.text_encoder.load_adapter(text...
_mps class IFImg2ImgSuperResolutionPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase): pipeline_class = IFImg2ImgSuperResolutionPipeline params = (TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}) batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_...
def test_sphere_wrong_occupancy(): mesh = o3d.geometry.TriangleMesh.create_sphere(0.8) mesh = o3d.t.geometry.TriangleMesh.from_legacy(mesh) scene = o3d.t.geometry.RaycastingScene() scene.add_triangles(mesh) min_bound = (mesh.vertex.positions.min(0).numpy() * 1.1) max_bound = (mesh.vertex.positio...
def _create_model(variant, pretrained, model_kwargs): cfg = {} if variant.startswith('selecsls42'): cfg['block'] = SelecSLSBlock cfg['features'] = [(32, 0, 64, 64, True, 2), (64, 64, 64, 128, False, 1), (128, 0, 144, 144, True, 2), (144, 144, 144, 288, False, 1), (288, 0, 304, 304, True, 2), (30...
def _extract_weight_tuples(model): mlist = get_modules(model) return tuple([(m, 'weight') for m in mlist])
class CopyEnv(algorithmic_env.TapeAlgorithmicEnv): def __init__(self, base=5, chars=True): super(CopyEnv, self).__init__(base=base, chars=chars) def target_from_input_data(self, input_data): return input_data
def to_off(path): file_path = os.path.dirname(path) file_name = os.path.splitext(os.path.basename(path))[0] output_file = os.path.join(file_path, (file_name + '_scaled.off')) if os.path.exists(output_file): print('Exists: {}'.format(output_file)) return try: with HiddenPrints...
.slow def test_independent_samples(): (nsamples, nchains) = _get_sample_size() key = random.PRNGKey(0) independent_samples = random.normal(key, (nsamples, nchains)) (autocorr_curve, variance) = statistics.multi_chain_autocorr_and_variance(independent_samples) tau = statistics.tau(autocorr_curve) ...
class LazyModel(ABC): def __init__(self, loader: Callable[([], Callable)]): super().__init__() self.get_model = loader self.model: Optional[Callable] = None def is_in_memory(self) -> bool: return (self.model is not None) def load(self): if (not self.is_in_memory()): ...
class _TestClassD(_TestClassA): def __init__(self, input_shape: ShapeSpec, arg1: int, arg2, arg3=3): assert (input_shape == 'shape') super().__init__(arg1, arg2, arg3)
class InnerProductParameter(_message.Message): __metaclass__ = _reflection.GeneratedProtocolMessageType DESCRIPTOR = _INNERPRODUCTPARAMETER
def resume_exp_directory(cfg, pretrained_path=None): pretrained_path = (pretrained_path or cfg.get('pretrained_path', None) or cfg.get('pretrained_path', None)) if (os.path.basename(os.path.dirname(pretrained_path)) == 'checkpoint'): cfg.run_dir = os.path.dirname(os.path.dirname(cfg.pretrained_path)) ...
def test_ctypes_array_2d(): char2d = ((ctypes.c_char * 10) * 4)() int2d = ((ctypes.c_int * 15) * 3)() long2d = ((ctypes.c_long * 7) * 2)() for carray in (char2d, int2d, long2d): info = m.get_buffer_info(carray) assert (info.itemsize == ctypes.sizeof(carray[0]._type_)) assert (inf...
def check(variant, suffix, ckpt, gt_semantics): ckpt_dir = f'/srv/share/jye72/objectnav/{variant}-{suffix}/' ckpts = [] if (not osp.exists(ckpt_dir)): return ckpts = [int(p.split('.')[(- 2)]) for p in os.listdir(ckpt_dir)] existing_evals = [] eval_dir = f'/srv/share/jye72/objectnav_eval/...
def setup_gen_trainer(config, dataloader_object): model_path = os.path.join(config.generation_model_path, 'model.pt') print_msg(('PG Model Path: %s' % model_path), 'GenerateTrainerSetup') translate_evaluator = TranslationEvaluator(config, config.output_dir) dataloader_object.token_tokenizer = dataloader...
def get_in_dataset_patches_2(): ret_set = set() data = pandas.read_csv('csv/d4j-overlap.csv', header=0).fillna(0) for (index, type) in enumerate(data['Result-2']): if (type == 'Fixed function'): ret_set.add(data['Bug-2'][index].replace(' ', '-')) return ret_set
def _add_inplace_unary_passthrough_function(name, preferred=None): def iu_wrapper_function(self, *args, **kwargs): self._tensor = getattr(self._tensor, name)(*args, **kwargs) return self if (preferred is None): setattr(MPCTensor, name, iu_wrapper_function) else: setattr(MPCTe...
class QCNNBase(NNBase): def __init__(self, num_inputs, F_prior, recurrent=False, hidden_size=1024): super(QCNNBase, self).__init__(recurrent, hidden_size, hidden_size) self.main = nn.Sequential(Conv2d_Q(num_inputs, 32, 8, stride=4, F_prior=F_prior), nn.ReLU(), Conv2d_Q(32, 64, 4, stride=2, F_prior=F...
def compute_new_deaths(df, in_col='deaths'): return df[in_col].apply((lambda x: np.array([(x[(i + 1)] - x[i]) for i in range((len(x) - 1))])))
def _maybe_create_densepose_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]: if (not cfg.MODEL.DENSEPOSE_ON): return None use_masks = cfg.MODEL.ROI_DENSEPOSE_HEAD.COARSE_SEGM_TRAINED_BY_MASKS def has_densepose_annotations(instance: Instance) -> bool: for ann in instance[...
def benchmark_add_10k(benchmark, benchmark_data_10k): (_, solution_batch, objective_batch, measures_batch) = benchmark_data_10k def setup(): archive = SlidingBoundariesArchive(solution_dim=solution_batch.shape[1], dims=[10, 20], ranges=[((- 1), 1), ((- 2), 2)], remap_frequency=100, buffer_capacity=1000)...
def init_dist(rank, world_size): os.environ['LOCAL_RANK'] = str(rank) os.environ['RANK'] = str(rank) os.environ['WORLD_SIZE'] = str(world_size) os.environ['NPROC_PER_NODE'] = str(world_size) if torch.cuda.is_available(): atorch.init_distributed('nccl') else: atorch.init_distribut...
def standard_size(): from phcpy.phcpy2c3 import py2c_numbtrop_standard_size as get_size return get_size()
_lr_scheduler('inverse_sqrt') class InverseSquareRootSchedule(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if (len(args.lr) > 1): raise ValueError('Cannot use a fixed learning rate schedule with inverse_sqrt. Consider --lr-scheduler=fixed in...
def train_translation_model(data_dir, arch, extra_flags=None, task='translation', run_validation=False, lang_flags=None, extra_valid_flags=None): if (lang_flags is None): lang_flags = ['--source-lang', 'in', '--target-lang', 'out'] train_parser = options.get_training_parser() train_args = options.pa...
def lpg(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0, steps_per_epoch=4000, epochs=50, gamma=0.99, pi_lr=0.0003, vf_lr=0.001, ccritic_lr=0.001, train_v_iters=80, train_ccritic_iters=80, lam=0.97, max_ep_len=1000, target_kl=0.01, logger_kwargs=dict(), save_freq=10, backtrack_coeff=0.8, backtrack_it...
def resnext272_2x32d_svhn(num_classes=10, **kwargs): return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=2, bottleneck_width=32, model_name='resnext272_2x32d_svhn', **kwargs)
class TestFrameChange(QiskitTestCase): def test_default(self): fc_command = FrameChange(phase=1.57) self.assertEqual(fc_command.phase, 1.57) self.assertEqual(fc_command.duration, 0)
def _ensure_tensor(input): if isinstance(input, (int, float)): input = torch.tensor(input) return input
def _create_ngrams(tokens, n): ngrams = collections.Counter() for ngram in (tuple(tokens[i:(i + n)]) for i in range(((len(tokens) - n) + 1))): ngrams[ngram] += 1 return ngrams
class AgentParams(Params): def __init__(self): super(AgentParams, self).__init__() if (self.agent_type == 'sl'): if (self.circuit_type == 'ntm'): self.criteria = nn.BCELoss() self.optim = optim.RMSprop self.steps = 100000 se...
def _calculate_valid_crop_size(crop_size, upscale_factor): return (crop_size - (crop_size % upscale_factor))
def get_trainer(): x = ph([None, None, 3]) sx = tf.shape(x) noisy_x = x noisy_x = tf.clip_by_value(noisy_x, clip_value_max=1.0, clip_value_min=0.0) code_noise = tf.Variable(1.0) linear_code = enc(noisy_x) noisy_code = (linear_code - tf.random_normal(stddev=code_noise, shape=tf.shape(linear_c...
def get_name(node, nid): if (node.state is None): t = 0 else: t = int(node.state.t) name = ('%s %d' % (node.tag, nid)) return (name, (nid + 1))
.filterwarnings('ignore::DeprecationWarning') def test_log_file() -> None: with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) configure_logging(fname=(tmpdir / 'test1.log')) logger.debug('Debug message') logger.info('Info message') logger.warning('Warn message') ...
def norm_ema_inplace(moving_avg, new, decay): moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay)) moving_avg.data.copy_(l2norm(moving_avg.data))
class KukaKr3(Robot): def __init__(self, name: str, id_num: int, world, sim_step: float, use_physics_sim: bool, base_position: Union[(list, np.ndarray)], base_orientation: Union[(list, np.ndarray)], resting_angles: Union[(list, np.ndarray)], control_mode: Union[(int, str)], ik_xyz_delta: float=0.005, ik_rpy_delta: ...
class GeneralData(NiceRepr): def __init__(self, meta_info=None, data=None): self._meta_info_fields = set() self._data_fields = set() if (meta_info is not None): self.set_meta_info(meta_info=meta_info) if (data is not None): self.set_data(data) def set_meta...
def main(): env = gym.make('MountainCar-v0') act = deepq.load('mountaincar_model.pkl') while True: (obs, done) = (env.reset(), False) episode_rew = 0 while (not done): env.render() (obs, rew, done, _) = env.step(act(obs[None])[0]) episode_rew += re...
def compute_cost_mat(X_1, X_2, rescale_cost=False, cost_distance='l2'): (n_1, _) = X_1.size() (n_2, _) = X_2.size() if (cost_distance == 'l2'): X_1 = X_1.view(n_1, 1, (- 1)) X_2 = X_2.view(1, n_2, (- 1)) squared_dist = ((X_1 - X_2) ** 2) cost_mat = torch.sum(squared_dist, dim...
def get_loss(task, loss_name, data_batch, out, dataset_name): check_out_fmt(task, out, dataset_name) if (task == 'cls'): label = data_batch['label'].to(out['logit'].device) if (loss_name == 'cross_entropy'): if ('label_2' in data_batch.keys()): label_2 = data_batch['l...
def densenet121(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet: return DenseNet(torchvision.models.densenet121(pretrained, progress, **kwargs))
_register(log_shape=False, use_scope=False) def BNReLU(x, name=None): x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
def do_tokenize(args): print(time.clock()) data_builder.tokenize(args) print(time.clock())
def _a3_tab1(brd): return ((((((- 0.0247) * (brd ** 4.0)) + (0.1718 * (brd ** 3.0))) - (0.4124 * (brd ** 2.0))) - (0.5944 * brd)) + 0.7333)
class AutoregressiveLSTMCell(tf.contrib.rnn.RNNCell): def __init__(self, lstm, output_size): super(AutoregressiveLSTMCell, self).__init__() self.lstm_cell = lstm self._output_size = output_size def state_size(self): return (self.lstm_cell.state_size + self._output_size) def o...
def test_double_double_track(vrblvl=0): mickey = ['x^2 + 4*y^2 - 4;', '2*y^2 - x;'] (start, startsols) = total_degree_start_system(mickey, vrblvl=vrblvl) print('the start system :') for pol in start: print(pol) print('the start solutions :') for (idx, sol) in enumerate(startsols): ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride) self.bn2 = ...
class EvalArguments(TrainingArguments): topk: int = field(default=1000) threads: int = field(default=32)
class ProbeRegimen(): def __init__(self, args): self.args = args self.max_epochs = args['probe_training']['epochs'] self.params_path = os.path.join(args['reporting']['root'], args['probe']['params_path']) def set_optimizer(self, probe): self.optimizer = optim.Adam(probe.parameter...
def generate_uid_from_pbobject(pb_object): json_string = json.dumps(MessageToDict(pb_object, including_default_value_fields=True, preserving_proto_field_name=True), indent=2, sort_keys=True) out = StringIO() out.write(json_string) uid = hashlib.sha1(out.getvalue().encode('utf-8')).hexdigest() out.cl...
class AVATAR_OT_SetBodyShape(bpy.types.Operator): bl_idname = 'avt.set_body_shape' bl_label = 'Set Body Shape' bl_description = 'Set Body Shape' def execute(self, context): global mAvt obj = mAvt.body cp_vals = obj.data.copy() mAvt.np_mesh_prev = mAvt.read_verts(cp_vals) ...
class Text(list): def __init__(self, string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA], language='en', encoding='utf-8'): self.encoding = encoding if _is_tokenstring(string): (token, language) = (string.tags, getattr(string, 'language', language)) if string: i...
def test_track_parallel_progress_list(capsys): results = mmcv.track_parallel_progress(sleep_1s, [1, 2, 3, 4], 2, bar_width=4) (out, _) = capsys.readouterr() assert (out == '[ ] 0/4, elapsed: 0s, ETA:\r[> ] 1/4, 1.0 task/s, elapsed: 1s, ETA: 3s\r[>> ] 2/4, 2.0 task/s, elapsed: 1s, ETA: 1s\r[>>>...
class GaussianCriterion(Criterion): def __init__(self, bigdl_type='float'): super(GaussianCriterion, self).__init__(None, bigdl_type)
((torch.cuda.device_count() < 2), 'test requires 2 GPUs') class TestBMUF(unittest.TestCase): def bmuf_process(self, cfg, args, iterations): processes = [] results = Manager().dict() torch.multiprocessing.spawn(fn=functools.partial(single_gpu_training, cfg, args), args=(iterations, results), ...
def load_data(): dir = '/backup3/jcxu/data/compression-data.json' train_file = '/backup3/jcxu/data/compression-train.tsv' test_file = '/backup3/jcxu/data/compression-test.tsv' with open(dir, 'r') as fd: lines = fd.read().splitlines() line_num = [idx for (idx, x) in enumerate(lines) if (x == ...
def setup(args): cfg = get_cfg() add_densepose_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() default_setup(cfg, args) setup_logger(output=cfg.OUTPUT_DIR, distributed_rank=comm.get_rank(), name='densepose') return cfg
def train(args, logger, run_id): model = get_model(args) optimizer = get_optim(args, model) (train_data, eval_data) = get_data(args) train_dataset = LocalizationDataset(train_data) eval_dataset = LocalizationDataset(eval_data) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, ...
def s2hot(arr): h = [] for i in range(len(arr)): if (arr[i][0] == 1.0): h.append([1, 0]) else: h.append([0, 1]) return array(h)
def vote(predicted_file: str, size: int): import json from cap.data.utils import iobes_to_spans, spans_to_iobes, span_vote from cap.training.metrics.span_f1_measure import SpanF1Measure from conlleval import evaluate_conll_file metric = SpanF1Measure() lines = list() with open(predicted_file...
def color_begin_end(latex_contents, latex_file, str, color_name, inner_outer='outer'): all_begin_brace_list = get_all_begin_brace_nodes(latex_contents, latex_file, str=str) for begin_brace_list in all_begin_brace_list: latex_contents = add_color_begin_end_command(latex_contents, begin_brace_list[(- 1)],...
def load_movielens100k(as_frame: bool=False) -> Union[(Tuple[(np.ndarray, np.ndarray, np.ndarray)], Tuple[(pd.DataFrame, pd.DataFrame, pd.DataFrame)])]: with resources.path('pytorch_widedeep.datasets.data', 'MovieLens100k_data.parquet.brotli') as fpath: df_data = pd.read_parquet(fpath) with resources.pa...
def entropy_loss(Pz, Pzt, Pzzt): (Pz, Pzt, Pzzt) = batch_probability(Pz, Pzt, Pzzt) entropy = (Pz * torch.log(Pz)).sum() entropy += (Pzt * torch.log(Pzt)).sum() entropy += (Pzzt * torch.log(Pzzt)).sum() entropy /= 3 return entropy
class PSAMask(Function): def __init__(self, psa_type=0, mask_H_=None, mask_W_=None): super(PSAMask, self).__init__() assert (psa_type in [0, 1]) self.psa_type = psa_type assert (((mask_H_ is None) and (mask_W_ is None)) or ((mask_H_ is not None) and (mask_W_ is not None))) se...
def create_dir_and_delete_content(directory): os.makedirs(directory, exist_ok=True) files = sorted(filter((lambda f: (os.path.isfile(f) and f.endswith('.h5'))), map((lambda f: os.path.join(directory, f)), os.listdir(directory))), key=os.path.getmtime) for file in files[:(- 4)]: logging.info('removin...
class NormedHistogram(nn.Module): def __init__(self, nbins: int=256, r_min: float=0.0, r_max: float=255.0): super(NormedHistogram, self).__init__() assert isinstance(nbins, int), type(nbins) assert (nbins > 0), nbins self.nbins = nbins assert isinstance(r_min, float), type(r_...
class HitNet(): def __init__(self, model_path, model_type=ModelType.eth3d, camera_config=DEFAULT_CONFIG, max_dist=10): self.model = self.initialize_model(model_path, model_type, camera_config, max_dist) def __call__(self, left_img, right_img): return self.update(left_img, right_img) def init...
class ModuleParallel(nn.Module): def __init__(self, module): super(ModuleParallel, self).__init__() self.module = module def forward(self, x_parallel): return [self.module(x) for x in x_parallel]
class InitialStateBridge(Bridge): def __init__(self, encoder_outputs, decoder_state_size, params, mode): super(InitialStateBridge, self).__init__(encoder_outputs, decoder_state_size, params, mode) if (not hasattr(encoder_outputs, self.params['bridge_input'])): raise ValueError('Invalid b...
def createdataset_byid(ds_files_subsets, subsets, classname, out_path): for s in subsets: try: folderpath = os.path.join(out_path, s, classname) os.makedirs(folderpath) except OSError: print(('Creation of the directory %s failed' % out_path)) else: ...
class MixerBlock(nn.Module): def __init__(self, config): super(MixerBlock, self).__init__() self.token_mlp_block = MlpBlock(config.n_patches, config.tokens_mlp_dim) self.channel_mlp_block = MlpBlock(config.hidden_dim, config.channels_mlp_dim) self.pre_norm = nn.LayerNorm(config.hidde...
def squeezenet1_1(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> SqueezeNet: return SqueezeNet(torchvision.models.squeezenet1_1(pretrained, progress, **kwargs))
def train_collate_fn(batch): (imgs, pids, camids, img_paths) = zip(*batch) pids = torch.tensor(pids, dtype=torch.int64) return (torch.stack(imgs, dim=0), pids, camids, img_paths)
def serve(): port = str(config.grpc_api_port) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) neural_solution_pb2_grpc.add_TaskServiceServicer_to_server(TaskSubmitterServicer(), server) server.add_insecure_port(('[::]:' + port)) server.start() logger.info(('Server started, liste...
def main(): p = create_config(args.config_env, args.config_exp) print(colored(p, 'red')) print(colored('Retrieve model', 'blue')) model = get_model(p) print('Model is {}'.format(model.__class__.__name__)) print('Model parameters: {:.2f}M'.format((sum((p.numel() for p in model.parameters())) / 10...
class Visualizer(): def __init__(self, opt): self.opt = opt self.tf_log = opt.tf_log self.use_html = (opt.isTrain and (not opt.no_html)) self.win_size = opt.display_winsize self.name = opt.name if self.tf_log: import tensorflow as tf self.tf = ...