code
stringlengths
17
6.64M
def collate_fn(batch): res = defaultdict(list) for d in batch: for (k, v) in d.items(): res[k].append(v) res['label'] = torch.stack(res['label']) return res
def collate_fn_enrico(batch): res = defaultdict(list) for d in batch: for (k, v) in d.items(): res[k].append(v) res['label'] = torch.tensor(res['label'], dtype=torch.long) return res
class EnricoImageDataset(torch.utils.data.Dataset): def __init__(self, id_list_path, csv='../../metadata/screenclassification/design_topics.csv', class_map_file='../../metadata/screenclassification/class_map_enrico.json', img_folder=(os.environ['SM_CHANNEL_TRAINING'] if ('SM_CHANNEL_TRAINING' in os.environ) else...
class CombinedImageDataset(torch.utils.data.IterableDataset): def __init__(self, ds_list, prob_list): super(CombinedImageDataset, self).__init__() self.ds_list = ds_list self.prob_list = prob_list def __iter__(self): while True: dsi = choices(list(range(len(self.d...
class SilverMultilabelImageDataset(torch.utils.data.Dataset): def __init__(self, id_list_path=None, silver_id_list_path_ignores=None, K=150, P=1, csv='../../metadata/screenclassification/silver_webui-multi_topic.csv', img_folder=(os.environ['SM_CHANNEL_TRAINING'] if ('SM_CHANNEL_TRAINING' in os.environ) else '.....
class SilverDataModule(pl.LightningDataModule): def __init__(self, batch_size=16, num_workers=0, silver_id_list_path=None, silver_id_list_path_ignores=None, ra_num_ops=2, ra_magnitude=9, P=1, K=150, silver_csv='../../metadata/screenclassification/silver_webui-multi_topic.csv', img_folder='../../downloads/ds'): ...
class EnricoDataModule(pl.LightningDataModule): def __init__(self, batch_size=16, num_workers=4, img_size=128, ra_num_ops=(- 1), ra_magnitude=(- 1)): super(EnricoDataModule, self).__init__() self.batch_size = batch_size self.num_workers = num_workers self.train_dataset = EnricoIma...
class UIScreenClassifier(pl.LightningModule): def __init__(self, num_classes=20, dropout_block=0.0, dropout=0.2, lr=5e-05, soft_labels=True, stochastic_depth_p=0.2, arch='resnet50'): super(UIScreenClassifier, self).__init__() self.save_hyperparameters() if ((arch == 'resnet50') or (arch =...
class UIScreenSegmenter(pl.LightningModule): def __init__(self, num_classes=20): super(UIScreenSegmenter, self).__init__() self.save_hyperparameters() model = models.resnet50(pretrained=False, norm_layer=nn.InstanceNorm2d) model.fc = nn.Linear(model.fc.in_features, num_classes) ...
class StochasticBasicBlock(nn.Module): def __init__(self, m, stochastic_depth_p=0.2, stochastic_depth_mode='row'): super(StochasticBasicBlock, self).__init__() self.m = m self.sd = StochasticDepth(stochastic_depth_p, mode=stochastic_depth_mode) def forward(self, x): identity ...
class StochasticBottleneck(nn.Module): def __init__(self, m, stochastic_depth_p=0.2, stochastic_depth_mode='row'): super(StochasticBottleneck, self).__init__() self.m = m self.sd = StochasticDepth(stochastic_depth_p, mode=stochastic_depth_mode) def forward(self, x): identity ...
class CustomNormAndDropout(nn.Module): def __init__(self, num_features, dropout): super(CustomNormAndDropout, self).__init__() self.norm = nn.InstanceNorm2d(num_features) self.dropout = nn.Dropout2d(dropout) def forward(self, x): x = self.norm(x) x = self.dropout(x) ...
def replace_default_bn_with_custom(model, dropout=0.0): for (child_name, child) in model.named_children(): if isinstance(child, nn.BatchNorm2d): setattr(model, child_name, CustomNormAndDropout(child.num_features, dropout)) else: replace_default_bn_with_custom(child, dropout...
def replace_default_bn_with_in(model): for (child_name, child) in model.named_children(): if isinstance(child, nn.BatchNorm2d): setattr(model, child_name, nn.InstanceNorm2d(child.num_features)) else: replace_default_bn_with_in(child)
def replace_res_blocks_with_stochastic(model, stochastic_depth_p=0.2, stochastic_depth_mode='row'): all_blocks = [] def get_blocks(model, blocks): for (child_name, child) in model.named_children(): if isinstance(child, BasicBlock): blocks.append((child_name, StochasticBasi...
class UIElementDetector(pl.LightningModule): def __init__(self, num_classes=25, min_size=320, max_size=640, use_multi_head=True, lr=0.0001, val_weights=None, test_weights=None, arch='fcos'): super(UIElementDetector, self).__init__() self.save_hyperparameters() if (arch == 'fcos'): ...
def random_viewport_from_full(height, w, h): h1 = int((random.random() * (h - height))) h2 = (h1 + height) viewport = (0, h1, w, h2) return viewport
def random_viewport_pair_from_full(img_full, height_ratio): img_pil = Image.open(img_full).convert('RGB') (w, h) = img_pil.size height = int((w * height_ratio)) viewport1 = random_viewport_from_full(height, w, h) vh1 = viewport1[1] delta = (int((random.random() * (2 * height))) - height) v...
class WebUISimilarityDataset(torch.utils.data.IterableDataset): def __init__(self, split_file='../../downloads/train_split_web350k.json', root_dir='../../downloads/ds', domain_map_file='../../metadata/screensim/domain_map.json', duplicate_map_file='../../metadata/screensim/duplicate_map.json', device_name='iPhon...
class WebUISimilarityDataModule(pl.LightningDataModule): def __init__(self, batch_size=16, num_workers=4, split_file='../../downloads/train_split_web350k.json', root_dir='../../downloads/ds', domain_map_file='../../metadata/screensim/domain_map.json', duplicate_map_file='../../metadata/screensim/duplicate_map.js...
class UIScreenEmbedder(pl.LightningModule): def __init__(self, hidden_size=256, lr=5e-05, margin_pos=0.2, margin_neg=0.5, lambda_dann=1): super(UIScreenEmbedder, self).__init__() self.save_hyperparameters() model = models.resnet18(pretrained=False) replace_default_bn_with_in(model...
def replace_default_bn_with_in(model): for (child_name, child) in model.named_children(): if isinstance(child, nn.BatchNorm2d): setattr(model, child_name, nn.InstanceNorm2d(child.num_features)) else: replace_default_bn_with_in(child)
class DailyDialogParser(): def __init__(self, path, sos, eos, eou): self.path = path self.sos = sos self.eos = eos self.eou = eou def get_dialogs(self): train_dialogs = self.process_file((self.path + 'train.txt')) validation_dialogs = self.process_file((self.p...
class DPCollator(): def __init__(self, pad_token, reply_length=None): self.pad_token = pad_token self.reply_length = reply_length def __call__(self, batch): (contexts, replies) = zip(*batch) padded_contexts = self.pad(contexts) padded_replies = self.pad(replies, self....
class DPCorpus(object): SOS = '<s>' EOS = '</s>' EOU = '</u>' PAD = '<pad>' UNK = '<unk>' def __init__(self, dialog_parser=None, vocabulary_limit=None): if (dialog_parser is None): path = (os.path.dirname(os.path.realpath(__file__)) + '/daily_dialog/') dialog_p...
class DPDataLoader(DataLoader): def __init__(self, dataset, batch_size=64): if (dataset == None): corpus = DPCorpus(vocabulary_limit=5000) dataset = corpus.get_train_dataset(2, 5, 20) collator = dataset.corpus.get_collator(reply_length=20) super().__init__(dataset,...
class DPDataset(Dataset): def __init__(self, corpus, dialogs, context_size=2, min_reply_length=None, max_reply_length=None): self.corpus = corpus self.contexts = [] self.replies = [] for dialog in dialogs: max_start_i = (len(dialog) - context_size) for star...
class Discriminator(nn.Module): def __init__(self, embedding_dim, hidden_dim, vocab_size, max_seq_len, gpu=False, dropout=0.2, device='cpu'): super(Discriminator, self).__init__() self.hidden_dim = hidden_dim self.embedding_dim = embedding_dim self.max_seq_len = max_seq_len ...
def greedy_match(fileone, filetwo, w2v): res1 = greedy_score(fileone, filetwo, w2v) res2 = greedy_score(filetwo, fileone, w2v) res_sum = ((res1 + res2) / 2.0) return (np.mean(res_sum), ((1.96 * np.std(res_sum)) / float(len(res_sum))), np.std(res_sum))
def greedy_score(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() dim = w2v.layer1_size scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = np.z...
def extrema_score(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = [] for tok in tokens1...
def average(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() dim = w2v.layer1_size scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = np.zeros(...
def prepare_discriminator_data(pos_samples, neg_samples, gpu=False): '\n Takes positive (target) samples, negative (generator) samples and prepares inp and target data for discriminator.\n\n Inputs: pos_samples, neg_samples\n - pos_samples: pos_size x seq_len\n - neg_samples: neg_size x seq_le...
def load_data(path='dataset.pickle'): '\n Load data set\n ' if (not os.path.isfile(path)): corpus = DPCorpus(vocabulary_limit=VOCAB_SIZE) train_dataset = corpus.get_train_dataset(min_reply_length=MIN_SEQ_LEN, max_reply_length=MAX_SEQ_LEN) with open(path, 'wb') as handle: ...
class ReplayMemory(): def __init__(self, capacity): self.capacity = capacity self.memory = [] def push(self, transition): if (len(self.memory) == self.capacity): del self.memory[0] self.memory.append(transition) def push_batch(self, transition): if (l...
class Attention(nn.Module): '\n Applies an attention mechanism on the output features from the decoder.\n\n .. math::\n \\begin{array}{ll}\n x = context*output \\\\\n attn = exp(x_i) / sum_j exp(x_j) \\\\\n output = \\tanh(w * (attn * context) + b * output)\n ...
class BaseRNN(nn.Module): "\n Applies a multi-layer RNN to an input sequence.\n Note:\n Do not use this class directly, use one of the sub classes.\n Args:\n vocab_size (int): size of the vocabulary\n max_len (int): maximum allowed length for the sequence to be processed\n hid...
class EncoderRNN(BaseRNN): '\n Applies a multi-layer RNN to an input sequence.\n\n Args:\n vocab_size (int): size of the vocabulary\n max_len (int): a maximum allowed length for the sequence to be processed\n hidden_size (int): the number of features in the hidden state `h`\n inp...
class Seq2seq(nn.Module): ' Standard sequence-to-sequence architecture with configurable encoder\n and decoder.\n\n Args:\n encoder (EncoderRNN): object of EncoderRNN\n decoder (DecoderRNN): object of DecoderRNN\n decode_function (func, optional): function to generate symbols from outpu...
class DailyDialogParser(): def __init__(self, path, sos, eos, eou): self.path = path self.sos = sos self.eos = eos self.eou = eou def get_dialogs(self): train_dialogs = self.process_file((self.path + 'train.txt')) validation_dialogs = self.process_file((self.p...
class DPCollator(): def __init__(self, pad_token, reply_length=None): self.pad_token = pad_token self.reply_length = reply_length def __call__(self, batch): (contexts, replies) = zip(*batch) padded_contexts = self.pad(contexts) padded_replies = self.pad(replies, self....
class DPCorpus(object): SOS = '<s>' EOS = '</s>' EOU = '</u>' PAD = '<pad>' UNK = '<unk>' def __init__(self, dialog_parser=None, vocabulary_limit=None): if (dialog_parser is None): path = (os.path.dirname(os.path.realpath(__file__)) + '/daily_dialog/') dialog_p...
class DPDataLoader(DataLoader): def __init__(self, dataset, batch_size=64): if (dataset == None): corpus = DPCorpus(vocabulary_limit=5000) dataset = corpus.get_train_dataset(2, 5, 20) collator = dataset.corpus.get_collator(reply_length=20) super().__init__(dataset,...
class DPDataset(Dataset): def __init__(self, corpus, dialogs, context_size=2, min_reply_length=None, max_reply_length=None): self.corpus = corpus self.contexts = [] self.replies = [] for dialog in dialogs: max_start_i = (len(dialog) - context_size) for star...
class Discriminator(nn.Module): def __init__(self, embedding_dim, hidden_dim, vocab_size, max_seq_len, gpu=False, dropout=0.2, device='cpu'): super(Discriminator, self).__init__() self.hidden_dim = hidden_dim self.embedding_dim = embedding_dim self.max_seq_len = max_seq_len ...
def greedy_match(fileone, filetwo, w2v): res1 = greedy_score(fileone, filetwo, w2v) res2 = greedy_score(filetwo, fileone, w2v) res_sum = ((res1 + res2) / 2.0) return (np.mean(res_sum), ((1.96 * np.std(res_sum)) / float(len(res_sum))), np.std(res_sum))
def greedy_score(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() dim = w2v.layer1_size scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = np.z...
def extrema_score(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = [] for tok in tokens1...
def average(fileone, filetwo, w2v): f1 = open(fileone, 'r') f2 = open(filetwo, 'r') r1 = f1.readlines() r2 = f2.readlines() dim = w2v.layer1_size scores = [] for i in range(len(r1)): tokens1 = r1[i].strip().split(' ') tokens2 = r2[i].strip().split(' ') X = np.zeros(...
def prepare_discriminator_data(pos_samples, neg_samples, gpu=False): '\n Takes positive (target) samples, negative (generator) samples and prepares inp and target data for discriminator.\n\n Inputs: pos_samples, neg_samples\n - pos_samples: pos_size x seq_len\n - neg_samples: neg_size x seq_le...
def load_data(path='dataset.pickle'): '\n Load data set\n ' if (not os.path.isfile(path)): corpus = DPCorpus(vocabulary_limit=VOCAB_SIZE) train_dataset = corpus.get_train_dataset(min_reply_length=MIN_SEQ_LEN, max_reply_length=MAX_SEQ_LEN) with open(path, 'wb') as handle: ...
class ReplayMemory(): def __init__(self, capacity): self.capacity = capacity self.memory = [] def push(self, transition): if (len(self.memory) == self.capacity): del self.memory[0] self.memory.append(transition) def push_batch(self, transition): if (l...
class Attention(nn.Module): '\n Applies an attention mechanism on the output features from the decoder.\n\n .. math::\n \\begin{array}{ll}\n x = context*output \\\\\n attn = exp(x_i) / sum_j exp(x_j) \\\\\n output = \\tanh(w * (attn * context) + b * output)\n ...
class BaseRNN(nn.Module): "\n Applies a multi-layer RNN to an input sequence.\n Note:\n Do not use this class directly, use one of the sub classes.\n Args:\n vocab_size (int): size of the vocabulary\n max_len (int): maximum allowed length for the sequence to be processed\n hid...
class EncoderRNN(BaseRNN): '\n Applies a multi-layer RNN to an input sequence.\n\n Args:\n vocab_size (int): size of the vocabulary\n max_len (int): a maximum allowed length for the sequence to be processed\n hidden_size (int): the number of features in the hidden state `h`\n inp...
class Seq2seq(nn.Module): ' Standard sequence-to-sequence architecture with configurable encoder\n and decoder.\n\n Args:\n encoder (EncoderRNN): object of EncoderRNN\n decoder (DecoderRNN): object of DecoderRNN\n decode_function (func, optional): function to generate symbols from outpu...
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--work-dir', help='the directory to save the file containing evalua...
def main(): args = parse_args() assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"' if (args.eval and ...
def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--resume-from', help='the checkpoint file to resume from') ...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']...
class BMAML(): def __init__(self, dim_input, dim_output, dim_hidden=32, num_layers=4, num_particles=2, max_test_step=5): self.dim_input = dim_input self.dim_output = dim_output self.dim_hidden = dim_hidden self.num_layers = num_layers self.num_particles = num_particles ...
def train(model, dataset, saver, sess, config_str): experiment_dir = ((FLAGS.logdir + '/') + config_str) train_writer = tf.summary.FileWriter(experiment_dir, sess.graph) print('Done initializing, starting training.') num_iters_per_epoch = int((FLAGS.train_total_num_tasks / FLAGS.num_tasks)) if (no...
def test(model, dataset, sess, inner_lr): eval_valid_loss_list = [] for i in range(int((FLAGS.test_total_num_tasks / FLAGS.num_tasks))): [follow_x, _, valid_x, follow_y, _, valid_y] = dataset.generate_batch(is_training=False, batch_idx=(i * FLAGS.num_tasks), inc_follow=True) feed_in = OrderedD...
def main(): random.seed(FLAGS.seed) np.random.seed(FLAGS.seed) tf.set_random_seed(FLAGS.seed) if (not os.path.exists(FLAGS.logdir)): os.makedirs(FLAGS.logdir) fname_args = [] if FLAGS.finite: fname_args += [('train_total_num_tasks', 'SinusoidFinite')] fname_args += [('t...
class BNN(object): def __init__(self, dim_input, dim_output, dim_hidden, num_layers, is_bnn=True): self.dim_input = dim_input self.dim_output = dim_output self.dim_hidden = dim_hidden self.num_layers = num_layers self.is_bnn = is_bnn def construct_network_weights(self...
class EMAML(): def __init__(self, dim_input, dim_output, dim_hidden=32, num_layers=4, num_particles=2, max_test_step=5): self.dim_input = dim_input self.dim_output = dim_output self.dim_hidden = dim_hidden self.num_layers = num_layers self.num_particles = num_particles ...
def train(model, dataset, saver, sess, config_str): experiment_dir = ((FLAGS.logdir + '/') + config_str) train_writer = tf.summary.FileWriter(experiment_dir, sess.graph) print('Done initializing, starting training.') num_iters_per_epoch = int((FLAGS.train_total_num_tasks / FLAGS.num_tasks)) if (no...
def test(model, dataset, sess, inner_lr): eval_valid_loss_list = [] for i in range(int((FLAGS.test_total_num_tasks / FLAGS.num_tasks))): [train_x, valid_x, train_y, valid_y] = dataset.generate_batch(is_training=False, batch_idx=(i * FLAGS.num_tasks)) feed_in = OrderedDict() feed_in[mod...
def main(): random.seed(FLAGS.seed) np.random.seed(FLAGS.seed) tf.set_random_seed(FLAGS.seed) if (not os.path.exists(FLAGS.logdir)): os.makedirs(FLAGS.logdir) fname_args = [] if FLAGS.finite: fname_args += [('train_total_num_tasks', 'SinusoidFinite')] fname_args += [('t...
def pdist(tensor, metric='euclidean'): assert isinstance(tensor, (tf.Variable, tf.Tensor)), 'tensor_utils.pdist: Input must be a `tensorflow.Tensor` instance.' if (len(tensor.shape.as_list()) != 2): raise ValueError('tensor_utils.pdist: A 2-d tensor must be passed.') if (metric == 'euclidean'): ...
def _is_vector(tensor): return (len(tensor.shape.as_list()) == 1)
def median(tensor): tensor_reshaped = tf.reshape(tensor, [(- 1)]) n_elements = tensor_reshaped.get_shape()[0] sorted_tensor = tf.nn.top_k(tensor_reshaped, n_elements, sorted=True) mid_index = (n_elements // 2) if ((n_elements % 2) == 1): return sorted_tensor.values[mid_index] return ((...
def squareform(tensor): assert isinstance(tensor, tf.Tensor), 'tensor_utils.squareform: Input must be a `tensorflow.Tensor` instance.' tensor_shape = tensor.shape.as_list() n_elements = tensor_shape[0] if _is_vector(tensor): if (n_elements == 0): return tf.zeros((1, 1), dtype=tenso...
def get_images(paths, labels, nb_samples=None, shuffle=True): if (nb_samples is not None): sampler = (lambda x: random.sample(x, nb_samples)) else: sampler = (lambda x: x) images = [(i, os.path.join(path, image)) for (i, path) in zip(labels, paths) for image in sampler(os.listdir(path))] ...
def clip_if_not_none(grad, min_value, max_value): if (grad is None): return grad return tf.clip_by_value(grad, min_value, max_value)
def str2bool(v): if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
def make_logdir(configs, fname_args=[]): this_run_str = (time.strftime('%H%M%S_') + str(socket.gethostname())) if is_git_dir(): this_run_str += ('_git' + git_hash_str()) for str_arg in fname_args: if (str_arg in configs.keys()): this_run_str += ((('_' + str_arg.title().replace(...
def experiment_prefix_str(separator=',', hostname=False, git=True): this_run_str = time.strftime('%y%m%d_%H%M%S') if hostname: this_run_str += str(socket.gethostname()) if (git and is_git_dir()): this_run_str += (separator + str(git_hash_str())) this_run_str = this_run_str.replace('-',...
def experiment_string2(configs, fname_args=[], separator=','): this_run_str = '' for (org_arg_str, short_arg_str) in fname_args: short_arg_str = (org_arg_str.title().replace('_', '') if (short_arg_str is None) else short_arg_str) if (org_arg_str in configs.keys()): this_run_str += ...
def experiment_string(configs, fname_args=[], separator=','): this_run_str = expr_prefix_str(configs) for str_arg in fname_args: if (str_arg in configs.keys()): this_run_str += (((separator + str_arg.title().replace('_', '')) + '=') + str(configs[str_arg])) else: raise ...
def is_git_dir(): from subprocess import call, STDOUT if (call(['git', 'branch'], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0): return False else: return True
def git_hash_str(hash_len=7): import subprocess hash_str = subprocess.check_output(['git', 'rev-parse', 'HEAD']) return str(hash_str[:hash_len])
def multi_collate_fn(batch, samples_per_gpu=1): 'Puts each data field into a tensor/DataContainer with outer dimension\n batch size. This is mainly used in query_support dataloader. The main\n difference with the :func:`collate_fn` in mmcv is it can process\n list[list[DataContainer]].\n\n Extend def...
def build_point_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, **kwargs): 'Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there is only one dataloader for all GPUs.\n\n Args:\n...
class PointGenerator(object): def __init__(self, ann_file): self.ann_file = ann_file self.coco = COCO(ann_file) self.seed = 0 def generate_points(self): save_json = dict() save_json['images'] = self.coco.dataset['images'] save_json['annotations'] = [] ...
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--ceph', action='store_true', help='whether not to evaluate the che...
def main(): args = parse_args() assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"' if (args.eval and ...
def train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None): logger = get_root_logger(log_level=cfg.log_level) dataset = (dataset if isinstance(dataset, (list, tuple)) else [dataset]) if ('imgs_per_gpu' in cfg.data): logger.warning('"imgs_per_gpu" is depre...
def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--resume-from', help='the checkpoint file to resume from') ...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): for (k, v) in args.cfg_options.items(): args.cfg_options[k] = eval(v) cfg.merge_from_dict(args.cfg_options) if cfg.get('custom_imports', None): from mmcv.utils impo...
def parse_args(): parser = argparse.ArgumentParser(description='MMDetection webcam demo') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--device', type=int, default=0, help='CUDA device id') parser.add_arg...
def main(): args = parse_args() model = init_detector(args.config, args.checkpoint, device=torch.device('cuda', args.device)) camera = cv2.VideoCapture(args.camera_id) print('Press "Esc", "q" or "Q" to exit.') while True: (ret_val, img) = camera.read() result = inference_detector(m...
def single_gpu_test(model, data_loader, show=False): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for (i, data) in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=(not show), **data) ...
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False): "Test model with multiple gpus.\n\n This method tests model with multiple gpus and collects the results\n under two different modes: gpu and cpu modes. By setting 'gpu_collect=True'\n it encodes results to gpu tensors and use gpu com...
def collect_results_cpu(result_part, size, tmpdir=None): (rank, world_size) = get_dist_info() if (tmpdir is None): MAX_LEN = 512 dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda') if (rank == 0): tmpdir = tempfile.mkdtemp() tmpdir = torch....
def collect_results_gpu(result_part, size): (rank, world_size) = get_dist_info() part_tensor = torch.tensor(bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda') shape_tensor = torch.tensor(part_tensor.shape, device='cuda') shape_list = [shape_tensor.clone() for _ in range(world_size...
def set_random_seed(seed, deterministic=False): 'Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn....
def parse_losses(losses): log_vars = OrderedDict() for (loss_name, loss_value) in losses.items(): if isinstance(loss_value, torch.Tensor): log_vars[loss_name] = loss_value.mean() elif isinstance(loss_value, list): log_vars[loss_name] = sum((_loss.mean() for _loss in los...
def batch_processor(model, data, train_mode): 'Process a data batch.\n\n This method is required as an argument of Runner, which defines how to\n process a data batch and obtain proper outputs. The first 3 arguments of\n batch_processor are fixed.\n\n Args:\n model (nn.Module): A PyTorch model....
def train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None): logger = get_root_logger(cfg.log_level) dataset = (dataset if isinstance(dataset, (list, tuple)) else [dataset]) data_loaders = [build_dataloader(ds, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, len(...