code
stringlengths
101
5.91M
def detect(cfgfile, weightfile, imgfolder): m = Darknet(cfgfile) m.load_weights(weightfile) print(('Loading weights from %s... Done!' % weightfile)) use_cuda = True if use_cuda: m.cuda() imgfiles = [x for x in os.listdir(imgfolder) if (x[(- 4):] == '.jpg')] imgfiles.sort() for im...
def mean_stdev_masked(input_tensor, is_valid, items_axis, dimensions_axis, fixed_ref=None): if (fixed_ref is not None): mean = fixed_ref else: mean = reduce_mean_masked(input_tensor, is_valid, axis=items_axis, keepdims=True) centered = (input_tensor - mean) n_new_dims = (input_tensor.sha...
def remove_extra_spaces(s: str) -> str: s = re.sub('\u200b', '', s) s = re.sub('[ \u3000]+', ' ', s) s = s.replace(' ?', '?') s = s.replace(' !', '!') s = s.replace(' ,', ',') s = s.replace(' .', '.') s = s.replace(' :', ':') return s.strip()
def sort_vol_slice(path): vol = re.findall('[a-z]+_([0-9]+)_.+?\\.npy', path.split('/')[(- 1)])[0] slice_ = re.findall('[a-z]+_[0-9]+_([0-9]+).+', path.split('/')[(- 1)])[0] return ((int(vol) * 1000) + int(slice_))
class ImagenetDataModule(LightningDataModule): name = 'imagenet' def __init__(self, data_dir: str, image_size: int=224, train_transforms=None, val_transforms=None, test_transforms=None, img_dtype='float32', cache_val_dataset=False, mixup: Optional[Callable]=None, num_aug_repeats: int=0, num_workers: int=0, batc...
class Trainer(): _STEPS_PER_LOSS_WRITE = 10 _STEPS_PER_GRAD_WRITE = 10 _STEPS_PER_LR_WRITE = 10 def __init__(self, module, device, train_metrics, train_loader, opts, lr_schedulers, max_epochs, max_grad_norm, test_metrics, test_loader, epochs_per_test, early_stopping, valid_loss, valid_loader, max_bad_va...
def session(engine): from sqlalchemy.orm import sessionmaker connection = engine.connect() trans = connection.begin() session = sessionmaker()(bind=connection) (yield session) session.close() trans.rollback() connection.close()
class ElvenShortSword(BaseShortSword): def __init__(self): super().__init__('elven short sword', weight=30, damage=D.Dice.from_str('d8'), material=M.Wood, hit=0)
def check_generator(params: Tuple, state: State) -> None: (num_nodes, _, _, num_agents, num_nodes_per_agent, max_step) = params assert (jnp.min(state.node_types) == UTILITY_NODE) assert (jnp.max(state.node_types) == (num_agents - 1)) assert (state.positions.shape == (num_agents,)) assert (state.conn...
def split_tfrecord(cfg, logger): tfrecord_path = cfg.DATASET.FFHQ_SOURCE ffhq_size = cfg.DATASET.SIZE part_size = (ffhq_size // cfg.DATASET.PART_COUNT) logger.info(('Splitting into % size parts' % part_size)) chunk_size = 1024 for i in range(0, (cfg.DATASET.MAX_RESOLUTION_LEVEL + 1)): pa...
def create_dataset_artifact(opt): with open(opt.data) as f: data = yaml.safe_load(f) logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
_name('new_eval') def test_new_eval_extreme(benchmark): new_eval_runner(benchmark, bond_dim=100, seq_len=1000)
def test_close_with_paused(): (configs, datasets) = _load_test_data() num_envs = len(configs) env_fn_args = tuple(zip(configs, datasets, range(num_envs))) with habitat.VectorEnv(env_fn_args=env_fn_args, multiprocessing_start_method='forkserver') as envs: envs.reset() envs.pause_at(3) ...
def pix2pix_discriminator(net, num_filters, padding=2, pad_mode='REFLECT', activation_fn=tf.nn.leaky_relu, is_training=False): del is_training end_points = {} num_layers = len(num_filters) def padded(net, scope): if padding: with tf.variable_scope(scope): spatial_pad ...
def cleanup_log_dir(log_dir): try: os.makedirs(log_dir) except OSError: files = glob.glob(os.path.join(log_dir, '*.monitor.csv')) for f in files: os.remove(f)
class BaseDetector(ABC): def __init__(self): pass def image_preprocess(self, img_name): pass def images_detection(self, imgs, orig_dim_list): pass def detect_one_img(self, img_name): pass
def _fitFunc(pars, drim, l, b, dist, ext, e_ext): amp = numpy.exp(pars[0]) fd = (amp * numpy.exp(pars[1])) fs = (amp * numpy.exp(pars[2])) fo = (amp * ((1.0 - fd) - fs)) dist_stretch = numpy.exp(pars[3]) model_ext = drim(l, b, (dist * dist_stretch), _fd=fd, _fs=fs, _fo=fo) return (0.5 * nump...
class Code2VecModel(Code2VecModelBase): def __init__(self, config: Config): self.keras_train_model: Optional[keras.Model] = None self.keras_eval_model: Optional[keras.Model] = None self.keras_model_predict_function: Optional[K.GraphExecutionFunction] = None self.training_status: Mode...
class Img2Tensor(object): def __init__(self, include_rgb: bool=False, include_grey: bool=True) -> None: super().__init__() assert (include_rgb or include_grey), f'Options must be True for at least one option, given {include_rgb}, {include_grey}' self.include_rgb = include_rgb ...
def to_numpy(X): if isinstance(X, np.ndarray): return X if hasattr(X, 'iloc'): return X.values if isinstance(X, (tuple, list)): return np.array(X) if (not isinstance(X, (torch.Tensor, PackedSequence))): raise TypeError(f'Cannot convert {type(X)} to a numpy array.') if...
def apply_random_motion_blur(img, chance, mb_max_size, mask=None, rnd_state=None): if (rnd_state is None): rnd_state = np.random mblur_rnd_kernel = (rnd_state.randint(mb_max_size) + 1) mblur_rnd_deg = rnd_state.randint(360) result = img if (rnd_state.randint(100) < np.clip(chance, 0, 100)): ...
def setup_estimator(hub_module, hub_module_signature, work_dir, tpu_name, save_checkpoints_steps, optimization_params, data_params): num_classes = data_params['dataset'].get_num_classes() params = {k: v for d in [optimization_params, data_params, {'hub_module': hub_module, 'hub_module_signature': hub_module_sig...
def build_non_MSE_yaml(): fake_yaml = "\n model:\n name: imagenet\n framework: onnxrt_qlinearops\n\n quantization:\n approach: post_training_static_quant\n calibration:\n sampling_size: 50\n op_wise: {\n 'Gather_*': {\n 'a...
class TanhNormal(torch.distributions.Distribution): def __init__(self, loc, scale): self._normal = Independent(Normal(loc, scale), 1) super().__init__(batch_shape=self._normal.batch_shape, event_shape=self._normal.event_shape) def log_prob(self, value, pre_tanh_value=None, epsilon=1e-06): ...
(version='2.0') def process_config(config): if isinstance(config, str): try: with open(config, 'r') as f: content = f.read() try: from .schema_check import schema except ImportError: from ...conf.config impor...
class TestAspectRatioGrouping(unittest.TestCase): def test_reiter_leak(self): data = [(1, 0), (0, 1), (1, 0), (0, 1)] data = [{'width': a, 'height': b} for (a, b) in data] batchsize = 2 dataset = AspectRatioGroupedDataset(data, batchsize) for _ in range(5): for (i...
def get_preds(model, span, inference_vectorizer): if (len(span) == 0): return 0 batch_instances = [span] sens = torch.FloatTensor(batch_instances) if USE_CUDA: sens = sens.cuda() preds = model(sens, batch_size=1) pred = preds[0].data.tolist()[0] return pred
def get_final_report(text): if ('FINAL REPORT' not in text): return None idx = text.index('FINAL REPORT') text = text[idx:] while (('(Over)' in text) and ('(Cont)' in text)): text = (text[0:text.index('(Over)')] + text[(text.index('(Cont)') + 6):]) return text
def set_seed(args: argparse.Namespace): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if (args.n_gpu > 0): torch.cuda.manual_seed_all(args.seed)
def _is_valid_glassbox_explainer(proposed_explainer): try: is_valid_explainer = _is_valid_explainer(proposed_explainer, 'model') has_fit = hasattr(proposed_explainer, 'fit') has_predict = hasattr(proposed_explainer, 'predict') if (not is_valid_explainer): _log.warning('Ex...
class PSP(BaseDecodeHead): def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): super(PSP, self).__init__(input_transform='multiple_select', **kwargs) self.psp_modules = PPM(pool_scales, self.in_channels[(- 1)], self.channels, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, ...
def fof_paths(G, i): fofs = {} neighbors = list(nx.neighbors(G, i)) for k in neighbors: for j in nx.neighbors(G, k): if ((j in neighbors) or (j == i)): continue if (j not in fofs): fofs[j] = 0 fofs[j] += 1 return fofs
def test_update_move_metadata_fn(): nmoves_per_update = 5 original_std_move = 0.9 def multiplicative_adjustment(val, accept_avg): return (val * accept_avg) move_masks = jnp.array([[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0]]) a...
def main(test_files, pretrained_file, labeldict, output_dir, batch_size=32): device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) print((20 * '='), ' Preparing for testing ', (20 * '=')) output_dir = os.path.normpath(output_dir) if (not os.path.exists(output_dir)): os.makedi...
class DeprecateAction(argparse.Action): def __init__(self, option_strings, dest, help=None, **kwargs): super(DeprecateAction, self).__init__(option_strings, dest, nargs=0, help=help, **kwargs) def __call__(self, parser, namespace, values, flag_name): help = (self.help if (self.mdhelp is not None...
class TestEasy_post_processing(TestCase): def test_easy_post_processing(self): inp = ["In two years ' time , the Scandinavian nation is slated to become the first in the world to phase out radio entirely .", 'Digitally , there are four times that number .', 'Frum : Ukrainians want to enter EU and lessen dep...
class NiceRepr(object): def __nice__(self): if hasattr(self, '__len__'): return str(len(self)) else: raise NotImplementedError('Define the __nice__ method for {!r}'.format(self.__class__)) def __repr__(self): try: nice = self.__nice__() cla...
def test_scale(): scale = Scale() assert (scale.scale.data == 1.0) assert (scale.scale.dtype == torch.float) x = torch.rand(1, 3, 64, 64) output = scale(x) assert (output.shape == (1, 3, 64, 64)) scale = Scale(10.0) assert (scale.scale.data == 10.0) assert (scale.scale.dtype == torch...
class MultiCameraImageDataset(Dataset): def __init__(self, ds_type='train', ds_name='wildtrack', root='/home/xzhangga/datasets/WildTrack/', crop_size=(256, 256), num_camera=7, **kwargs): super().__init__() self.path = Path(f'{root}') self.ds_name = ds_name self.ds_type = ds_type ...
class InceptionV3Aux(nn.Module): def __init__(self, inception_blocks=None, num_classes=1000, in_chans=3, drop_rate=0.0, global_pool='avg'): super(InceptionV3Aux, self).__init__() self.num_classes = num_classes self.drop_rate = drop_rate if (inception_blocks is None): ince...
def parse_args(): parser = argparse.ArgumentParser('Train Cognition Network') parser.add_argument('--cfg', type=str, help='path to config file') parser.add_argument('--model-dir', type=str, help='root path to store checkpoint') parser.add_argument('--log-dir', type=str, help='tensorboard log dir') p...
class SNLIClassifier(nn.Module): def __init__(self, num_classes, input_dim, hidden_dim, num_layers, use_batchnorm, dropout_prob): super(SNLIClassifier, self).__init__() self.num_classes = num_classes self.input_dim = input_dim self.hidden_dim = hidden_dim self.num_layers = nu...
class Conv1dWithInitialization(BaseModule): def __init__(self, **kwargs): super(Conv1dWithInitialization, self).__init__() self.conv1d = torch.nn.Conv1d(**kwargs) torch.nn.init.orthogonal_(self.conv1d.weight.data, gain=1) def forward(self, x): return self.conv1d(x)
def main(_): detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(pb_path, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, ...
def run_seq_group_alignments(seq_groups, alignment_runner, args): dirs = set(os.listdir(args.output_dir)) for (seq, names) in seq_groups: first_name = names[0] alignment_dir = os.path.join(args.output_dir, first_name) try: os.makedirs(alignment_dir) except Exception a...
def main(): data_path = '/path/to/musdb18hq' save_path = '/path/to/musdb18hq_custom_limiter_fixed_attack' batch_size = 1 num_workers = 1 sr = 44100 dataset = DelimitValidDataset(root=data_path, use_custom_limiter=True, custom_limiter_attack_range=[2.0, 2.0]) data_loader = DataLoader(dataset,...
def find_crop_x_boundaries(img): (width, height) = img.size pixels = img.load() white_color = (255, 255, 255) leftmost_x = None rightmost_x = None for x in range(width): all_white = True for y in range(height): if (pixels[(x, y)] != white_color): all_w...
class Render(): def __init__(self, width=1600, height=1200, name='GL Renderer', program_files=['simple.fs', 'simple.vs'], color_size=1, ms_rate=1): self.width = width self.height = height self.name = name self.display_mode = ((GLUT_DOUBLE | GLUT_RGB) | GLUT_DEPTH) self.use_in...
class UploadCommand(BaseUserCommand): def run(self): print(ANSI.red('Deprecated: used to be the way to upload a model to S3. We now use a git-based system for storing models and other artifacts. Use the `repo create` command instead.')) exit(1)
_model def gluon_resnet152_v1c(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], stem_width=32, stem_type='deep', **kwargs) return _create_resnet('gluon_resnet152_v1c', pretrained, **model_args)
class TestSnapshot(TfGraphTestCase): def setup_method(self): super().setup_method() self.temp_dir = tempfile.TemporaryDirectory() snapshot_config = SnapshotConfig(snapshot_dir=self.temp_dir.name, snapshot_mode='all', snapshot_gap=1) fixture_exp(snapshot_config, self.sess) for...
class nnUNetTrainerV2_insaneDA(nnUNetTrainerV2): def setup_DA_params(self): self.deep_supervision_scales = ([[1, 1, 1]] + list((list(i) for i in (1 / np.cumprod(np.vstack(self.net_num_pool_op_kernel_sizes), axis=0))))[:(- 1)]) if self.threeD: self.data_aug_params = default_3D_augmentatio...
def main(args): cfg = setup(args) print(cfg) if args.eval_only: model = Trainer.build_model(cfg) DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume) res = Trainer.test(cfg, model) return res trainer = Trainer(cfg) ...
def get_env(env_str, api_key=None, initialtags=None, poslabels=None, user=None, device=None, threshold=0.6): if (env_str == 'OpenImage'): return OpenImage(poslabels, initialtags) elif (env_str == 'Flickr'): return Flicker(api_key, initialtags, user, device, threshold) raise NotImplementedErr...
_model_architecture(model_name='s2spect2_conformer', arch_name='s2spect_conformer_translatotron2') def s2spect2_conformer_architecture_base_legacy(args): s2spect2_conformer_architecture_base(args)
def ndcg(correct_duplicates: List, retrieved_duplicates: List) -> float: if ((len(retrieved_duplicates) == 0) and (len(correct_duplicates) == 0)): return 1.0 if ((not len(retrieved_duplicates)) or (not len(correct_duplicates))): return 0.0 def dcg(rel): relevance_numerator = [((2 ** ...
('word') class WordTokenizer(Tokenizer): def __init__(self, word_splitter: WordSplitter=None, word_filter: WordFilter=PassThroughWordFilter(), word_stemmer: WordStemmer=PassThroughWordStemmer(), start_tokens: List[str]=None, end_tokens: List[str]=None) -> None: self._word_splitter = (word_splitter or SpacyW...
def createModel(input_data, input_size, sequence_length, slots, slot_size, intent_size, layer_size=128, isTraining=True): cell_fw = tf.contrib.rnn.BasicLSTMCell(layer_size) cell_bw = tf.contrib.rnn.BasicLSTMCell(layer_size) if (isTraining == True): cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, in...
def fuse_depth_map(frame, prev_keyframe): actual_fuse_v = np.vectorize(actual_fuse, signature='(1)->(),()', excluded=[1, 2]) (D, U) = actual_fuse_v(index_matrix, frame, prev_keyframe) frame.D = np.reshape(D, im_size) frame.U = np.reshape(U, im_size) return (frame.D, frame.U)
_pipeline_test class Text2TextGenerationPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def get_test_pipeline(self, model, tokenizer, processor): generator = Text2TextGenerationPipeline(model=model,...
class ExponentialScheduler(LinearScheduler): def __init__(self, start_value, end_value, n_iterations, start_iteration=0, base=10): self.base = base super(ExponentialScheduler, self).__init__(start_value=math.log(start_value, base), end_value=math.log(end_value, base), n_iterations=n_iterations, star...
class SSIterator(object): def __init__(self, dialogue_file, batch_size, seed, max_len=(- 1), use_infinite_loop=True, dtype='int32'): self.dialogue_file = dialogue_file self.batch_size = batch_size args = locals() args.pop('self') self.__dict__.update(args) self.load_f...
def _mel_to_linear_matrix(sr, n_fft, n_mels): m = librosa.filters.mel(sr, n_fft, n_mels) m_t = np.transpose(m) p = np.matmul(m, m_t) d = [((1.0 / x) if (np.abs(x) > 1e-08) else x) for x in np.sum(p, axis=0)] return np.matmul(m_t, np.diag(d))
class ExampleModel(nn.Module): def __init__(self): super(ExampleModel, self).__init__() self.test_cfg = None self.conv = nn.Conv2d(3, 3, 3) def forward(self, img, img_metas, return_loss=False, **kwargs): return img
class MultiHeadAttention(nn.Module): def __init__(self, n_head, d_k, d_in): super().__init__() self.n_head = n_head self.d_k = d_k self.d_in = d_in self.key = nn.Linear(d_in, (n_head * d_k)) self.query = nn.Parameter(torch.zeros(n_head, d_k)).requires_grad_(True) ...
def _trim(image): background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0))) diff = PIL.ImageChops.difference(image, background) diff = PIL.ImageChops.add(diff, diff, 2.0, (- 100)) bbox = diff.getbbox() if bbox: image = image.crop(bbox) return image
_registry(operator_type='PositionIds') class PositionIds(Operator): def __init__(self): super().__init__()
class Dictionary(object): def __init__(self, id2word, word2id, counts): assert (len(id2word) == len(word2id) == len(counts)) self.id2word = id2word self.word2id = word2id self.counts = counts self.bos_index = word2id[BOS_WORD] self.eos_index = word2id[EOS_WORD] ...
def video2frames(vid_path, out_dir): global default_ffmpeg_vcodec, default_ffmpeg_pix_fmt, default_ffmpeg_exe_path ffmpeg_exc_path = os.environ.get('ffmpeg_exe_path', default_ffmpeg_exe_path) imgs = glob.glob(os.path.join(out_dir, '*.png')) length = len(imgs) if (length > 0): print('Writing ...
def add_mim_extention(): if ('develop' in sys.argv): mode = 'symlink' elif (('sdist' in sys.argv) or ('bdist_wheel' in sys.argv)): mode = 'copy' else: return filenames = ['tools', 'configs', 'demo', 'model-index.yml'] repo_path = osp.dirname(__file__) mim_path = osp.join(...
_grad() def eval_model(interpolation_net, BFrameCompressor: nn.Module, IFrameCompressor: nn.Module, sequence: Path, binpath: Path, **args: Any) -> Dict[(str, Any)]: import time org_seq = RawVideoSequence.from_file(str(sequence)) if (org_seq.format != VideoFormat.YUV420): raise NotImplementedError(f'...
def TrainForceField(SetName_='GoldStd'): a = MSet(SetName_) a.Load() TreatedAtoms = a.AtomTypes() PARAMS['learning_rate'] = 1e-05 PARAMS['momentum'] = 0.95 PARAMS['max_steps'] = 201 PARAMS['batch_size'] = 100 PARAMS['test_freq'] = 5 PARAMS['tf_prec'] = 'tf.float64' PARAMS['GradSc...
def store_multprec_laurent_system(polsys, decimals, **nbvar): from phcpy.phcpy2c3 import py2c_syscon_clear_multprec_Laurent_system from phcpy.phcpy2c3 import py2c_syscon_initialize_number_of_multprec_Laurentials from phcpy.phcpy2c3 import py2c_syscon_store_multprec_Laurential py2c_syscon_clear_multprec_...
def define_net_d(opt): network_type = opt.pop('type') net_d = dynamic_instantiation(_arch_modules, network_type, opt) return net_d
def retrace_graph_with(gm: GraphModule, tracer: Tracer=None, func: Callable[([GraphModule], GraphModule)]=None) -> GraphModule: if ((tracer is None) and (func is None)): raise ValueError('Either a tracer or a function using a tracer must be provided.') elif ((tracer is not None) and (func is not None)):...
class GraphConv(nn.Module): def __init__(self, args): super(GraphConv, self).__init__() self.args = args hidden_size = args.hidden_size self.n_atom_feats = mol_features.N_ATOM_FEATS self.n_bond_feats = mol_features.N_BOND_FEATS self.W_message_i = nn.Linear((self.n_ato...
def run(data_fn, prop_missing=0.0, max_num_feature=(- 1), feature_selection='random', k=10, data_dir='_data', out_dir='_out'): from keras.models import load_model from riddle import emr, feature_importance from riddle.models import MLP start = time.time() base_out_dir = get_base_out_dir(out_dir, 'ri...
def get_descriptive_statistics(dict_, labels_): for j in range(len(labels_)): try: dict_[labels[j]] = (((str(np.mean(np.array(dict_[labels[j]]))) + ' (+/- ') + str(np.std(np.array(dict_[labels[j]])))) + ')') except: dict_.pop(labels[j]) return dict_
class BlenderbotOnnxConfig(OnnxSeq2SeqConfigWithPast): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task in ['default', 'seq2seq-lm']): common_inputs = OrderedDict([('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'})]) ...
class Cnn14(nn.Module): def __init__(self, config): super(Cnn14, self).__init__() self.bn0 = nn.BatchNorm2d(64) sr = config.wav.sr window_size = config.wav.window_size hop_length = config.wav.hop_length mel_bins = config.wav.mel_bins self.dropout = config.trai...
def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): def model_fn(features, labels, mode, params): tf.logging.info('*** Features ***') for name in sorted(features.keys()): tf.logging.info((' name = %s, sha...
.parametrize('alpha', [0.001, 0.1, 1, 10, 100, 1000, 1000000.0]) .parametrize('penalty, lambda_1, lambda_2', [('l1', 1, 0), ('l2', 0, 1)]) def test_elastic_net_l1_l2_equivalence(alpha, penalty, lambda_1, lambda_2): (X, y) = make_classification(random_state=0) lr_enet = LogisticRegression(penalty='elasticnet', l...
def rmse(y_true, y_pred): from keras import backend as K return K.sqrt(K.mean(K.square((y_pred - y_true)), axis=(- 1)))
def pattern_to_path(pattern): act_path = (pattern[0], 'activation', *pattern[1][0]) weight_path = (pattern[0], 'weight', *pattern[1][1]) return (act_path, weight_path)
def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu))...
class MixerBlock(nn.Module): def __init__(self, dim, num_patch, token_dim, channel_dim, dropout=0.0): super().__init__() self.token_mix = nn.Sequential(nn.LayerNorm(dim), Rearrange('b p d -> b d p'), FeedForward(num_patch, token_dim, dropout), Rearrange('b d p -> b p d')) self.channel_mix = ...
def register_all_coco(root): for (dataset_name, splits_per_dataset) in _PREDEFINED_SPLITS_COCO.items(): for (key, (image_root, json_file)) in splits_per_dataset.items(): register_coco_instances(key, _get_builtin_metadata(dataset_name), (os.path.join(root, json_file) if ('://' not in json_file) e...
def basic_cleaners(text): text = lowercase(text) text = collapse_whitespace(text) return text
def dense_model(timesteps, n_class, n_features, classifier_architecture, dropout): inputs = Input((timesteps, n_features)) x = Dense(128, activation=Mish())(inputs) x = LayerNormalization()(x) (x, a) = attention_simple(x, timesteps) for (d, dr) in zip(classifier_architecture, dropout): x = D...
def load_nerve(): test_images = [] test_labels = [] for file in glob.glob(os.path.join(args['test_path'], 'orig', '*.tif')): basename = os.path.basename(file) file_name = basename[:(- 4)] image_name = os.path.join(args['test_path'], 'orig', basename) label_name = os.path.join...
def create_corrupted_utt2uniq(input_dir, output_dir, num_replicas, include_original, prefix): corrupted_utt2uniq = {} utt2spk = parse_file_to_dict((input_dir + '/utt2spk'), value_processor=(lambda x: ' '.join(x))) keys = sorted(utt2spk.keys()) if include_original: start_index = 0 else: ...
class CustomTest(CustomBase): def __init__(self, size, test_images_list_file): super().__init__() with open(test_images_list_file, 'r') as f: paths = f.read().splitlines() self.data = ImagePaths(paths=paths, size=size, random_crop=False)
class SentenceMoversMetric(Metric): def __init__(self, wordrep='glove', metric='sms', n_workers=24, tokenize=True): self.wordrep = wordrep self.metric = metric self.model = (ElmoEmbedder() if (wordrep == 'elmo') else None) self.n_workers = n_workers self.tokenize = tokenize ...
class Vocab(defaultdict): def __init__(self, train=True): super().__init__((lambda : len(self))) self.train = train self.UNK = 'UNK' self[self.UNK] self.idx2w = self.update_idx2w() def set_vocab(self): self.train = False def train(self): self.train = T...
def test_DVCCA_methods(): max_epochs = 2 latent_dimensions = 2 encoder_1 = architectures.Encoder(latent_dimensions=latent_dimensions, feature_size=feature_size[0], variational=True) encoder_2 = architectures.Encoder(latent_dimensions=latent_dimensions, feature_size=feature_size[1], variational=True) ...
class RecordProcessor(FewGLUEDataProcessor): def __init__(self): super().__init__() self.labels = ['0', '1'] def get_examples(path, split, seed=42, max_train_candidates_per_question: int=10) -> List[InputExample]: examples = [] path = os.path.join(data_dir, '{}.jsonl'.format(spli...
class GPRNet(torch.nn.Module): def __init__(self, K=10): super(GPRNet, self).__init__() self.lin1 = Linear(1, 32) self.lin2 = Linear(32, 64) self.prop1 = GPR_prop(K) self.fc2 = torch.nn.Linear(64, 1) def reset_parameters(self): self.prop1.reset_parameters() de...
def run(cfg): print('Start making fragments') uio.may_create_folder(cfg.out_root) scenes = uio.list_folders(cfg.dataset_root, sort=False) print('{} scenes'.format(len(scenes))) for scene in scenes: run_scene(cfg, scene) print('Finished making fragments')
def computerNetParameters(net): params = list(net.parameters()) k = 0 for (index, i) in enumerate(params): l = 1 print((index + 1), ('layer structure:' + str(list(i.size())))) for j in i.size(): l *= j print(('layer paramenters: ' + str(l))) k += l pri...
class Normalizer(TextTransformer): def __init__(self, bigdl_type='float'): super(Normalizer, self).__init__(bigdl_type)