code stringlengths 17 6.64M |
|---|
def _CalACC(model, dataloader):
model.eval()
correct = 0
label_list = []
pred_list = []
with torch.no_grad():
for (i_batch, data) in enumerate(dataloader):
'Prediction'
(batch_input_tokens, batch_labels) = data
(batch_input_tokens, batch_labels) = (batch... |
def _SaveModel(model, path):
if (not os.path.exists(path)):
os.makedirs(path)
torch.save(model.state_dict(), os.path.join(path, 'model.bin'))
|
def encode_right_truncated(text, tokenizer, max_length=511):
tokenized = tokenizer.tokenize(text)
truncated = tokenized[(- max_length):]
ids = tokenizer.convert_tokens_to_ids(truncated)
return ([tokenizer.cls_token_id] + ids)
|
def padding(ids_list, tokenizer):
max_len = 0
for ids in ids_list:
if (len(ids) > max_len):
max_len = len(ids)
pad_ids = []
for ids in ids_list:
pad_len = (max_len - len(ids))
add_ids = [tokenizer.pad_token_id for _ in range(pad_len)]
pad_ids.append((ids + a... |
def encode_right_truncated_gpt(text, tokenizer, max_length=511):
tokenized = tokenizer.tokenize(text)
truncated = tokenized[(- max_length):]
ids = tokenizer.convert_tokens_to_ids(truncated)
return (ids + [tokenizer.cls_token_id])
|
def padding_gpt(ids_list, tokenizer):
max_len = 0
for ids in ids_list:
if (len(ids) > max_len):
max_len = len(ids)
pad_ids = []
for ids in ids_list:
pad_len = (max_len - len(ids))
add_ids = [tokenizer.pad_token_id for _ in range(pad_len)]
pad_ids.append((add... |
def make_batch_roberta(sessions):
(batch_input, batch_labels) = ([], [])
for session in sessions:
data = session[0]
label_list = session[1]
(utt, emotion, sentiment) = data
batch_input.append(encode_right_truncated(utt.strip(), roberta_tokenizer))
if (len(label_list) > ... |
def make_batch_bert(sessions):
(batch_input, batch_labels) = ([], [])
for session in sessions:
data = session[0]
label_list = session[1]
(utt, emotion, sentiment) = data
batch_input.append(encode_right_truncated(utt.strip(), bert_tokenizer))
if (len(label_list) > 3):
... |
def make_batch_gpt(sessions):
(batch_input, batch_labels) = ([], [])
for session in sessions:
data = session[0]
label_list = session[1]
(utt, emotion, sentiment) = data
batch_input.append(encode_right_truncated_gpt(utt.strip(), gpt_tokenizer, max_length=511))
if (len(la... |
class MELD_loader(Dataset):
def __init__(self, txt_file, dataclass):
self.dialogs = []
f = open(txt_file, 'r')
dataset = f.readlines()
f.close()
temp_speakerList = []
context = []
context_speaker = []
self.speakerNum = []
emodict = {'anger':... |
class MELD_loader(Dataset):
def __init__(self, txt_file, dataclass):
self.dialogs = []
f = open(txt_file, 'r')
dataset = f.readlines()
f.close()
temp_speakerList = []
context = []
context_speaker = []
self.speakerNum = []
emodict = {'anger':... |
def main():
initial = args.initial
model_type = args.pretrained
if ('roberta' in model_type):
make_batch = make_batch_roberta
elif (model_type == 'bert-large-uncased'):
make_batch = make_batch_bert
else:
make_batch = make_batch_gpt
freeze = args.freeze
if freeze:
... |
def _CalACC(model, dataloader):
model.eval()
correct = 0
label_list = []
pred_list = []
with torch.no_grad():
for (i_batch, data) in enumerate(tqdm(dataloader)):
'Prediction'
(batch_input_tokens, batch_labels, batch_speaker_tokens) = data
(batch_input_to... |
def CELoss(pred_outs, labels):
'\n pred_outs: [batch, clsNum]\n labels: [batch]\n '
loss = nn.CrossEntropyLoss()
loss_val = loss(pred_outs, labels)
return loss_val
|
def main():
'Dataset Loading'
batch_size = args.batch
dataset = args.dataset
dataclass = args.cls
sample = args.sample
model_type = args.pretrained
freeze = args.freeze
initial = args.initial
dataType = 'multi'
if (dataset == 'MELD'):
if args.dyadic:
dataTyp... |
def _CalACC(model, dataloader):
model.eval()
correct = 0
label_list = []
pred_list = []
with torch.no_grad():
for (i_batch, data) in enumerate(dataloader):
'Prediction'
(batch_input_tokens, batch_labels, batch_speaker_tokens) = data
(batch_input_tokens, ... |
def _SaveModel(model, path):
if (not os.path.exists(path)):
os.makedirs(path)
torch.save(model.state_dict(), os.path.join(path, 'model.bin'))
|
def encode_right_truncated(text, tokenizer, max_length=511):
tokenized = tokenizer.tokenize(text)
truncated = tokenized[(- max_length):]
ids = tokenizer.convert_tokens_to_ids(truncated)
return ([tokenizer.cls_token_id] + ids)
|
def padding(ids_list, tokenizer):
max_len = 0
for ids in ids_list:
if (len(ids) > max_len):
max_len = len(ids)
pad_ids = []
for ids in ids_list:
pad_len = (max_len - len(ids))
add_ids = [tokenizer.pad_token_id for _ in range(pad_len)]
pad_ids.append((ids + a... |
def encode_right_truncated_gpt(text, tokenizer, max_length=511):
tokenized = tokenizer.tokenize(text)
truncated = tokenized[(- max_length):]
ids = tokenizer.convert_tokens_to_ids(truncated)
return (ids + [tokenizer.cls_token_id])
|
def padding_gpt(ids_list, tokenizer):
max_len = 0
for ids in ids_list:
if (len(ids) > max_len):
max_len = len(ids)
pad_ids = []
for ids in ids_list:
pad_len = (max_len - len(ids))
add_ids = [tokenizer.pad_token_id for _ in range(pad_len)]
pad_ids.append((add... |
def make_batch_roberta(sessions):
(batch_input, batch_labels, batch_speaker_tokens) = ([], [], [])
for session in sessions:
data = session[0]
label_list = session[1]
(context_speaker, context, emotion, sentiment) = data
now_speaker = context_speaker[(- 1)]
speaker_utt_l... |
def make_batch_bert(sessions):
(batch_input, batch_labels, batch_speaker_tokens) = ([], [], [])
for session in sessions:
data = session[0]
label_list = session[1]
(context_speaker, context, emotion, sentiment) = data
now_speaker = context_speaker[(- 1)]
speaker_utt_list... |
def make_batch_gpt(sessions):
(batch_input, batch_labels, batch_speaker_tokens) = ([], [], [])
for session in sessions:
data = session[0]
label_list = session[1]
(context_speaker, context, emotion, sentiment) = data
now_speaker = context_speaker[(- 1)]
speaker_utt_list ... |
class MultiHeadedDotAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1, scale=1, project_k_v=1, use_output_layer=1, do_aoa=0, norm_q=0, dropout_aoa=0.3):
super(MultiHeadedDotAttention, self).__init__()
assert (((d_model * scale) % h) == 0)
self.d_k = ((d_model * scale) // h)... |
class AoA_Refiner_Layer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super(AoA_Refiner_Layer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.use_ff = 0
if (self.feed_forward is not None):
self.use_ff... |
class AoA_Refiner_Core(nn.Module):
def __init__(self, opt):
super(AoA_Refiner_Core, self).__init__()
attn = MultiHeadedDotAttention(opt.num_heads, opt.rnn_size, project_k_v=1, scale=opt.multi_head_scale, do_aoa=opt.refine_aoa, norm_q=0, dropout_aoa=getattr(opt, 'dropout_aoa', 0.3))
layer ... |
class AoA_Decoder_Core(nn.Module):
def __init__(self, opt):
super(AoA_Decoder_Core, self).__init__()
self.drop_prob_lm = opt.drop_prob_lm
self.d_model = opt.rnn_size
self.use_multi_head = opt.use_multi_head
self.multi_head_scale = opt.multi_head_scale
self.use_ctx_... |
class AoAModel(AttModel):
def __init__(self, opt):
super(AoAModel, self).__init__(opt)
self.num_layers = 2
self.use_mean_feats = getattr(opt, 'mean_feats', 1)
if (opt.use_multi_head == 2):
del self.ctx2att
self.ctx2att = nn.Linear(opt.rnn_size, ((2 * opt.mu... |
def setup(opt):
if (opt.caption_model in ['fc', 'show_tell']):
print(('Warning: %s model is mostly deprecated; many new features are not supported.' % opt.caption_model))
if (opt.caption_model == 'fc'):
print('Use newfc instead of fc')
if (opt.caption_model == 'fc'):
model ... |
def repeat_tensors(n, x):
'\n For a tensor of size Bx..., we repeat it n times, and make it Bnx...\n For collections, do nested repeat\n '
if torch.is_tensor(x):
x = x.unsqueeze(1)
x = x.expand((- 1), n, *([(- 1)] * len(x.shape[2:])))
x = x.reshape((x.shape[0] * n), *x.shape[2... |
def split_tensors(n, x):
if torch.is_tensor(x):
assert ((x.shape[0] % n) == 0)
x = x.reshape((x.shape[0] // n), n, *x.shape[1:]).unbind(1)
elif ((type(x) is list) or (type(x) is tuple)):
x = [split_tensors(n, _) for _ in x]
elif (x is None):
x = ([None] * n)
return x
|
class CfgNode(_CfgNode):
'\n Our own extended version of :class:`yacs.config.CfgNode`.\n It contains the following extra features:\n\n 1. The :meth:`merge_from_file` method supports the "_BASE_" key,\n which allows the new CfgNode to inherit all the attributes from the\n base configuration fi... |
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
|
def compute_div_n(caps, n=1):
aggr_div = []
for k in caps:
all_ngrams = set()
lenT = 0.0
for c in caps[k]:
tkns = c.split()
lenT += len(tkns)
ng = find_ngrams(tkns, n)
all_ngrams.update(ng)
aggr_div.append((float(len(all_ngrams)) ... |
def compute_global_div_n(caps, n=1):
aggr_div = []
all_ngrams = set()
lenT = 0.0
for k in caps:
for c in caps[k]:
tkns = c.split()
lenT += len(tkns)
ng = find_ngrams(tkns, n)
all_ngrams.update(ng)
if (n == 1):
aggr_div.append(float(le... |
def pickle_load(f):
' Load a pickle.\n Parameters\n ----------\n f: file-like object\n '
if six.PY3:
return cPickle.load(f, encoding='latin-1')
else:
return cPickle.load(f)
|
def pickle_dump(obj, f):
' Dump a pickle.\n Parameters\n ----------\n obj: pickled object\n f: file-like object\n '
if six.PY3:
return cPickle.dump(obj, f, protocol=2)
else:
return cPickle.dump(obj, f)
|
def serialize_to_tensor(data):
device = torch.device('cpu')
buffer = cPickle.dumps(data)
storage = torch.ByteStorage.from_buffer(buffer)
tensor = torch.ByteTensor(storage).to(device=device)
return tensor
|
def deserialize(tensor):
buffer = tensor.cpu().numpy().tobytes()
return cPickle.loads(buffer)
|
def decode_sequence(ix_to_word, seq):
(N, D) = seq.size()
out = []
for i in range(N):
txt = ''
for j in range(D):
ix = seq[(i, j)]
if (ix > 0):
if (j >= 1):
txt = (txt + ' ')
txt = (txt + ix_to_word[str(ix.item())]... |
def save_checkpoint(opt, model, infos, optimizer, histories=None, append=''):
if (len(append) > 0):
append = ('-' + append)
if (not os.path.isdir(opt.checkpoint_path)):
os.makedirs(opt.checkpoint_path)
checkpoint_path = os.path.join(opt.checkpoint_path, ('model%s.pth' % append))
torch.... |
def set_lr(optimizer, lr):
for group in optimizer.param_groups:
group['lr'] = lr
|
def get_lr(optimizer):
for group in optimizer.param_groups:
return group['lr']
|
def build_optimizer(params, opt):
if (opt.optim == 'rmsprop'):
return optim.RMSprop(params, opt.learning_rate, opt.optim_alpha, opt.optim_epsilon, weight_decay=opt.weight_decay)
elif (opt.optim == 'adagrad'):
return optim.Adagrad(params, opt.learning_rate, weight_decay=opt.weight_decay)
el... |
def penalty_builder(penalty_config):
if (penalty_config == ''):
return (lambda x, y: y)
(pen_type, alpha) = penalty_config.split('_')
alpha = float(alpha)
if (pen_type == 'wu'):
return (lambda x, y: length_wu(x, y, alpha))
if (pen_type == 'avg'):
return (lambda x, y: length... |
def length_wu(length, logprobs, alpha=0.0):
'\n NMT length re-ranking score from\n "Google\'s Neural Machine Translation System" :cite:`wu2016google`.\n '
modifier = (((5 + length) ** alpha) / ((5 + 1) ** alpha))
return (logprobs / modifier)
|
def length_average(length, logprobs, alpha=0.0):
'\n Returns the average probability of tokens in a sequence.\n '
return (logprobs / length)
|
class NoamOpt(torch.optim.Optimizer):
'Optim wrapper that implements rate.'
def __init__(self, model_size, factor, warmup, optimizer):
self.optimizer = optimizer
self._step = 0
self.warmup = warmup
self.factor = factor
self.model_size = model_size
self._rate = ... |
class ReduceLROnPlateau(torch.optim.Optimizer):
'Optim wrapper that implements rate.'
def __init__(self, optimizer, mode='min', factor=0.1, patience=10, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08, verbose=False):
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(optim... |
def get_std_opt(model, optim_func='adam', factor=1, warmup=2000):
optim_func = dict(adam=torch.optim.Adam, adamw=torch.optim.AdamW)[optim_func]
return NoamOpt(model.d_model, factor, warmup, optim_func(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-09))
|
def if_use_feat(caption_model):
if (caption_model in ['show_tell', 'all_img', 'fc', 'newfc']):
(use_att, use_fc) = (False, True)
elif (caption_model == 'language_model'):
(use_att, use_fc) = (False, False)
elif (caption_model in ['updown', 'topdown']):
(use_fc, use_att) = (True, Tr... |
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--input_json', type=str, default='data/coco.json', help='path to the json file containing additional info and vocab')
parser.add_argument('--input_fc_dir', type=str, default='data/cocotalk_fc', help='path to the directory containing ... |
def add_eval_options(parser):
parser.add_argument('--batch_size', type=int, default=0, help='if > 0 then overrule, otherwise load from checkpoint.')
parser.add_argument('--num_images', type=int, default=(- 1), help='how many images to use when periodically evaluating the loss? (-1 = all)')
parser.add_argu... |
def add_diversity_opts(parser):
parser.add_argument('--sample_n', type=int, default=1, help='Diverse sampling')
parser.add_argument('--sample_n_method', type=str, default='sample', help='sample, bs, dbs, gumbel, topk, dgreedy, dsample, dtopk, dtopp')
parser.add_argument('--eval_oracle', type=int, default=... |
def add_eval_sample_opts(parser):
parser.add_argument('--sample_method', type=str, default='greedy', help='greedy; sample; gumbel; top<int>, top<0-1>')
parser.add_argument('--beam_size', type=int, default=1, help='used when sample_method = greedy, indicates number of beams in beam search. Usually 2 or 3 works... |
class ResNet(torchvision.models.resnet.ResNet):
def __init__(self, block, layers, num_classes=1000):
super(ResNet, self).__init__(block, layers, num_classes)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True)
for i in range(2, 5):
getattr(self, ('l... |
def resnet18(pretrained=False):
'Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = ResNet(BasicBlock, [2, 2, 2, 2])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
return model... |
def resnet34(pretrained=False):
'Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = ResNet(BasicBlock, [3, 4, 6, 3])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
return model... |
def resnet50(pretrained=False):
'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = ResNet(Bottleneck, [3, 4, 6, 3])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model... |
def resnet101(pretrained=False):
'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = ResNet(Bottleneck, [3, 4, 23, 3])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
return m... |
def resnet152(pretrained=False):
'Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = ResNet(Bottleneck, [3, 8, 36, 3])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
return m... |
class myResnet(nn.Module):
def __init__(self, resnet):
super(myResnet, self).__init__()
self.resnet = resnet
def forward(self, img, att_size=14):
x = img.unsqueeze(0)
x = self.resnet.conv1(x)
x = self.resnet.bn1(x)
x = self.resnet.relu(x)
x = self.resn... |
def build_vocab(imgs, params):
captions = []
for img in imgs:
for sent in img['sentences']:
captions.append(' '.join(sent['tokens']))
captions = '\n'.join(captions)
all_captions = tempfile.NamedTemporaryFile(delete=False)
all_captions.close()
with open(all_captions.name, 'w... |
def encode_captions(imgs, params, wtoi):
' \n\tencode all captions into one large array, which will be 1-indexed.\n\talso produces label_start_ix and label_end_ix which store 1-indexed \n\tand inclusive (Lua-style) pointers to the first and last caption for\n\teach image in the dataset.\n\t'
max_length = para... |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
imgs = imgs['images']
seed(123)
(vocab, bpe) = build_vocab(imgs, params)
itow = {(i + 1): w for (i, w) in enumerate(vocab)}
wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)}
(L, label_start_ix, label_end_ix, label_length)... |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
imgs = imgs['images']
N = len(imgs)
if (params['fc_input_dir'] is not None):
print('processing fc')
with h5py.File(params['fc_output']) as file_fc:
for (i, img) in enumerate(tqdm(imgs)):
npy... |
class FolderLMDB(data.Dataset):
def __init__(self, db_path, fn_list=None):
self.db_path = db_path
self.lmdb = lmdbdict(db_path, unsafe=True)
self.lmdb._key_dumps = DUMPS_FUNC['ascii']
self.lmdb._value_loads = LOADS_FUNC['identity']
if (fn_list is not None):
sel... |
def make_dataset(dir, extension):
images = []
dir = os.path.expanduser(dir)
for (root, _, fnames) in sorted(os.walk(dir)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, [extension]):
path = os.path.join(root, fname)
images.append(path... |
def raw_reader(path):
with open(path, 'rb') as f:
bin_data = f.read()
return bin_data
|
def raw_npz_reader(path):
with open(path, 'rb') as f:
bin_data = f.read()
try:
npz_data = np.load(six.BytesIO(bin_data))['feat']
except Exception as e:
print(path)
npz_data = None
print(e)
return (bin_data, npz_data)
|
def raw_npy_reader(path):
with open(path, 'rb') as f:
bin_data = f.read()
try:
npy_data = np.load(six.BytesIO(bin_data))
except Exception as e:
print(path)
npy_data = None
print(e)
return (bin_data, npy_data)
|
class Folder(data.Dataset):
def __init__(self, root, loader, extension, fn_list=None):
super(Folder, self).__init__()
self.root = root
if fn_list:
samples = [os.path.join(root, (str(_) + extension)) for _ in fn_list]
else:
samples = make_dataset(self.root, ... |
def folder2lmdb(dpath, fn_list, write_frequency=5000):
directory = osp.expanduser(osp.join(dpath))
print(('Loading dataset from %s' % directory))
if (args.extension == '.npz'):
dataset = Folder(directory, loader=raw_npz_reader, extension='.npz', fn_list=fn_list)
else:
dataset = Folder(... |
def parse_args():
'\n Parse input arguments\n '
parser = argparse.ArgumentParser(description='Generate bbox output from a Fast R-CNN network')
parser.add_argument('--input_json', default='./data/dataset_coco.json', type=str)
parser.add_argument('--output_file', default='.dump_cache.tsv', type=st... |
def build_vocab(imgs, params):
count_thr = params['word_count_threshold']
counts = {}
for img in imgs:
for sent in img['sentences']:
for w in sent['tokens']:
counts[w] = (counts.get(w, 0) + 1)
cw = sorted([(count, w) for (w, count) in counts.items()], reverse=True)
... |
def encode_captions(imgs, params, wtoi):
' \n encode all captions into one large array, which will be 1-indexed.\n also produces label_start_ix and label_end_ix which store 1-indexed \n and inclusive (Lua-style) pointers to the first and last caption for\n each image in the dataset.\n '
max_len... |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
imgs = imgs['images']
seed(123)
vocab = build_vocab(imgs, params)
itow = {(i + 1): w for (i, w) in enumerate(vocab)}
wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)}
(L, label_start_ix, label_end_ix, label_length) = enco... |
def get_doc_freq(refs, params):
tmp = CiderScorer(df_mode='corpus')
for ref in refs:
tmp.cook_append(None, ref)
tmp.compute_doc_freq()
return (tmp.document_frequency, len(tmp.crefs))
|
def build_dict(imgs, wtoi, params):
wtoi['<eos>'] = 0
count_imgs = 0
refs_words = []
refs_idxs = []
for img in imgs:
if ((params['split'] == img['split']) or ((params['split'] == 'train') and (img['split'] == 'restval')) or (params['split'] == 'all')):
ref_words = []
... |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
dict_json = json.load(open(params['dict_json'], 'r'))
itow = dict_json['ix_to_word']
wtoi = {w: i for (i, w) in itow.items()}
if ('bpe' in dict_json):
import tempfile
import codecs
codes_f = tempfile.NamedT... |
def main(params):
imgs = json.load(open(params['input_json'][0], 'r'))['images']
out = {'info': {'description': 'This is stable 1.0 version of the 2014 MS COCO dataset.', 'url': 'http://mscoco.org', 'version': '1.0', 'year': 2014, 'contributor': 'Microsoft COCO group', 'date_created': '2015-01-27 09:11:52.357... |
def test_folder():
x = pickle_load(open('log_trans/infos_trans.pkl', 'rb'))
dataset = CaptionDataset(x['opt'])
ds = torch.utils.data.Subset(dataset, dataset.split_ix['train'])
ds[0]
|
def test_lmdb():
x = pickle_load(open('log_trans/infos_trans.pkl', 'rb'))
x['opt'].input_att_dir = 'data/vilbert_att.lmdb'
dataset = CaptionDataset(x['opt'])
ds = torch.utils.data.Subset(dataset, dataset.split_ix['train'])
ds[0]
|
def add_summary_value(writer, key, value, iteration):
if writer:
writer.add_scalar(key, value, iteration)
|
def train(opt):
loader = DataLoader(opt)
opt.vocab_size = loader.vocab_size
opt.seq_length = loader.seq_length
infos = {'iter': 0, 'epoch': 0, 'loader_state_dict': None, 'vocab': loader.get_vocab()}
if ((opt.start_from is not None) and os.path.isfile(os.path.join(opt.start_from, (('infos_' + opt.i... |
def assert_and_infer_cfg(make_immutable=True):
"Call this function in your script after you have finished setting all cfg\n values that are necessary (e.g., merging a config from a file, merging\n command line config options, etc.). By default, this function will also\n mark the global cfg as immutable t... |
def merge_cfg_from_file(cfg_filename):
'Load a yaml config file and merge it into the global config.'
with open(cfg_filename, 'r') as f:
yaml_cfg = AttrDict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
|
def merge_cfg_from_cfg(cfg_other):
'Merge `cfg_other` into the global config.'
_merge_a_into_b(cfg_other, __C)
|
def merge_cfg_from_list(cfg_list):
"Merge config keys, values in a list (e.g., from command line) into the\n global config. For example, `cfg_list = ['TEST.NMS', 0.5]`.\n "
assert ((len(cfg_list) % 2) == 0)
for (full_key, v) in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = full_key.split('... |
def _merge_a_into_b(a, b, stack=None):
'Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n '
assert isinstance(a, AttrDict), 'Argument `a` must be an AttrDict'
assert isinstance(b, AttrDict), 'Argument `b` must be an AttrDict'
... |
def _decode_cfg_value(v):
'Decodes a raw config value (e.g., from a yaml config files or command\n line argument) into a Python object.\n '
if isinstance(v, dict):
return AttrDict(v)
if (not isinstance(v, six.string_types)):
return v
try:
v = literal_eval(v)
except Va... |
def _check_and_coerce_cfg_value_type(value_a, value_b, key, full_key):
'Checks that `value_a`, which is intended to replace `value_b` is of the\n right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n '
type_b = type(value_b)
ty... |
def cityscapes_to_coco(cityscapes_id):
lookup = {0: 0, 1: 2, 2: 3, 3: 1, 4: 7, 5: 8, 6: 4, 7: 6, 8: (- 1)}
return lookup[cityscapes_id]
|
def cityscapes_to_coco_with_rider(cityscapes_id):
lookup = {0: 0, 1: 2, 2: 3, 3: 1, 4: 7, 5: 8, 6: 4, 7: 6, 8: 1}
return lookup[cityscapes_id]
|
def cityscapes_to_coco_without_person_rider(cityscapes_id):
lookup = {0: 0, 1: 2, 2: 3, 3: (- 1), 4: 7, 5: 8, 6: 4, 7: 6, 8: (- 1)}
return lookup[cityscapes_id]
|
def cityscapes_to_coco_all_random(cityscapes_id):
lookup = {0: (- 1), 1: (- 1), 2: (- 1), 3: (- 1), 4: (- 1), 5: (- 1), 6: (- 1), 7: (- 1), 8: (- 1)}
return lookup[cityscapes_id]
|
def parse_args():
parser = argparse.ArgumentParser(description='Convert dataset')
parser.add_argument('--dataset', help='cocostuff, cityscapes', default=None, type=str)
parser.add_argument('--outdir', help='output dir for json files', default=None, type=str)
parser.add_argument('--datadir', help='data... |
def convert_coco_stuff_mat(data_dir, out_dir):
'Convert to png and save json with path. This currently only contains\n the segmentation labels for objects+stuff in cocostuff - if we need to\n combine with other labels from original COCO that will be a TODO.'
sets = ['train', 'val']
categories = []
... |
def getLabelID(self, instID):
if (instID < 1000):
return instID
else:
return int((instID / 1000))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.