code
stringlengths
101
5.91M
class EsmConfig(PretrainedConfig): model_type = 'esm' def __init__(self, vocab_size=None, mask_token_id=None, pad_token_id=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1026, initial...
def convert_to_coco_dict(dataset_name): dataset_dicts = DatasetCatalog.get(dataset_name) metadata = MetadataCatalog.get(dataset_name) if hasattr(metadata, 'thing_dataset_id_to_contiguous_id'): reverse_id_mapping = {v: k for (k, v) in metadata.thing_dataset_id_to_contiguous_id.items()} revers...
class MyNewExpectedFlux(ExpectedFlux): def __init__(self, config): super().__init__() pass def compute_expected_flux(self, forest): pass
def define_saver(exclude=None): variables = [] exclude = (exclude or []) exclude = [re.compile(regex) for regex in exclude] for variable in tf.global_variables(): if any((regex.match(variable.name) for regex in exclude)): continue variables.append(variable) saver = tf.tra...
def build_dataset(src_trgs_pairs, opt, mode='one2one', include_original=True): word2idx = opt.vocab['word2idx'] return_examples = [] oov_target = 0 max_oov_len = 0 max_oov_sent = '' for (idx, (source, targets)) in enumerate(src_trgs_pairs): src = [(word2idx[w] if ((w in word2idx) and (wo...
class Params(): def __init__(self, json_path): self.update(json_path) def save(self, json_path): with open(json_path, 'w') as f: json.dump(self.__dict__, f, indent=4) def update(self, json_path): with open(json_path) as f: params = json.load(f) sel...
class MemComputer(): def __init__(self, net_def, np_data_type): self.net_def = net_def self.np_data_type = np_data_type self.const_tensor_names = [] for const_tensor in net_def.tensors: self.const_tensor_names.append(const_tensor.name) self.input_names = [] ...
class RGBD_sal(nn.Module): def __init__(self): super(RGBD_sal, self).__init__() feats = list(models.vgg16_bn(pretrained=True).features.children()) self.conv0 = nn.Conv2d(4, 64, kernel_size=3, padding=1) self.conv1 = nn.Sequential(*feats[1:6]) self.conv2 = nn.Sequential(*feats...
class Conv2dGaussian(ConvNdGaussianMixin, torch.nn.Conv2d): def forward(self, input): return self._forward_impl(input, F.conv2d)
class MissingPackageError(Exception): error_message = "Mandatory package '{name}' not found!" def __init__(self, package_name: str): self.package_name = package_name super(MissingPackageError, self).__init__(self.error_message.format(name=package_name))
def _megatron_glm_attn_com(ranks, tensor_shape, orig_module): return ([('all_reduce', ranks, tensor_shape)] * 4)
def other_class(n_classes, current_class): if ((current_class < 0) or (current_class >= n_classes)): error_str = 'class_ind must be within the range (0, nb_classes - 1)' raise ValueError(error_str) other_class_list = list(range(n_classes)) other_class_list.remove(current_class) other_cla...
def make_dataset(dir, class_to_idx, extensions=None, is_valid_file=None): images = [] dir = os.path.expanduser(dir) if (not ((extensions is None) ^ (is_valid_file is None))): raise ValueError('Both extensions and is_valid_file cannot be None or not None at the same time') if (extensions is not N...
class TACREDProcessor(DataProcessor): def __init__(self): super().__init__(labels=['no_relation', 'org:founded', 'org:subsidiaries', 'per:date_of_birth', 'per:cause_of_death', 'per:age', 'per:stateorprovince_of_birth', 'per:countries_of_residence', 'per:country_of_birth', 'per:stateorprovinces_of_residence'...
class BaseProgressBar(Subscriber): def __init__(self): super().__init__() self.type = 'progressbar' self.touched = False self.iter = None self.t_start = None self.t_done = None def start(self, iterations): self.touched = True self.iter = int(iterat...
class PrefixTuning(GPT2PreTrainedModel): def __init__(self, config, model_gpt2, optim_prefix=False, preseqlen=5, use_infix=False, deep_param=False): super().__init__(config) print('under the PrefixTuning model') self.match_n_layer = config.n_layer self.match_n_head = config.n_head ...
def bessel_basis(n, k): zeros = Jn_zeros(n, k) normalizer = [] for order in range(n): normalizer_tmp = [] for i in range(k): normalizer_tmp += [(0.5 * (Jn(zeros[(order, i)], (order + 1)) ** 2))] normalizer_tmp = (1 / (np.array(normalizer_tmp) ** 0.5)) normalizer +...
class QDA(AutotabularClassificationAlgorithm): def __init__(self, reg_param, random_state=None): self.reg_param = float(reg_param) self.estimator = None def fit(self, X, Y): import sklearn.discriminant_analysis estimator = sklearn.discriminant_analysis.QuadraticDiscriminantAnalys...
class Cluster(object): def __init__(self, root, img_path, combine_all=True): self.images_dir = osp.join(root) self.img_path = img_path self.train_path = self.img_path self.gallery_path = '' self.query_path = '' self.train = [] self.gallery = [] self.qu...
class AngleLoss(nn.Module): def __init__(self, gamma=0): super(AngleLoss, self).__init__() self.gamma = gamma self.it = 0 self.LambdaMin = 5.0 self.LambdaMax = 1500.0 self.lamb = 1500.0 def forward(self, input, target): self.it += 1 (cos_theta, phi...
def train_model(config, exp_dir): torch.manual_seed(config.random_seed) (tokenizer, max_len_token) = get_tokenizer(config) vocab = get_vocab(config, tokenizer, max_len_token) model = get_model(config, vocab, max_len_token) model = model.cuda() optimizer = optim.Adam(filter((lambda p: p.requires_...
def jsonline_iter(path) -> Iterable[Dict]: with open(path) as file: for line in file: obj = json.loads(line) if obj: (yield obj)
class MyRandomCrop(object): def __init__(self, size): self.size = size def __call__(self, img): (width, height) = img.size (target_width, target_height) = self.size pad_width = 0 pad_height = 0 do_padding = False if (width < target_width): pad_...
def _status_file(key, host=None): if (host is not None): return os.path.join(_status_path(key), ('status-%s.txt' % host)) else: return os.path.join(_status_path(key), 'status.txt')
def get_macro_recall(guess_entities, gold_entities, mode='strong'): (guess_entities, gold_entities) = get_doc_level_guess_gold_entities(guess_entities, gold_entities) all_scores = [get_micro_recall(guess_entities[k], gold_entities[k], mode) for k in guess_entities] return ((sum(all_scores) / len(all_scores)...
class MemoryDataParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _MEMORYDATAPARAMETER
class SquaredLR(LambdaStepLR): def __init__(self, optimizer, max_iter, last_step=(- 1)): super(SquaredLR, self).__init__(optimizer, (lambda s: ((1 - (s / (max_iter + 1))) ** 2)), last_step)
class LongformerSelfAttentionForBart(nn.Module): def __init__(self, config, layer_id): super().__init__() self.embed_dim = config.d_model self.longformer_self_attn = LongformerSelfAttention(config, layer_id=layer_id) self.output = nn.Linear(self.embed_dim, self.embed_dim) def for...
def dglane_from_position(p: T2value, network: LaneletNetwork, init_lane_selection: int=0, succ_lane_selection: int=0) -> DgLanelet: lane_id = network.find_lanelet_by_position([p]) assert (len(lane_id[0]) > 0), p lane = network.find_lanelet_by_id(lane_id[0][init_lane_selection]) merged_lane = Lanelet.all...
def get_model_size(model: Union[(nn.Module, torch.jit.ScriptModule)]): tmp_model_path = Path('temp.p') if isinstance(model, torch.jit.ScriptModule): torch.jit.save(model, tmp_model_path) else: torch.save(model.state_dict(), tmp_model_path) size = tmp_model_path.stat().st_size os.remo...
class TFData2VecVisionForSemanticSegmentation(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
_module() class mit_b2(MixVisionTransformer): def __init__(self, **kwargs): super(mit_b2, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], **k...
class ErrorMetricsAverager(object): def __init__(self): (self.rmse_avg, self.mae_avg, self.absrel_avg) = (0, 0, 0) (self.inv_rmse_avg, self.inv_mae_avg, self.inv_absrel_avg) = (0, 0, 0) self.total_count = 0 def accumulate(self, error_metrics): assert isinstance(error_metrics, Err...
def main(argv): if (len(argv) > 1): raise RuntimeError('generate_copts needs no command line args') generate_copt_file(StarlarkStyle()) generate_copt_file(CMakeStyle())
def get_pretraining_stl10(data_dir): train_data = CIFAR10Pair(numpy_file=(data_dir + 'train_unlabeled.npz'), class_type=classes, transform=train_transform) memory_data = CIFAR10Mem(numpy_file=(data_dir + 'train.npz'), class_type=classes, transform=test_transform_stl10) test_data = CIFAR10Mem(numpy_file=(dat...
def from_txt(txt): captions = [] with open(txt, 'rb') as f: for line in f: captions.append(line.strip()) return captions
def build_vision_tower(vision_tower_cfg, **kwargs): vision_tower = getattr(vision_tower_cfg, 'vision_tower', getattr(vision_tower_cfg, 'mm_vision_tower', None)) is_absolute_path_exists = os.path.exists(vision_tower) if (is_absolute_path_exists or vision_tower.startswith('openai') or vision_tower.startswith(...
(signature3, parallel=True) def erf_numba3(x): t = (1 / (1 + (p * np.abs(x)))) return (np.sign(x) * (1 - ((t * ((a1 + (a2 * t)) + (a3 * (t ** 2)))) * np.exp((- (x ** 2))))))
def compute_jittered_speed(factor: float, speed: int) -> float: min_speed = (speed * (1 - factor)) max_speed = (speed * (1 + factor)) jittered_speed = np.random.uniform(min_speed, max_speed) return jittered_speed
class PPOTransition(NamedTuple): done: Done action: Action value: Value reward: chex.Array log_prob: chex.Array obs: chex.Array info: Dict
def add_resizing_arguments(parser): group = parser.add_mutually_exclusive_group() group.add_argument('--resize_factor', type=float, help="Option to resize the images. Examples: '0.5' downscale half, '2' upscale twice, '1' no resizing (default)") group.add_argument('--image_size', type=int, help='Option to r...
def sql_dataframe_writer_api(spark): print('Start running dataframe writer API') sc = spark.sparkContext sqlContext = SQLContext(sc) df = spark.createDataFrame([(2, 'Alice'), (5, 'Bob')], ['age', 'name']) df.write.format('parquet').bucketBy(100, 'age', 'name').mode('overwrite').saveAsTable('bucketed...
def extract_graph(ebm, feature_index, normalization='none', use_feature_bounds=True): feature_name = ebm.feature_names_in_[feature_index] feature_type = ebm.feature_types_in_[feature_index] scores = ebm.term_scores_[feature_index][1:(- 1)] stds = ebm.standard_deviations_[feature_index][1:(- 1)] norm...
class NormalizedEnv(Serializable): def __init__(self, env, scale_reward=1.0, normalize_obs=False, normalize_reward=False, obs_alpha=0.001, reward_alpha=0.001, normalization_scale=1.0, dummy_flag=False): Serializable.quick_init(self, locals()) self._scale_reward = 1 self._wrapped_env = env ...
def sample_normal_ig(prior): (mu, lambda0, alpha, beta) = prior tau = np.random.gamma(shape=alpha, scale=(1.0 / beta)) var = (1.0 / (lambda0 * tau)) mean = np.random.normal(loc=mu, scale=np.sqrt(var)) return (mean, tau)
class MLP4(nn.Module): def __init__(self, nin, nout, nh): super().__init__() self.net = nn.Sequential(nn.Linear(nin, nh), nn.LeakyReLU(0.2), nn.Linear(nh, nh), nn.LeakyReLU(0.2), nn.Linear(nh, nh), nn.LeakyReLU(0.2), nn.Linear(nh, nout)) def forward(self, x): return self.net(x)
class BaseLoss(nn.Module): def __init__(self): super(BaseLoss, self).__init__() def forward(self, preds, targets, weight=None): if isinstance(preds, list): N = len(preds) if (weight is None): weight = preds[0].new_ones(1) errs = [self._forward(...
def skip(app, what, name, obj, would_skip, options): if (name == '__init__'): return False return would_skip
class TransformerDecoderLayer(Module): def __init__(self, self_attention, cross_attention, d_model, d_ff=None, dropout=0.1, activation='relu', event_dispatcher=''): super(TransformerDecoderLayer, self).__init__() d_ff = (d_ff or (4 * d_model)) self.self_attention = self_attention sel...
def intervals_to_boundaries(intervals): boundaries = np.zeros(intervals[(- 1)][1], dtype=bool) boundaries[[(i[1] - 1) for i in intervals]] = True return boundaries
def total_incorrect_edges(true_adj, pred_adj, abs_tol=0.5): diff = remove_diag(tf.math.abs((true_adj - pred_adj))) return num_incorrect(diff, abs_tol)
def condense_complex_conv1x1(in_channels, out_channels, groups): return CondenseComplexConv(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, groups=groups)
class Instance(): def __init__(self, gate_type, name): self.gate_type = gate_type self.name = name self.ipins = list() self.opins = list() self.ipin_name_to_net = dict() self.opin_name_to_net = dict() def __str__(self): return ('%s %s %s %s' % (self.gate_t...
class AutoModelForCTC(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def deeplabv3_resnetd101b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs): backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features del backbone[(- 1)] return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name='deep...
def load_superres_from_checkpoint(checkpoint_path, load_weights=True, load_ema_if_available=False): model_path = Path(checkpoint_path) full_model_path = str(model_path.resolve()) assert model_path.exists(), f'checkpoint not found at {full_model_path}' loaded = torch.load(str(model_path), map_location='c...
class DummyFloatProblem(FloatProblem): def __init__(self): super(DummyFloatProblem, self).__init__() def number_of_objectives(self) -> int: return 2 def number_of_constraints(self) -> int: return 0 def evaluate(self, solution: FloatSolution) -> FloatSolution: return solut...
def build_dataset(fields, data_type=None, data_iter=None, data_path=None, total_token_length=500, src_seq_length=100, src_sent_length=100, seq_length_trunc=0, use_filter_pred=True): (examples_iter, num_feats) = TextDataset.make_text_examples_nfeats_tpl(data_iter, data_path, seq_length_trunc) dataset = TextDatas...
class Bottleneck(Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes,...
def sigmoid(tensor: Tensor, temp: float) -> Tensor: exponent = ((- tensor) / temp) exponent = torch.clamp(exponent, min=(- 50), max=50) y = (1.0 / (1.0 + torch.exp(exponent))) return y
def bbox_ohem_orginal(bbox_pred, bbox_target, label): zeros_index = tf.zeros_like(label, dtype=tf.float32) valid_inds = tf.where((label != zeros_index), tf.ones_like(label, dtype=tf.float32), zeros_index) square_error = tf.reduce_sum(tf.square((bbox_pred - bbox_target)), axis=1) keep_num = tf.cast((tf.r...
() ('--data_root', default='../../ultrasound/train') ('--output_path', default='./unet_trained_ultrasound') ('--training_iters', default=20) ('--epochs', default=100) ('--restore', default=False) ('--layers', default=3) ('--features_root', default=32) def launch(data_root, output_path, training_iters, epochs, restore, ...
.script def CCA_CV(representations: List[torch.Tensor]): latent_dimensions = representations[0].shape[1] C = torch.zeros(latent_dimensions, latent_dimensions, device=representations[0].device) V = torch.zeros(latent_dimensions, latent_dimensions, device=representations[0].device) for (i, zi) in enumerat...
class StochasticPolicy(Policy): def distribution(self): def dist_info(self, obs, state_infos):
def _convert_tokens_to_string_with_added_encoders(tokenizer: Union[(PreTrainedTokenizer, PreTrainedTokenizerFast)], output_tokens: List[str], skip_special_tokens: bool, spaces_between_special_tokens: bool) -> str: sub_texts = [] current_sub_text = [] all_special_tokens = set(tokenizer.all_special_tokens) ...
def apu_enabled(configs): if (RuntimeType.apu in get_runtimes(configs)): return True return False
def test_digits_naive_init(): model1 = FeatureBasedSelection(100, 'sqrt') model2 = FeatureBasedSelection(100, 'log') model = MixtureSelection(100, [model1, model2], [1.0, 0.3], optimizer='naive', initial_subset=digits_ranking[:5]) model.fit(X_digits) assert_array_equal(model.ranking[:20], digits_ran...
def _get_lazy_chamfer_dataset(inf_cloud_dataset, cat_id, n_samples): return get_lazy_evaluation_dataset(inf_cloud_dataset, cat_id, n_samples, (lambda c0, c1: (np_metrics.chamfer(c0, c1) / n_samples)))
_bpe('sentencepiece', dataclass=SentencepieceConfig) class SentencepieceBPE(object): def __init__(self, cfg): self.enable_sampling = cfg.sentencepiece_enable_sampling self.alpha = cfg.sentencepiece_alpha sentencepiece_model = file_utils.cached_path(cfg.sentencepiece_model) try: ...
class LGBOptimizerOptuna(object): def __init__(self, objective: str='binary', verbose: bool=False): self.objective = objective self.verbose = verbose self.best: Dict[(str, Any)] = {} def optimize(self, dtrain: lgbDataset, deval: lgbDataset): params: Dict = {'objective': self.obje...
class VecTaskPython(VecTask): def get_state(self): return torch.clamp(self.task.states_buf, (- self.clip_obs), self.clip_obs).to(self.rl_device) def step(self, actions): actions_tensor = torch.clamp(actions, (- self.clip_actions), self.clip_actions) self.task.step(actions_tensor) ...
def temporal_sampling(frames, start_idx, end_idx, num_samples): index = torch.linspace(start_idx, end_idx, num_samples) index = torch.clamp(index, 0, (len(frames) - 1)).long().tolist() frames = [frames[idx] for idx in index] return frames
def get_git_version(): result = subprocess.run(['git', '--version'], stdout=subprocess.PIPE).stdout.decode('utf-8') version = [int(c) for c in result.replace('git version ', '').replace('\n', '').split('.')] return version
def _test(): import torch pretrained = False models = [fishnet99, fishnet150] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != fishnet99) or ...
_grad() def from_importance_weights(log_rhos, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0): with torch.no_grad(): rhos = torch.exp(log_rhos) if (clip_rho_threshold is not None): clipped_rhos = torch.clamp(rhos, max=clip_rho_threshold) ...
_module class GHMC(nn.Module): def __init__(self, bins=10, momentum=0, use_sigmoid=True, loss_weight=1.0): super(GHMC, self).__init__() self.bins = bins self.momentum = momentum self.edges = (torch.arange((bins + 1)).float().cuda() / bins) self.edges[(- 1)] += 1e-06 i...
def checkLabelledGraph(g, *, string: str, vertexString: str, edgeString: str, graphNameInElements: str=None, vIdFull: bool=True): checkGraph(g, string=string, vertexString=vertexString, edgeString=edgeString, graphNameInElements=graphNameInElements, vIdFull=vIdFull) vNull = g.Vertex() fail((lambda : vNull.s...
class PILCutout(object): def __init__(self, min_box: int, max_box: int, pad_value: int=0) -> None: super().__init__() self.min_box = int(min_box) self.max_box = int(max_box) self.pad_value = int(pad_value) def __call__(self, img: Image.Image) -> Image.Image: r_img = img.c...
def dummy_input_layer(): from lasagne.layers.input import InputLayer input_layer = InputLayer((2, 3, 4)) mock = Mock(input_layer) mock.shape = input_layer.shape mock.input_var = input_layer.input_var mock.output_shape = input_layer.output_shape return mock
def evaluate(data_source, batch_size=10): model.eval() model_now = model.module criterion_now = criterion.module if (args.model == 'QRNN'): model_now.reset() total_loss = 0 ntokens = len(corpus.dictionary) hidden = model_now.init_hidden(batch_size) for i in range(0, (data_source....
def plot_model(model, ratio, keep_x_axis, keep_y_axis): (adapted, original) = ([], []) filename = f'{model}-results/{model}_evaluate_ratio={ratio}_run=' (adapted1, original1) = interpret(open((filename + '1.txt')).readlines()) (adapted2, original2) = interpret(open((filename + '2.txt')).readlines()) ...
class SVHNClusteringDatasetInterface(ClusterDatasetInterface): ALLOWED_SPLIT = ['train', 'test'] def __init__(self, data_root=None, split_partitions: List[str]=[], batch_size: int=1, shuffle: bool=False, num_workers: int=1, pin_memory: bool=True) -> None: super().__init__(SVHN, data_root, split_partitio...
def register_embedding(embedding_tensor_name, meta_data_fname, log_dir): config = projector.ProjectorConfig() embedding = config.embeddings.add() embedding.tensor_name = embedding_tensor_name embedding.metadata_path = meta_data_fname projector.visualize_embeddings(log_dir, config)
def set_config(new_config): global config config = new_config import crypten.mpc crypten.mpc.mpc.config = new_config
def sequence_to_text(sequence): result = '' for symbol_id in sequence: s = _id_to_symbol[symbol_id] result += s return result
def make_lm_config(data_dir=None, extra_flags=None, task='language_modeling', arch='transformer_lm_gpt2_tiny'): task_args = [task] if (data_dir is not None): task_args += [data_dir] train_parser = options.get_training_parser() train_args = options.parse_args_and_arch(train_parser, (['--task', *t...
def test_init_shared_network(dataloaders_with_covariates): dataset = dataloaders_with_covariates['train'].dataset net = TemporalFusionTransformer.from_dataset(dataset, share_single_variable_networks=True) net.predict(dataset, fast_dev_run=True)
def create_critic_model(opt, fields): encoder_src = EncoderRNN('GRU', opt.embedding_size, opt.hidden_size, opt.num_layers, opt.dropout, opt.bidirectional) encoder_tgt = EncoderRNN('GRU', opt.embedding_size, opt.hidden_size, opt.num_layers, opt.dropout, opt.bidirectional) model = Critic(encoder_src, encoder_...
def require_pytesseract(test_case): return unittest.skipUnless(is_pytesseract_available(), 'test requires PyTesseract')(test_case)
class InvLrUpdaterHook(LrUpdaterHook): def __init__(self, gamma, power=1.0, **kwargs): self.gamma = gamma self.power = power super(InvLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): progress = (runner.epoch if self.by_epoch else runner.iter) ret...
class Ensemble(nn.ModuleList): def __init__(self): super(Ensemble, self).__init__() def forward(self, x, augment=False): y = [] for module in self: y.append(module(x, augment)[0]) y = torch.cat(y, 1) return (y, None)
def _download_images(label_path: PathOrStr, img_tuples: list, max_workers: int=defaults.cpus, timeout: int=4) -> FilePathList: os.makedirs(Path(label_path), exist_ok=True) parallel(partial(_download_single_image, label_path, timeout=timeout), img_tuples, max_workers=max_workers) return get_image_files(label...
def get_classes(filename='../tiny-imagenet-200/val/val_annotations.txt'): class_dict = {} for line in open(filename): line_array = line.rstrip('\n').split('\t') class_dict[line_array[0]] = line_array[1] return class_dict
class InputWire(DrawElement): def __init__(self, label): super().__init__(label) def fillup_layer(names): longest = max([len(name) for name in names]) inputs_wires = [] for name in names: inputs_wires.append(InputWire(name.rjust(longest))) return inputs_wires
class OHEMSampler(BaseSampler): def __init__(self, num, pos_fraction, context, neg_pos_ub=(- 1), add_gt_as_proposals=True, **kwargs): super(OHEMSampler, self).__init__(num, pos_fraction, neg_pos_ub, add_gt_as_proposals) if (not hasattr(context, 'num_stages')): self.bbox_roi_extractor = c...
class TestValidSubsetsErrors(unittest.TestCase): def _test_case(self, paths, extra_flags): with tempfile.TemporaryDirectory() as data_dir: [write_empty_file(os.path.join(data_dir, f'{p}.bin')) for p in (paths + ['train'])] cfg = make_lm_config(data_dir, extra_flags=extra_flags) ...
def _tokenize(text_path, dictionary): print('Tokenizing {}'.format(text_path)) assert os.path.exists(text_path) ids = [] with open(text_path, 'r', encoding='utf8') as f: for line in f: tokens = (line.split() + ['<eos>']) for token in tokens: ids.append(dic...
class ExternalProcess(object): _ACCESS = 1 _CALL = 2 _RESULT = 3 _EXCEPTION = 4 _CLOSE = 5 def __init__(self, constructor): (self._conn, conn) = multiprocessing.Pipe() self._process = multiprocessing.Process(target=self._worker, args=(constructor, conn)) atexit.register(s...
def default_flist_reader(flist): imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): impath = line.strip() imlist.append(impath) return imlist
def resnet_ole18(pretrained=False, **kwargs): model = Resnet_Ole(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet_ole18'])) return model