code
stringlengths
101
5.91M
def decay(X, n_bins=4): ids = (np.round((np.linspace(1, len(X), (n_bins + 1)) + 1e-10)) - 1) ids = ids.astype(np.uint8) D_bins = [X[ids[i]:(ids[(i + 1)] + 1)] for i in range(0, 4)] with warnings.catch_warnings(): warnings.simplefilter('ignore', category=RuntimeWarning) D = (np.nanmean(D_...
def read_requirements_file(path): with open(path, 'r') as f: return [_ for _ in f.readlines() if _[:1].isidentifier()]
class AsyncCpuSampler(AsyncParallelSamplerMixin, ParallelSamplerBase): def __init__(self, *args, CollectorCls=DbCpuResetCollector, eval_CollectorCls=CpuEvalCollector, **kwargs): super().__init__(*args, CollectorCls=CollectorCls, eval_CollectorCls=eval_CollectorCls, **kwargs) def initialize(self, affinit...
class PreResNet110Drop(): base = PreResNetDrop args = list() kwargs = {'depth': 110} transform_train = transforms.Compose([transforms.Resize(32), transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994...
def distillation_loss(y, labels, teacher_scores, T, alpha, reduction_kd='mean', reduction_nll='mean'): if (teacher_scores is not None): d_loss = ((nn.KLDivLoss(reduction=reduction_kd)(F.log_softmax((y / T), dim=1), F.softmax((teacher_scores / T), dim=1)) * T) * T) else: assert (alpha == 0), 'alp...
class DatasetsHolder(): def read_datasets(inp_folder_path): with os.scandir(inp_folder_path) as entries: return dict([(entry.name, pd.read_csv(entry, index_col=0)) for entry in entries if entry.is_file()])
def test_tuning(vrblvl=0): show_parameters(vrblvl) print('setting the condition level to 2 ...') set_condition_level(2, vrblvl) level = get_condition_level(vrblvl) print('the condition level :', level) autotune_parameters(level, 14, vrblvl) show_parameters(vrblvl) autotune_parameters(0, ...
class VGG(nn.Module): def __init__(self, vgg_name, Num_classes=100): super(VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, Num_classes) def forward(self, x): out = self.features(x) out = out.view(out.size(0), (- 1)) ...
def levenshtein(reference, hypothesis, progress_bar=False): assert (len(reference) == len(hypothesis)) text = zip(reference, hypothesis) if progress_bar: text = tqdm(text, total=len(reference)) d = [distance(r, h) for (r, h) in text] output = pd.DataFrame({'reference': reference, 'hypothesis...
class Scenario(BaseScenario): def make_world(self): world = World() world.dim_c = 2 num_good_agents = 1 num_adversaries = 3 num_agents = (num_adversaries + num_good_agents) num_landmarks = 2 world.agents = [Agent() for i in range(num_agents)] for (i, a...
def set_attr_shape(node, key, value): try: node.attr[key].CopyFrom(attr_value_pb2.AttrValue(shape=tensor_shape.as_shape(value).as_proto())) except KeyError: pass
class InceptionBlock(nn.Module): def __init__(self, in_channels, mid1_channels_list, mid2_channels_list, avg_pool, bias, use_bn): super(InceptionBlock, self).__init__() assert (len(mid1_channels_list) == 2) assert (len(mid2_channels_list) == 4) self.branches = Concurrent() se...
class BottleneckBlock(ResNetBlockBase): def __init__(self, in_channels, out_channels, *, bottleneck_channels, stride=1, num_groups=1, norm='BN', stride_in_1x1=False, dilation=1): super().__init__(in_channels, out_channels, stride) if (in_channels != out_channels): self.shortcut = Conv2d(...
def resnet18(in_channels=3, pretrained=False, progress=True, **kwargs): return _resnet(in_channels, 'resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)
def get_match_index(src_bboxes, dst_bboxes): indices = set() for src_bbox in src_bboxes: for (i, dst_bbox) in enumerate(dst_bboxes): iou = calculate_iou(src_bbox, dst_bbox) if (iou >= 0.5): indices.add(i) return list(indices)
def joint_coherence(): model.eval() with torch.no_grad(): pzs = model.pz(*model.pz_params).sample([1000]) gen_images = model.vaes[0].dec(pzs)[0].squeeze(1) gen_sentences = model.vaes[1].dec(pzs)[0].argmax(dim=(- 1)).squeeze(1) score = calculate_corr(gen_images, fn_to_emb(gen_sent...
class ConvBnAct(nn.Module): def __init__(self, in_chs, out_chs, kernel_size, stride=1, pad_type='', act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, norm_kwargs=None): super(ConvBnAct, self).__init__() assert (stride in [1, 2]) norm_kwargs = (norm_kwargs or {}) self.conv = select_conv2d...
def walk_to_root(node): result = [] n = node while (n.parent != None): result.append(n) n = n.parent result.append(n) return result
def get_model(): dvec_inp = Input(shape=[emb_dim], name='dvec') input_spec = Input(shape=[T_dim, num_freq], name='input_spec') x = Reshape((T_dim, num_freq, 1))(input_spec) x = ZeroPadding2D(((0, 0), (3, 3)))(x) x = Conv2D(filters=64, kernel_size=[1, 7], dilation_rate=[1, 1])(x) x = BatchNormali...
def build_meta4train_lmdb(args): out_dir = os.path.join(args.saving_dir, 'meta') lmdb_path = os.path.join(args.saving_dir, 'lmdb') os.makedirs(out_dir, exist_ok=True) if os.path.exists(lmdb_path): shutil.rmtree(lmdb_path) os.makedirs(lmdb_path, exist_ok=True) trainset_dict_path = os.path...
def throughput(args, model_path, forecaster, train_loader, test_loader, records): try: forecaster.load(model_path) except: forecaster.fit(train_loader, epochs=1) if (args.framework == 'tensorflow'): inference_sample_num = sum([x.shape[0] for (x, _) in test_loader]) else: ...
def _parse_args(): parser = ArgumentParser() parser.add_argument('--input_folder', type=str, required=True, help='Path to the folder of parquet files.') parser.add_argument('--output_folder', type=str, default='.', help='The path to save the preprocessed data to parquet files. ') args = parser.parse_arg...
def log_every_n_seconds(lvl, msg, n=1, *, name=None): (caller_module, key) = _find_caller() last_logged = _LOG_TIMER.get(key, None) current_time = time.time() if ((last_logged is None) or ((current_time - last_logged) >= n)): logging.getLogger((name or caller_module)).log(lvl, msg) _LOG_...
def get_act_layer(name: Union[(Type[nn.Module], str)]='relu'): if (not name): return None if isinstance(name, type): return name if (not (is_no_jit() or is_exportable() or is_scriptable())): if (name in _ACT_LAYER_ME): return _ACT_LAYER_ME[name] if (is_exportable() an...
def get_LR_cheating(): np.random.seed(500) random.seed(500) torch.manual_seed(500) i = 100 (acc, f1, prec, rec, _, _, _, _) = run_LR_cheating(i, True) LR = ['Logistic Regression Cheating', '{:.2f}'.format(acc), '{:.2f}'.format(prec), '{:.2f}'.format(rec), '{:.2f}'.format(f1)] return LR
def path2Path(path): assert isinstance(path, (Path, str)), type(path) return (Path(path) if isinstance(path, str) else path)
class LVIS(BaseImageDataset): def __init__(self, root=None, image_loader=jpeg4py_loader_w_failsafe, data_fraction=None, min_area=None, split='train'): root = (env_settings().lvis_dir if (root is None) else root) super().__init__('LVIS', root, image_loader) self.img_pth = os.path.join(root, '...
class ACVLoss(): def __init__(self, loss_type='attn_only'): super().__init__() assert (loss_type in ['attn_only', 'freeze_attn', 'full', 'test']), f'loss_type {loss_type} not supported' self.loss_fn = None if (loss_type == 'attn_only'): self.loss_fn = self.model_loss_trai...
def get_std_of_list(list_of_values): if (len(list_of_values) > 1): return np.std(list_of_values) return 0
def gen_updates_adagrad(loss, all_parameters, learning_rate=1.0, epsilon=1e-06): all_grads = [theano.grad(loss, param) for param in all_parameters] all_accumulators = [theano.shared((param.get_value() * 0.0)) for param in all_parameters] updates = [] for (param_i, grad_i, acc_i) in zip(all_parameters, a...
def create_indoor_map(height, width, corridor_radius, iterations, room_number, room_width, room_height, no_overlap): tree = [] map = initialize_map(height, width) insert_root_node(map, tree) for i in range(iterations): random_position = sample(map, corridor_radius) nearest_node = find_ne...
def prepare_parser(): usage = 'Calculate and store inception metrics.' parser = ArgumentParser(description=usage) parser.add_argument('--dataset', type=str, default='I128_hdf5', help='Which Dataset to train on, out of I128, I256, C10, C100...Append _hdf5 to use the hdf5 version of the dataset. (default: %(d...
_pipeline_test class ZeroShotClassificationPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING tf_model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def get_test_pipeline(self, model, tokenizer, processor): classifier = ZeroShotClassificationPipeline...
class ParameterRange(): def __init__(self, lo, hi): self.lo = lo self.hi = hi def get_lower_bound(self): return self.lo def get_upper_bound(self): return self.hi
def info_to_nt(value, name='info'): if (not isinstance(value, dict)): return value ntc = globals()[name] values = {k: info_to_nt(v, '_'.join([name, k])) for (k, v) in value.items() if (k in ntc._fields)} values.update({k: 0 for k in ntc._fields if (k not in values)}) return ntc(**values)
def apply_grad_processors(grads, gradprocs): g = [] for (grad, var) in grads: if (grad is None): logger.warn('No Gradient w.r.t {}'.format(var.op.name)) else: g.append((grad, var)) for proc in gradprocs: g = proc.process(g) return g
class IterLoader(): def __init__(self, loader, length=None): self.loader = loader self.length = length self.iter = None def __len__(self): if (self.length is not None): return self.length return len(self.loader) def new_epoch(self): self.iter = ite...
def retrieve_info_for_model(model_type, frameworks: Optional[List[str]]=None): if (model_type not in auto_module.MODEL_NAMES_MAPPING): raise ValueError(f'{model_type} is not a valid model type.') model_name = auto_module.MODEL_NAMES_MAPPING[model_type] config_class = auto_module.configuration_auto.C...
def compute_metrics(task_name, preds, labels): assert (len(preds) == len(labels)) if (task_name == 'cola'): return {'mcc': matthews_corrcoef(labels, preds)} elif (task_name == 'sst-2'): return {'acc': simple_accuracy(preds, labels)} elif (task_name == 'mrpc'): return acc_and_f1(p...
_model def ssl_resnext50_32x4d(pretrained=True, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], cardinality=32, base_width=4, **kwargs) model.default_cfg = default_cfgs['ssl_resnext50_32x4d'] if pretrained: load_pretrained(model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_...
def get_or_make(name: str, node_type: str, tree: bpy.types.NodeTree, label_tag: str='(zpy) ', pos: Tuple[float]=None) -> bpy.types.Node: node = tree.nodes.get(name, None) if (node is None): node = tree.nodes.new(node_type) node.name = name node.label = f'{label_tag}{name}' node.bl_descri...
class BallQuery(Function): def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, new_xyz: torch.Tensor) -> torch.Tensor: if (not (open3d.core.cuda.device_count() > 0)): raise NotImplementedError assert new_xyz.is_contiguous() assert xyz.is_contiguous() idx = ba...
def eval_10_crop_accuracy(opt, model): print('10-crop test epoch ------->') valdir = opt.localization_val_path random_crop_nonreproducible_transform = get_nonreproducible_rand_transform(opt) print('Creating data loader for test set...') multi_crop_val_dataset = ImageFolder(root=valdir, opt=opt, tran...
_data_params('usps2mnist') class Usps2MnistParams(DatasetParams): num_channels = 3 image_size = 16 mean = 0.5 std = 0.5 num_cls = 10 target_transform = None
class _SetEvalIterationsHook(session_run_hook.SessionRunHook): def __init__(self, num_steps): self._num_steps = num_steps def begin(self): self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): self._iterations_per_loop_va...
def _create_dummy_ann_file(ann_file): data = {'text': ',', 'label': {'address': {'': [[15, 16]]}, 'name': {'': [[0, 2]]}}} with open(ann_file, 'w') as fw: fw.write((json.dumps(data, ensure_ascii=False) + '\n'))
def validate_megengine_model(platform, model_file, input_file, mace_out_file, input_names, input_shapes, input_data_formats, output_names, output_shapes, output_data_formats, validation_threshold, input_data_types, log_file): import megengine._internal as mgb if (not os.path.isfile(model_file)): common....
class TrainLoop(object): def __init__(self, generator, disc_list, optimizer, train_loader, alpha=0.8, nadir_slack=1.1, train_mode='vanilla', checkpoint_path=None, checkpoint_epoch=None, cuda=True): if (checkpoint_path is None): self.checkpoint_path = os.getcwd() else: self.ch...
def train(args): processor = data_utils.AscProcessor() label_list = processor.get_labels() tokenizer = ABSATokenizer.from_pretrained('bert-base-multilingual-cased') train_examples = processor.get_train_examples(args.data_dir, 'train_rels.json', method=args.method) num_train_steps = (int((len(train_e...
def test_digits_cosine_lazy(): model = GraphCutSelection(100, 'cosine', optimizer='lazy') model.fit(X_digits) assert_array_equal(model.ranking, digits_cosine_ranking) assert_array_almost_equal(model.gains, digits_cosine_gains, 4) assert_array_almost_equal(model.subset, X_digits[model.ranking])
def process_folder(q, data_dir, output_dir, stride=1): while True: if q.empty(): break folder = q.get() image_path = os.path.join(data_dir, folder) dump_image_path = os.path.join(output_dir, folder) if (not os.path.isdir(dump_image_path)): os.makedirs(...
def get_down_block(down_block_type, num_layers, in_channels, out_channels, temb_channels, add_downsample, resnet_eps, resnet_act_fn, transformer_layers_per_block=1, num_attention_heads=None, resnet_groups=None, cross_attention_dim=None, downsample_padding=None, use_linear_projection=False, only_cross_attention=False, u...
class TestTokenBlockDataset(unittest.TestCase): def _build_dataset(self, data, **kwargs): sizes = [len(x) for x in data] underlying_ds = test_utils.TestDataset(data) return TokenBlockMixtureDataset(underlying_ds, sizes, **kwargs) def test_complete_break_mode(self): data = [torch....
class DenoisingDataset(FairseqDataset): def __init__(self, dataset, sizes, vocab, mask_idx, mask_whole_words, shuffle, seed, args, eos=None, item_transform_func=None): self.dataset = dataset self.sizes = sizes self.vocab = vocab self.shuffle = shuffle self.seed = seed ...
class SetupCallback(Callback): def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config): super().__init__() self.resume = resume self.now = now self.logdir = logdir self.ckptdir = ckptdir self.cfgdir = cfgdir self.config = config ...
class TestCheckpointUtils(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def _train_transformer(self, seed, extra_args=None): if (extra_args is None): extra_args = [] with tempfile.Tempora...
class XconfigTrivialOutputLayer(XconfigLayerBase): def __init__(self, first_token, key_to_value, prev_names=None): assert (first_token == 'output') XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names) def set_default_configs(self): self.config = {'input': '[-1]', 'dim':...
def to_categorical(y_seq, nb_classes): Y = np.zeros((y_seq.shape + (nb_classes,))) for (sample_idx, sample) in enumerate(y_seq): for (tag_idx, tag) in enumerate(sample): if (tag != 0): Y[(sample_idx, tag_idx, (int(tag) - 1))] = 1 return Y
class ResNet(nn.Module): __factory = {18: torchvision.models.resnet18, 34: torchvision.models.resnet34, 50: torchvision.models.resnet50, 101: torchvision.models.resnet101, 152: torchvision.models.resnet152} def __init__(self, depth, pretrained=True, cut_at_pooling=False, num_features=0, norm=False, dropout=0, n...
class Statistics(): def __init__(self, name='AVG'): self.name = name self.history = [] self.sum = 0 self.cnt = 0 def update(self, val): self.history.append(val) self.sum += val self.cnt += 1 def mean_std(self): mean = np.mean(self.history) ...
def get_netG(): model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-512', pretrained=True, useGPU=False) return model.netG
def get_ipex_version(): global _ipex_version if (_ipex_version is not None): return _ipex_version import intel_extension_for_pytorch as ipex _ipex_version = ipex.__version__ return _ipex_version
def discount(x, gamma): assert (x.ndim >= 1) return scipy.signal.lfilter([1], [1, (- gamma)], x[::(- 1)], axis=0)[::(- 1)]
_optimizer('adafactor') class FairseqAdafactor(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = Adafactor(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--adafactor-eps', default='(1e-30, 1e-3)', metavar='E', help=...
def dataloader_msrvtt_test(args, tokenizer): msrvtt_testset = MSRVTT_DataLoader(jsonl_path=args.val_csv, train_jsonl=args.train_csv, ans2label_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, u...
def blind(output_size, dtype=np.float32): def _thunk(obs_space): pipeline = (lambda x: torch.zeros(output_size)) return (pipeline, spaces.Box((- 1), 1, output_size, dtype)) return _thunk
def sqnxt23v5_w1(**kwargs): return get_squeezenext(version='23v5', width_scale=1.0, model_name='sqnxt23v5_w1', **kwargs)
class ResidualDenseBlock(nn.Module): def __init__(self, mid_channels=64, growth_channels=32): super().__init__() for i in range(5): out_channels = (mid_channels if (i == 4) else growth_channels) self.add_module(f'conv{(i + 1)}', nn.Conv2d((mid_channels + (i * growth_channels)...
class SpatialDropout1D(KerasLayer): def __init__(self, p=0.5, input_shape=None, **kwargs): super(SpatialDropout1D, self).__init__(None, float(p), (list(input_shape) if input_shape else None), **kwargs)
def get_speed(vehicle): vel = vehicle.get_velocity() return (3.6 * math.sqrt((((vel.x ** 2) + (vel.y ** 2)) + (vel.z ** 2))))
def add_generic_args(parser, root_dir) -> None: parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output directory where the model predictions and checkpoints will be written.') parser.add_argument('--n_tpu_cores', dest='tpu_cores', type=int) parser.add_argument('--max_gra...
class ResNet34Fc(nn.Module): def __init__(self): super(ResNet34Fc, self).__init__() model_resnet34 = models.resnet34(pretrained=True) self.conv1 = model_resnet34.conv1 self.bn1 = model_resnet34.bn1 self.relu = model_resnet34.relu self.maxpool = model_resnet34.maxpool ...
def train(): parser = HfArgumentParser((ModelArguments, TrainingArguments, Args)) (model_args, training_args, args) = cast(tuple[(ModelArguments, TrainingArguments, Args)], parser.parse_args_into_dataclasses()) dataset = load_dataset('json', data_files=args.datafile_paths, split='train') model_key = mod...
def compute_rank(tensor): tensor = tensor.detach().cpu() rank = np.linalg.matrix_rank(tensor, tol=0.0001) return rank
def fast_auc(actual, predicted): pred_ranks = rankdata(predicted) return _auc(actual, pred_ranks)
def get_sub_feed(input, place): new_dict = {} res_feed = {} key_name = ['bbox', 'im_info', 'im_id', 'im_shape', 'bbox_flip'] for k in key_name: if (k in input.keys()): new_dict[k] = input[k] for k in input.keys(): if ('image' in k): new_dict[k] = input[k] ...
class MergeFeatureLabelFeatureTransformer(FeatureTransformer): def __init__(self, bigdl_type='float'): super(MergeFeatureLabelFeatureTransformer, self).__init__(bigdl_type)
def slogdet_product(xs: PyTree) -> SLArray: slogdets = jax.tree_map(jnp.linalg.slogdet, xs) (slogdet_leaves, _) = jax.tree_util.tree_flatten(slogdets, is_tuple_of_arrays) (sign_prod, log_prod) = functools.reduce((lambda a, b: ((a[0] * b[0]), (a[1] + b[1]))), slogdet_leaves) return (sign_prod, log_prod)
def merge_dict_list(dict_list): new_dict = {} for d in dict_list: for key in d: if (key not in new_dict): new_dict[key] = d[key] return new_dict
def main(_): mkdir_if_missing(FLAGS.checkpoint_dir) mkdir_if_missing(FLAGS.log_dir) mkdir_if_missing(FLAGS.train_samples_dir) train_models.train()
def run(*args, **kwargs) -> Any: assert_tf_initialized() return tf.get_default_session().run(*args, **kwargs)
def _split_runs_on_parameters(runs): def _is_dagnode_parameterized(node): return any((isinstance(param, Parameter) for param in node.op.params)) out = [] for run in runs: groups = groupby(run, _is_dagnode_parameterized) for (group_is_parameterized, gates) in groups: if (n...
def test_anisotropic_hernquist_meanvr_directint(): pot = potential.HernquistPotential(amp=2.3, a=1.3) betas = [(- 0.7), (- 0.5), (- 0.4), 0.0, 0.3, 0.5] for beta in betas: dfh = constantbetaHernquistdf(pot=pot, beta=beta) tol = 1e-08 check_meanvr_directint(dfh, pot, tol, beta=beta, r...
class IntentDetector(): def __init__(self): pass def intent_detection(self, model_name, query): prompt = generate_intent_prompt(query) params = {} params['model_name'] = model_name params['prompt'] = prompt params['temperature'] = 0.001 params['top_k'] = 1...
def change_path(json_file_path, target_path): with open(json_file_path, 'r') as fp: data_json = json.load(fp) data = data_json['data'] for i in range(len(data)): ori_path = data[i]['wav'] new_path = ((target_path + '/audio_16k/') + ori_path.split('/')[(- 1)]) data[i]['wav'] =...
def identify_meshes(dir_): meshes_track1 = list(dir_.glob('**/*_normalized.npz')) meshes_track2 = list(dir_.glob('**/fusion_textured.npz')) meshes_challenge2 = list(dir_.glob('**/model_*.obj')) if meshes_track1: meshes = sorted(meshes_track1) challenge = 1 track = 1 elif mesh...
class ChatGLMForCausalLM(_BaseGGMLClass): GGML_Module = 'bigdl.llm.ggml.model.chatglm' GGML_Model = 'ChatGLM' HF_Class = AutoModel
class ExampleThing(HyperBase): def __init__(self, **hyper_params): super(ExampleThing, self).__init__(**hyper_params) self.register_hyper_param('hyper_a') self.register_hyper_param('hyper_b', default=23) self.register_hyper_param('hyper_c', default=(lambda : (2 * 21)), help='help') ...
class MobileNetV2_LandScape(nn.Module): def __init__(self, num_classes=1000, width_mult=1.0): super(MobileNetV2_LandScape, self).__init__() block = InvertedResidual input_channel = 32 last_channel = 1280 inverted_residual_setting = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2]...
def get_input_output(graph_path, args): fix_dynamic_shape = 300 if args.use_nc: from neural_compressor.model import Model model = Model(graph_path) if (args.output_name in [[], ['']]): raise AttributeError("Empty '--output_name', please specify a valid '--output_name'.") ...
_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): with tf.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) preact = slim.batch_norm(inputs, activation_fn=tf.nn....
def FeatureDropout(x): attention = torch.mean(x, dim=1, keepdim=True) (max_val, _) = torch.max(attention.view(x.size(0), (- 1)), dim=1, keepdim=True) threshold = (max_val * np.random.uniform(0.7, 0.9)) threshold = threshold.view(x.size(0), 1, 1, 1, 1).expand_as(attention) drop_mask = (attention < th...
def fix_word_offset(row): try: if (row.raw_sentence[(row.word_offset - 1)].lower() != row.verb): if (row.raw_sentence[row.word_offset].lower() == row.verb): print('Fixing word offset {}'.format(row.id)) return (row.word_offset + 1) if (row.raw_sentence...
def map_fn(fun, x): ensembles = [fun(elem) for elem in x] features = ensembles[0].keys() ensembled_dict = {} for feat in features: ensembled_dict[feat] = torch.stack([dict_i[feat] for dict_i in ensembles], dim=(- 1)) return ensembled_dict
class DensePoseOutputsVisualizer(object): def __init__(self, inplace=True, cmap=cv2.COLORMAP_PARULA, alpha=0.7, to_visualize=None, **kwargs): assert (to_visualize in 'IUV'), 'can only visualize IUV' self.to_visualize = to_visualize if (self.to_visualize == 'I'): val_scale = (255....
class PassiveAggressiveComponentTest(BaseClassificationComponentTest): __test__ = True res = dict() res['default_iris'] = 0.92 res['iris_n_calls'] = 5 res['default_iris_iterative'] = 0.92 res['iris_iterative_n_iter'] = 32 res['default_iris_proba'] = 0. res['default_iris_sparse'] = 0.4 ...
def train(model_id, max_steps): import tensorflow as tf from template_ffd.model import get_builder tf.logging.set_verbosity(tf.logging.INFO) builder = get_builder(model_id) builder.initialize_variables() if (max_steps is None): max_steps = builder.default_max_steps builder.train(max_...
def unpack_data_file(source_file_name, target_dir, start_idx): print('Unpacking {} to {}'.format(source_file_name, target_dir)) data = load_file(source_file_name) for (idx, (image_data, label_idx)) in tqdm(enumerate(zip(data['data'], data['labels'])), total=len(data['data'])): subdir = os.path.join(...
def solve_fbrfive4(): print('\nsolving a generic 5-point 4-bar design problem ...', end='') pols = fbrfive4() sols = solve(pols) fail = (len(sols) != 36) if (not fail): print(' passed') else: print(' failed') return int(fail)
def l2re_loss(data, name, pred, solution): l2re = (torch.norm((pred - solution)) / torch.norm(solution)) return l2re