code
stringlengths
17
6.64M
def main(): f = open('amazon_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' train_amazon_neg_path = (data_path + '/amazo...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(genmodel.state_dict(), 'models/gen_model_{}'.format(iter))
def main(): f = open('amazon_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' train_amazon_neg_path = (data_path + '/amazo...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(dismodel.state_dict(), 'models/cls_model_{}'.format(iter))
def main(): f = open('amazon_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' train_amazon_neg_path = (data_path + '/amazo...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(genmodel.state_dict(), 'models/gen_model_{}'.format(iter))
def main(): f = open('gpt_yelp_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' train_yelp_neg_path = (data_path + '/yelp/...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(genmodel.state_dict(), 'models/gen_model_{}'.format(iter))
def main(): f = open('../gpt_yelp_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' yelp_neg_path = (data_path + '/yelp/sen...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(dismodel.state_dict(), 'models/cls_model_{}'.format(iter))
def main(): f = open('../gpt_yelp_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' yelp_neg_path = (data_path + '/yelp/sen...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(dismodel.state_dict(), 'models/cls_model_{}'.format(iter))
def main(): f = open('gpt_yelp_vocab.json') token2num = json.load(f) num2token = {} for (key, value) in token2num.items(): num2token[value] = key f.close() data_path = '/DATA/joosung/sentiment_data/Sentiment-and-Style-Transfer-master/data' train_yelp_neg_path = (data_path + '/yelp/...
def save_model(iter): if (not os.path.exists('models/')): os.makedirs('models/') torch.save(genmodel.state_dict(), 'models/gen_model_{}'.format(iter))
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...
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 setup(opt): if (opt.caption_model == 'fc'): model = FCModel(opt) if (opt.caption_model == 'show_tell'): model = ShowTellModel(opt) elif (opt.caption_model == 'att2in'): model = Att2inModel(opt) elif (opt.caption_model == 'att2in2'): model = Att2in2Model(opt) eli...
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 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_length = para...
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 precook(s, n=4, out=False): '\n Takes a string as input and returns an object that can be given to\n either cook_refs or cook_test. This is optional: cook_refs and cook_test\n can take string arguments as well.\n :param s: string : sentence to be converted into ngrams\n :param n: int : number of ngram...
def cook_refs(refs, n=4): 'Takes a list of reference sentences for a single segment\n and returns an object that encapsulates everything that BLEU\n needs to know about them.\n :param refs: list of string : reference sentences for some image\n :param n: int : number of ngrams for which (ngram) represe...
def create_crefs(refs): crefs = [] for ref in refs: crefs.append(cook_refs(ref)) return crefs
def compute_doc_freq(crefs): '\n Compute term frequency for reference data.\n This will be used to compute idf (inverse document frequency later)\n The term frequency is stored in the object\n :return: None\n ' document_frequency = defaultdict(float) for refs in crefs: for ngram in set([ngram...
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')) itow = json.load(open(params['dict_json'], 'r'))['ix_to_word'] wtoi = {w: i for (i, w) in itow.items()} imgs = imgs['images'] (ngram_words, ngram_idxs, ref_len) = build_dict(imgs, wtoi, params) cPickle.dump({'document_frequenc...
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 Emory_loader(Dataset): def __init__(self, txt_file, dataclass): self.dialogs = [] f = open(txt_file, 'r') dataset = f.readlines() f.close() 'sentiment' pos = ['Joyful', 'Peaceful', 'Powerful'] neg = ['Mad', 'Sad', 'Scared'] neu = ['Neutral'] ...
class IEMOCAP_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 = [] pos = ['ang', 'e...
class DD_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 = [] self.emoSet = set() ...
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...