code
stringlengths
101
5.91M
def ReadFile(): interval = 1000000 truth_list = [] actual_list = [] event_id_list = [] truth_cdf = {} actual_cdf = {} x = [[], []] y = [[], []] source_file = '/home/myc/workspace/MorphStream-Stock/application/src/main/java/benchmark/datagenerator/apps/SHJ/dataset/stock_dataset_v2.csv...
class SCConv(nn.Module): def __init__(self, inplanes, planes, stride, padding, dilation, groups, pooling_r, norm_layer): super(SCConv, self).__init__() self.k2 = nn.Sequential(nn.AvgPool2d(kernel_size=pooling_r, stride=pooling_r), nn.Conv2d(inplanes, planes, kernel_size=3, stride=1, padding=padding,...
_tf class TFDistilBertModelTest(TFModelTesterMixin, unittest.TestCase): all_model_classes = ((TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification) if is_tf_available() else None) test_pruning = True test_torchscript = True test_resize_embed...
def get_config(): parser = ArgumentParser() parser = common_config(parser) parser.add_argument('--lr', type=float, default=0.001, help='Learning rate') parser.add_argument('--weight_decay', type=float, default=0, help='Weight decay') parser.add_argument('--max_steps', type=int, default=10000, help='...
def test_fails_on_dim_mismatch(): with pytest.raises(ValueError): GridArchive(solution_dim=10, dims=([10] * 2), ranges=([((- 1), 1)] * 3))
class UniformMutation(Mutation[FloatSolution]): def __init__(self, probability: float, perturbation: float=0.5): super(UniformMutation, self).__init__(probability=probability) self.perturbation = perturbation def execute(self, solution: FloatSolution) -> FloatSolution: Check.that((type(s...
def get_lean_files(paths: List[Path]) -> List[Path]: file_paths = [] for p in paths: for file_name in p.glob('**/*.lean'): file_paths.append(file_name) return file_paths
def Huffman_Encoding(data): symbol_with_probs = Calculate_Probability(data) symbols = symbol_with_probs.keys() probabilities = symbol_with_probs.values() (print('==symbols: ', symbols) if DEBUG else None) (print('==probabilities: ', probabilities) if DEBUG else None) nodes = [] for symbol in...
def test_audio_dataset_archive(mocker): data = AudioDataModule() mocked_archive = mocker.patch(f'{TESTED_MODULE}.data_utils.create_tarfile') data.archive_dataset('test.tar.gz') mocked_archive.assert_called_once_with('test.tar.gz', data.data_dir)
def make_default_index_mapper(special_symbols=SPECIAL_SYMBOLS): mapper = {} if special_symbols: assert (type(special_symbols) == dict), 'Need to provide dict as special symbols mapping.' for (_symbol, _id) in special_symbols.items(): mapper[_symbol] = _id return mapper
def test(args, io): test_loader = DataLoader(ModelNet40(args, partition='test'), batch_size=args.test_batch_size, shuffle=True, drop_last=False) device = torch.device(('cuda' if args.cuda else 'cpu')) model = DGCNN(args).to(device) model = nn.DataParallel(model) model.load_state_dict(torch.load(args...
def _check_matrix_is_sparse(func): (func) def wrapper(*args, **kwargs): if (('accept_sparse' in kwargs) and (not sparse.isspmatrix(args[0]))): raise TypeError('A dense matrix was passed in, but sparsedata is required.') result = func(*args, **kwargs) return result return ...
def get_spurious_datasets(dataset_dir, img_size=224, interpolation=InterpolationMode.BICUBIC, bs=128, num_workers=1): transform = get_imageNet_augmentation(type='no_crop', out_size=img_size, interpolation=interpolation) dataset = SpuriousDataset(dataset_dir, transform) loader = DataLoader(dataset, batch_siz...
def tps(gold, pred, label): (tp, fp, fn) = (0, 0, 0) for (g, p) in zip(gold, pred): if ((g == label) and (g == p)): tp += 1 elif ((p == label) and (g != p)): fp += 1 elif ((g == label) and (g != p)): fn += 1 return (tp, fp, fn)
def sample_hull(hull, domain, isDomainFinite): u = stats.uniform.rvs() if (hull[5][0] >= u): if (hull[3][0] == 0): if isDomainFinite[0]: thissample = (domain[0] + ((u / hull[5][0]) * (hull[4][0] - domain[0]))) else: thissample = else: ...
def require_torch_non_multi_gpu(test_case): if (not is_torch_available()): return unittest.skip('test requires PyTorch')(test_case) import torch return unittest.skipUnless((torch.cuda.device_count() < 2), 'test requires 0 or 1 GPU')(test_case)
def log_deferred(op, log_id, every_n=1, first_n=None): prefix = ':::MLPv0.5.0 [{}]'.format(log_id) if ((first_n is not None) and (first_n == 1)): return tf.compat.v1.Print(op, [tf.timestamp(), op], message=prefix, first_n=1) counter = tf.Variable((tf.zeros(shape=(), dtype=tf.int32) - 1), aggregation...
class BEV_UNet(nn.Module): def __init__(self, n_class, n_height, dilation, bilinear, group_conv, input_batch_norm, dropout, circular_padding, dropblock): super(BEV_UNet, self).__init__() self.inc = inconv(64, 64, dilation, input_batch_norm, circular_padding) self.down1 = down(64, 128, dilati...
def resnet101(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(torch.load(os.path.join(models_dir, model_name['resnet101']))) return model
class TFNoBadWordsLogitsProcessor(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def freeze(module): if (module is None): return None org = [] module.eval() for p in module.parameters(): org.append(p.requires_grad) p.requires_grad_(False) return org
class LearnedPositionalEmbedding(nn.Embedding): def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int): super().__init__(num_embeddings, embedding_dim, padding_idx) self.onnx_trace = False def forward(self, input, incremental_state=None, positions=None): assert ((p...
def train(args, run_opts): arg_string = pprint.pformat(vars(args)) logger.info('Arguments for the experiment\n{0}'.format(arg_string)) shutil.copy('{0}/phones.txt'.format(args.ali_dir), args.dir) num_jobs = common_lib.get_number_of_jobs(args.ali_dir) feat_dim = common_lib.get_feat_dim(args.feat_dir)...
class ParameterModule(nn.Module): def __init__(self, init_value): super().__init__() self.param = torch.nn.Parameter(init_value)
def train(net, trainloader, optimizer, criterion, device): net.train() train_loss = 0 correct = 0 total = 0 train_pred = [] train_true = [] time_cost = datetime.datetime.now() for (batch_idx, (data, label)) in enumerate(trainloader): (data, label) = (data.to(device), label.to(dev...
def weighted_l1_loss(inputs, targets, weights=None): loss = F.l1_loss(inputs, targets, reduce=False) if (weights is not None): loss *= weights.expand_as(loss) loss = torch.mean(loss) return loss
def main(): parser = argparse.ArgumentParser(description='Synchronize files in the Ithemal directory to a running AWS EC2 instance') direction_group = parser.add_mutually_exclusive_group(required=True) direction_group.add_argument('--to', help='Send files to the instance', default=False, action='store_true'...
def suppress_stdout(): with open(os.devnull, 'w') as devnull: old_stdout = sys.stdout sys.stdout = devnull try: (yield) finally: sys.stdout = old_stdout
class ResUNetBN2Cv2(ResUNet2v2): NORM_TYPE = 'BN' CHANNELS = [None, 32, 64, 128, 256] TR_CHANNELS = [None, 64, 64, 64, 128]
def train_poker_approx_best_response_nfsp(br_player, ray_head_address, scenario, general_trainer_config_overrrides, br_policy_config_overrides, get_stopping_condition, avg_policy_specs_for_players: Dict[(int, StrategySpec)], results_dir: str, trainer_class_override=None, br_policy_class_override=None, print_train_resul...
class AlternateCorrBlock(): def __init__(self, fmap1, fmap2, num_levels=4, radius=4): self.num_levels = num_levels self.radius = radius self.pyramid = [(fmap1, fmap2)] for i in range(self.num_levels): fmap2 = F.avg_pool2d(fmap2, 2, stride=2) self.pyramid.appen...
def create_transform(input_size, is_training=False, use_prefetcher=False, color_jitter=0.4, auto_augment=None, interpolation='bilinear', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, re_prob=0.0, re_mode='const', re_count=1, re_num_splits=0, crop_pct=None, tf_preprocessing=False, separate=False, less_aggressive...
def ResNet18(input_shape=None, input_tensor=None, weights=None, classes=1000, stride_size=2, init_filters=64, include_top=False, repetitions=(2, 2, 2, 2), **kwargs): return ResNet(MODELS_PARAMS['resnet18'], input_shape=input_shape, input_tensor=input_tensor, include_top=include_top, classes=classes, stride_size=str...
def train(config_path, device): config = parse_config(config_path) prepare_seed(seed=config['train'].get('seed', 777)) data_config = config['data'] if (data_config['title'].lower() == 'mnist'): (train_loader, test_loader, model) = prepare_mnist(config) else: (train_loader, test_loade...
def predict_by_split(): args.batch_size = max(args.batch_size, (torch.cuda.device_count() * 1024)) assert os.path.exists(args.valid_path) assert os.path.exists(args.train_path) assert os.path.exists(args.eval_model_path) predictor = BertPredictor() predictor.load(ckt_path=args.eval_model_path, u...
def get_next_double_solution(idx, vrblvl=0): if (vrblvl > 0): print('in get_next_double_solution, idx :', idx) phc = get_phcfun() aaa = pointer(c_int32(idx)) bbb = pointer(c_int32(0)) ccc = pointer(c_double(0.0)) vrb = c_int32(vrblvl) if (vrblvl > 0): print('-> get_next_doubl...
def main(): import sys if (len(sys.argv) != 3): print('Usage: python test_read_write_dense.py path/to/dense/input.bin path/to/dense/output.bin') return print(('Checking consistency of reading and writing dense arrays ' + '(depth maps / normal maps) ...')) path_to_dense_input = sys.argv[1...
def main(): parser = argparse.ArgumentParser(description='PyTorch Segmentation Model Training') args = parser_params.add_parser_params(parser) print(args) torch.manual_seed(args.seed) trainer = Trainer(args) start_time = time.time() trainer.validation() total_time = (time.time() - start_...
def prune_state_dict(state_dict, model_cfg: Optional[DictConfig]): arch = None if (model_cfg is not None): arch = (model_cfg._name if isinstance(model_cfg, DictConfig) else getattr(model_cfg, 'arch', None)) if ((not model_cfg) or (arch is None) or (arch == 'ptt_transformer')): return state_d...
def parse_stories(lines, only_supporting=False): data = [] story = [] for line in lines: line = str.lower(line) (nid, line) = line.split(' ', 1) nid = int(nid) if (nid == 1): story = [] if ('\t' in line): (q, a, supporting) = line.split('\t') ...
class Attention_block(nn.Module): def __init__(self, F_g, F_l, F_int): super(Attention_block, self).__init__() self.W_g = nn.Sequential(nn.Conv2d(F_g, F_int, kernel_size=1, stride=1, padding=0, bias=True), nn.BatchNorm2d(F_int)) self.W_x = nn.Sequential(nn.Conv2d(F_l, F_int, kernel_size=1, s...
def get_atom_map_nums(rxn_str) -> typing.Set[int]: mol = Chem.MolFromSmiles(rxn_str) return set([a.GetPropsAsDict()['molAtomMapNumber'] for a in mol.GetAtoms()])
.parametrize('gpu2gpu', [False, True]) def test_env(gpu2gpu): import habitat_sim if (gpu2gpu and (not habitat_sim.cuda_enabled)): pytest.skip('GPU-GPU requires CUDA') config = get_config(CFG_TEST) if (not os.path.exists(config.SIMULATOR.SCENE)): pytest.skip('Please download Habitat test ...
def resnet1202_svhn(num_classes=10, **kwargs): return get_resnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name='resnet1202_svhn', **kwargs)
def iou_x1y1x2y2(bbox1, bbox2): from shapely.geometry import Polygon bbox1_a = [[bbox1[0], bbox1[1]], [bbox1[2], bbox1[1]], [bbox1[2], bbox1[3]], [bbox1[0], bbox1[3]]] bbox2_a = [[bbox2[0], bbox2[1]], [bbox2[2], bbox2[1]], [bbox2[2], bbox2[3]], [bbox2[0], bbox2[3]]] poly_1 = Polygon(bbox1_a) poly_2 ...
class FMRegression(FactorizationMachine, RegressorMixin): def __init__(self, n_iter=100, init_stdev=0.1, rank=8, random_state=123, l2_reg_w=0.1, l2_reg_V=0.1, l2_reg=0): super(FMRegression, self).__init__(n_iter=n_iter, init_stdev=init_stdev, rank=rank, random_state=random_state) if (l2_reg != 0): ...
.register('ShuffleNetV2') def build_sfv2_backbone(cfg): arch = cfg.MODEL.BACKBONE.ARCH in_channels = cfg.MODEL.BACKBONE.IN_PLANES base_channels = cfg.MODEL.BACKBONE.BASE_PLANES round_nearest = cfg.MODEL.COMPRESSION.ROUND_NEAREST (block_layer, stage_channels, stage_blocks, out_channels) = copy.deepco...
class BN_Conv_layer(object): def __init__(self, batch_sz, numpy_rng, tnkern=5, bfilter_sz=5, tfilter_sz=5, bnkern=1, poolsize=(2, 2)): self.filter_shape = (tnkern, bnkern, tfilter_sz, tfilter_sz) self.eta = theano.shared(np.ones((bnkern,), dtype=theano.config.floatX), name='eta') self.beta =...
.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_points_in_polygons(): points = np.array([[300.0, 300.0], [400.0, 400.0], [100.0, 100], [300, 250], [100, 0]]) polygons = np.array([[200.0, 200.0, 400.0, 400.0, 500.0, 200.0, 400.0, 100.0], [400.0, 400.0, 500.0, 500.0, 600.0, 300.0...
def aa_color(letter): if (letter in ['C']): return 'green' elif (letter in ['F', 'W', 'Y']): return [(199 / 256.0), (182 / 256.0), 0.0, 1.0] elif (letter in ['Q', 'N', 'S', 'T']): return 'purple' elif (letter in ['V', 'L', 'I', 'M']): return 'black' elif (letter in ['...
def load_model(path, epoch=None, use_adjacent=False): from nets.attention_model import AttentionModel, student_AttentionModel from nets.pointer_network import PointerNetwork if isinstance(path, list): (encoder_model_filename, decoder_model_filename) = (path[0], path[1]) (encoder_path, decode...
def get(seed=0, fixed_order=False, pc_valid=0.1, nperm=10): data = {} taskcla = [] size = [1, 28, 28] nperm = nperm seeds = np.array(list(range(nperm)), dtype=int) if (not fixed_order): seeds = shuffle(seeds, random_state=seed) if (not os.path.isdir(pmnist_dir)): os.makedirs(...
def emotion_freqs(importtext): tokens = word_tokenize(importtext) fearwords = ['scared', 'afraid', 'avoid', 'not', 'no', 'anxiety', 'road', 'spider', 'snake', 'heights', 'die', 'falling', 'death', 'fast', 'despair', 'agonize', 'bother', 'worry', 'endure', 'sustain', 'tolerate', 'creeps', 'jitters', 'nervous', '...
def parse_list(config, key, dtype=int): if (key in config): if isinstance(config[key], str): config[key] = list(map(dtype, config[key].split(','))) assert (isinstance(config[key], list) and all([isinstance(e, dtype) for e in config[key]])), f'{key} should be a list of values dtype {dtype...
def get_param(l, exclude=set(['top', 'bottom', 'name', 'type'])): if (not hasattr(l, 'ListFields')): if hasattr(l, '__delitem__'): return [get_param(i) for i in l] return l r = dict() for (f, v) in l.ListFields(): if (f.name not in exclude): r[f.name] = get_pa...
(unsafe_hash=True, eq=True, order=True) class VehicleStateDyn(VehicleState): vy: float = 0 dpsi: float = 0 idx = frozendict({'x': 0, 'y': 1, 'psi': 2, 'vx': 3, 'vy': 4, 'dpsi': 5, 'delta': 6}) def __add__(self, other: 'VehicleStateDyn') -> 'VehicleStateDyn': if (type(other) == type(self)): ...
class FlaxDDPMScheduler(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax']) def from_config(cls, *args, **kwargs): requires_backends(cls, ['flax']) def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ['...
class ReplayMemory(Dataset): def __init__(self, capacity): self.capacity = capacity self.memory = list() self.position = 0 def push(self, item): if (len(self.memory) < (self.position + 1)): self.memory.append(item) else: self.memory[self.position] ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, act_layer='leaky_relu', aa_layer=None): super(Bottleneck, self).__init__() self.conv1 = conv2d_iabn(inplanes, planes, kernel_size=1, stride=1, act_layer=act_layer, act_param=0....
class AverageMeter(object): def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE): self.name = name self.fmt = fmt self.summary_type = summary_type self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 d...
('/semcomplete/', methods=['POST']) def semantic_autocomplete(): inputs = json.loads(request.data) scene_description = inputs['abstract_scene_description'] recursion_levels = None if ('recursion_levels' in inputs): recursion_levels = inputs['recursion_levels'] session_token = inputs['session...
class Graphormer(BertPreTrainedModel): def __init__(self, config): super(Graphormer, self).__init__(config) self.config = config self.bert = EncoderBlock(config) self.cls_head = nn.Linear(config.hidden_size, self.config.output_feature_dim) self.residual = nn.Linear(config.img...
def seed_everything(seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed)
class VideoNet(nn.Module): def __init__(self): super(VideoNet, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=3, kernel_size=5) self.relu1 = nn.ReLU() self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=1) self.conv2 = nn.Conv2d(in_channels=3, out_channels...
def download_tweets_for_csv(file_name: str, column: str, api_data: Dict) -> str: def hydrate(row, translation, columns): if (str(row[column]) in translation): row['text'] = translation[row[column]] row = row.drop(column) return row else: ser = pd.Serie...
class SearchEngine(ABC): def run(self): pass def get_best_trials(self, k): pass
class VaswaniRule(extension.Extension): def __init__(self, attr, d, warmup_steps=4000, init=None, target=None, optimizer=None, scale=1.0): self._attr = attr self._d_inv05 = ((d ** (- 0.5)) * scale) self._warmup_steps_inv15 = (warmup_steps ** (- 1.5)) self._init = init self._t...
class AICity20ReCam(BaseImageDataset): dataset_dir = 'AIC20_ReID/' dataset_aug_dir = 'AIC20_ReID_Cropped/' dataset_blend_dir = 'AIC20_ReID_blend/' def __init__(self, root='', verbose=True, **kwargs): super(AICity20ReCam, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir...
def define_G(input_nc, output_nc, ngf, norm='instance', which_model_netG='resnet', use_dropout=False, gpu_ids=[]): netG = None if (len(gpu_ids) > 0): assert torch.cuda.is_available() norm_layer = get_norm_layer(norm_type=norm) netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_laye...
def Trans4PASS_v2(num_classes=19, emb_chans=128): model = Trans4PASS(num_classes, emb_chans, encoder='trans4pass_v2') return model
def get_all_notebook_files(directory='./notebooks/'): ret = [] for (dirpath, subdirs, files) in os.walk(directory): for f in files: ret.append(os.path.join(dirpath, f)) return ret
class HM(autograd.Function): def forward(ctx, inputs, inputs_norm, indexes, features, features_norm, momentum): ctx.features = features ctx.features_norm = features_norm ctx.momentum = momentum ctx.save_for_backward(inputs, indexes) outputs = inputs_norm.mm(ctx.features_norm....
def load_dataset(root_dir, redux, params, shuffled=False, single=False): noise = (params.noise_type, params.noise_param) if (params.noise_type == 'mc'): dataset = MonteCarloDataset(root_dir, redux, params.crop_size, clean_targets=params.clean_targets) else: dataset = NoisyDataset(root_dir, r...
class AutoColBERTModel(): def from_pretrained(cls, model_path: str, config=None): if (config is None): config = AutoConfig.from_pretrained(model_path) if (config.model_type == 'bert'): model = ColBERT.from_pretrained(model_path, config=config) else: raise ...
class SpeechEncoderDecoderModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def load_requirements(path_dir: str=PATH_ROOT, comment_char: str='#') -> List: with open(os.path.join(path_dir, 'core_requirements.txt'), 'r') as file: lines = [ln.strip() for ln in file.readlines()] reqs = [] for ln in lines: if (comment_char in ln): ln = ln[:ln.index(comment_ch...
def hard_update(target, source): for (target_param, param) in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data)
def build_next_utterance(src, trg): global DG for (head1, _) in src.items(): for (head2, _) in trg.items(): create_edge(head1, head2, 'next_utterance')
class UpsamplingBlock(nn.Module): def __init__(self, input_nc, output_nc, kernel, stride, pad, dil): super(UpsamplingBlock, self).__init__() conv = nn.Conv2d biup = nn.UpsamplingBilinear2d block = nn.Sequential() block.add_module('conv_1', conv(input_nc, output_nc, kernel, st...
class Bleu(): def __init__(self, n=4): self._n = n self._hypo_for_image = {} self.ref_for_image = {} def compute_score(self, gts, res): assert (gts.keys() == res.keys()) imgIds = gts.keys() bleu_scorer = BleuScorer(n=self._n) for id in imgIds: ...
def clean_html(string: str): left_mark = '&lt;' right_mark = '&gt;' while True: next_left_start = string.find(left_mark) if (next_left_start == (- 1)): break next_right_start = string.find(right_mark, next_left_start) if (next_right_start == (- 1)): pr...
class CovarianceHeatmapDisplay(): def __init__(self, train_covariances, test_covariances): self.train_covariances = train_covariances self.test_covariances = test_covariances def _validate_plot_params(self): check_seaborn_support('CorrelationHeatmapDisplay') def from_estimator(cls, m...
def createAndConnectResetInitChannels(self, board, resetInitSnips): resetInitChannels = [] for i in range(self.numChipsUsed): initResetChannel = board.createChannel(bytes(('initreset' + str(i)), 'utf-8'), 'int', 3) initResetChannel.connect(None, resetInitSnips[i]) resetInitChannels.appen...
def do_training(hypes): modules = utils.load_modules_from_hypes(hypes) with tf.Session() as sess: with tf.name_scope('Queues'): queue = modules['input'].create_queues(hypes, 'train') regression_weights = tf.placeholder(dtype=tf.float32, shape=(3,)) hypes['solver']['regression...
def schema_integrate(example: Batch) -> Union[(Dict, Any)]: title = example['title'] question = example['question'] context = example['context'] guid = example['id'] classtype = ([''] * len(title)) dataset_name = source = (['squad_v2'] * len(title)) (answers, is_impossible) = ([], []) fo...
def make_builder(out_file, impl): if (impl == 'mmap'): return MMapIndexedDatasetBuilder(out_file) else: return IndexedDatasetBuilder(out_file)
class NetworkFailureReason(object): NODE_FAILURE = 'Node Failure' WAITING_NODE = 'Waiting node'
def build_net(net_name, input_tfs, reuse=False): net = None if (net_name == fc_2layers_256units.NAME): net = fc_2layers_256units.build_net(input_tfs, reuse) elif (net_name == fc_2layers_512units.NAME): net = fc_2layers_512units.build_net(input_tfs, reuse) else: assert False, ('Un...
class Net2(nn.Module): def __init__(self): super(Net2, self).__init__() def forward(self, input): return ((0.5 * input) * (1.0 + torch.tanh(((input * 0.) * (1.0 + ((0.044715 * input) * input))))))
def remove_under_k(seq, k): seq = seq.strip().split(' ') result = [] freqs = [(k, len(list(g))) for (k, g) in groupby(seq)] for (c, f) in freqs: if (f > k): result += [c for _ in range(f)] return (' '.join(result) + '\n')
class HyperSynthesisTransform(nn.Module): def __init__(self, num_filters=192, num_filters_out=192): super(HyperSynthesisTransform, self).__init__() self.conv_h4 = nn.ConvTranspose2d(num_filters, num_filters, 5, stride=2, padding=2, output_padding=1) self.relu_h4 = nn.ReLU() self.conv...
class VarTypeEnum(Enum): INVALID = 0 SEQUENCE = 1 MATRIX = 2 VECTOR = 3 SET = 4 SCALAR = 5 FUNCTION = 6 INDEX = 7
def scan_checkpoint(cp_dir, prefix): pattern = os.path.join(cp_dir, (prefix + '*')) cp_list = glob.glob(pattern) if (len(cp_list) == 0): return '' return sorted(cp_list)[(- 1)]
def iter_caption_to_json(iter_caption, json_file): key_captions = [(key, json.loads(p)) for (key, p) in iter_caption] info = {'info': 'dummy', 'licenses': 'dummy', 'type': 'captions'} info['images'] = [{'file_name': k, 'id': k} for (k, _) in key_captions] n = 0 annotations = [] for (k, cs) in ke...
class ResnetCompleteNetworkTest(tf.test.TestCase): def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope='resnet_v1_small'): block = resnet_v1.resnet_v1_block blocks = [block('block1'...
() def tf(): from sacred.optional import has_tensorflow if has_tensorflow: import tensorflow return tensorflow else: class tensorflow(): class summary(): class FileWriter(): def __init__(self, logdir, graph): sel...
class PlainNet(PlainNet.PlainNet): def __init__(self, argv=None, opt=None, num_classes=None, plainnet_struct=None, no_create=False, no_reslink=None, no_BN=None, use_se=None, dropout=None, **kwargs): if (argv is not None): module_opt = parse_cmd_options(argv) else: module_opt ...
def compute_nas_score(gpu, model, mixup_gamma, resolution, batch_size, repeat, fp16=False): info = {} nas_score_list = [] if (gpu is not None): device = torch.device('cuda:{}'.format(gpu)) else: device = torch.device('cpu') if fp16: dtype = torch.half else: dtype ...
def check_loss(loss): return ((not bool(torch.isnan(loss).item())) and bool((loss >= 0.0).item()) and bool((loss < 1000000.0).item()))
def add_head(head_map, tree, head): tree_repr = (tree.span, tree.label) head_map[tree_repr] = head