code stringlengths 17 6.64M |
|---|
class MarginRankingLoss(nn.Module):
'\n Compute margin ranking loss\n arg input: (batchsize, subspace) and (batchsize, subspace)\n '
def __init__(self, margin=0, measure='cosine', max_violation=False, cost_style='sum', direction='bidir', device=torch.device('cpu')):
'\n :param margin:... |
class MarginRankingLossWithScore(nn.Module):
'\n Compute margin ranking loss\n arg input: (batchsize, subspace) and (batchsize, subspace)\n '
def __init__(self, margin=0, max_violation=False, cost_style='sum', direction='bidir', device=torch.device('cpu')):
'\n\n :param margin:\n ... |
class ImprovedBCELoss(nn.Module):
def __init__(self, lambda_):
super(ImprovedBCELoss, self).__init__()
self.L = lambda_
def forward(self, s, im):
astype = torch.float
im = im.type(astype)
s = s.type(astype)
weight_1 = ((self.L / torch.sum(im, dim=1, keepdim=Tr... |
class MarginLoss(nn.Module):
'\n Compute margin loss\n arg input: (batchsize, subspace) and (batchsize, subspace)\n '
def __init__(self, neg_weight=1, margin=0, measure='cosine', cost_style='sum', device=torch.device('cpu'), pos_weight=300):
'\n\n :param margin:\n :param measu... |
class CrossEntropyLoss(nn.Module):
def __init__(self):
super(CrossEntropyLoss, self).__init__()
def forward(self, s, im, temp=1000):
sim_matrix1 = cosine_sim(s, im)
sim_matrix2 = sim_matrix1.T
loss1 = self.cal_loss(sim_matrix1, temp)
loss2 = self.cal_loss(sim_matrix2,... |
class DualSoftmaxLoss(nn.Module):
def __init__(self):
super(DualSoftmaxLoss, self).__init__()
def forward(self, s, im, temp=1000):
sim_matrix1 = cosine_sim(s, im)
sim_matrix2 = sim_matrix1.T
loss1 = self.cal_loss(sim_matrix1, temp)
loss2 = self.cal_loss(sim_matrix2, t... |
class KlLoss(nn.Module):
def __init__(self, cost_style='sum', direction='bidir', device=torch.device('cpu')):
super().__init__()
self.cost_style = cost_style
self.direction = direction
self.klloss = nn.KLDivLoss(reduction='none')
self.device = device
self.softmax =... |
class Margin2Loss(nn.Module):
'\n Compute margin loss\n arg input: (batchsize, subspace) and (batchsize, subspace)\n '
def __init__(self, bottommargin, uppermargin, bottommargin_t2t, uppermargin_t2t, neg_weight=1, measure='cosine', cost_style='sum', device=torch.device('cpu'), pos_weight=300):
... |
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
|
@lru_cache()
def bytes_to_unicode():
"\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke... |
def get_pairs(word):
'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n '
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
|
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
|
def whitespace_clean(text):
text = re.sub('\\s+', ' ', text)
text = text.strip()
return text
|
class SimpleTokenizer(object):
def __init__(self, bpe_path: str=default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode('utf-8').split('\n')
merges = merges[1:(((49152 - 25... |
class TestSuite(unittest.TestCase):
def test_rootpath(self):
self.assertTrue(os.path.exists(rootpath))
def test_w2v_dir(self):
w2v_dir = os.path.join(rootpath, 'word2vec/flickr/vec500flickr30m')
self.assertTrue(os.path.exists(w2v_dir), ('missing %s' % w2v_dir))
def test_train_da... |
class TextTool():
@staticmethod
def tokenize(input_str, clean=True, language='en', remove_stopword=False):
'\n 进行预处理,返回一个 list\n :param input_str:\n :param clean: 如果 true,去掉不是英文字母和数字的。\n :param language:\n :param remove_stopword: 如果 true,去掉 stopword\n :return... |
def negation_augumentation(input_str):
res = [input_str]
replacelist = [('don t', 'do not'), ('doesn t', 'does not'), ('didn t', 'did not'), ('isn t', 'is not'), ('aren t', 'are not'), ('wasn t', 'was not'), ('weren t', 'were not'), ('won t', 'will not'), ('hasn t', 'has not'), ('haven t', 'have not'), ('can ... |
class Vocabulary(object):
'Simple vocabulary wrapper.'
def __init__(self, encoding):
self.word2idx = {}
self.idx2word = {}
self.encoding = encoding
def add(self, word):
if (word not in self.word2idx):
idx = len(self.word2idx)
self.word2idx[word] = ... |
def load_config(config_path):
module = importlib.import_module(config_path)
return module.config()
|
def load_pretrained_model(pretrained_file_path, rootpath, device):
checkpoint = torch.load(pretrained_file_path, map_location='cpu')
epoch = checkpoint['epoch']
best_perf = checkpoint['best_perf']
config = checkpoint['config']
model_name = config.model_name
if hasattr(config, 't2v_w2v'):
... |
def prepare_config(opt, checkToSkip=True):
np.random.seed(opt.random_seed)
torch.manual_seed(opt.random_seed)
if ('~' in opt.rootpath):
opt.rootpath = opt.rootpath.replace('~', os.path.expanduser('~'))
rootpath = opt.rootpath
trainCollection = opt.trainCollection
if ('trainCollection2'... |
def prepare_model1(opt):
prepared_configs = prepare_config(opt)
config = prepared_configs['config']
model_name = config.model_name
if (opt.pretrained_file_path != 'None'):
pretrained_model = load_pretrained_model(opt.pretrained_file_path, opt.rootpath, device)
config = pretrained_model... |
def main(opt):
prepared_configs = prepare_config(opt)
vis_feat_files = prepared_configs['vis_feat_files']
vis_frame_feat_dicts = prepared_configs['vis_frame_feat_dicts']
frame_id_path_file = prepared_configs['frame_id_path_file']
vis_muti_feat_dicts = prepared_configs['vis_muti_feat_dicts']
ca... |
def get_negationset(capfile):
negationset = set()
with open(capfile, 'r') as reader:
lines = reader.readlines()
for line in lines:
(cap_id, caption) = line.strip().split(' ', 1)
negationset.add(cap_id)
return negationset
|
def main_subset(opt):
prepared_configs = prepare_config(opt)
vis_feat_files = prepared_configs['vis_feat_files']
cap_file_paths = prepared_configs['cap_file_paths']
cap_file_paths_task2 = prepared_configs['cap_file_paths_task2']
opt = prepared_configs['opt']
config = prepared_configs['config']... |
def train(model, train_loader, epoch):
batch_time = util.AverageMeter()
data_time = util.AverageMeter()
model.train()
progbar = Progbar(len(train_loader.dataset))
end = time.time()
for (i, train_data) in enumerate(train_loader):
if (__name__ == '__main__'):
pass
... |
def validate(model, txt_loader, vis_loader, epoch, measure='cosine', metric='mir', negative_val=False, config=None):
(txt2vis_sim, txt_ids, vis_ids) = model.predict(txt_loader, vis_loader, measure=config.measure)
inds = np.argsort(txt2vis_sim, axis=1)
label_matrix = np.zeros(inds.shape)
if negative_va... |
def write_metric(r1, r5, r10, medr, meanr, mir, mAP, epoch, mode='task1'):
sum_recall = ((r1 + r5) + r10)
print(' * Text to video:')
print(' * r_1_5_10: {}'.format([round(r1, 3), round(r5, 3), round(r10, 3)]))
print(' * medr, meanr, mir: {}'.format([round(medr, 3), round(meanr, 3), round(mir, 3)]))
... |
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', only_best=False, logdir=''):
'\n\n :param state:\n :param is_best: 比以前的好,就保存下来\n :param filename:\n :param only_best: 当结束训练时,only_best=True, 删除 checkpoint.pth.tar 文件,把 model_temp_best.pth.tar 文件 复制成 model_best.pth.tar\n :param logdi... |
def parse_result(res):
resp = {}
lines = res.split('\n')
for line in lines:
elems = line.split()
if (('infAP' == elems[0]) and ('all' in line)):
return float(elems[(- 1)])
|
def xml_to_treceval(opt, input_file):
overwrite = opt.overwrite
res_file = (os.path.splitext(input_file)[0] + '.treceval')
if os.path.exists(res_file):
if overwrite:
logger.info(('%s exists. Overwrite' % res_file))
else:
logger.info(('%s exists. Use "--overwrite 1" ... |
def process(opt, input_xml_file):
treceval_file = xml_to_treceval(opt, input_xml_file)
res_file = (input_xml_file + '_perf.txt')
gt_file = os.path.join(opt.rootpath, opt.collection, 'TextData', ('avs.qrels.%s' % opt.edition))
os.chdir(os.path.abspath(os.path.dirname(__file__)))
cmd = ('perl sample... |
def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
from optparse import OptionParser
parser = OptionParser(usage='usage: %prog [options] input_xml_file')
parser.add_option('--rootpath', type=str, default=ROOT_PATH, help=('path to datasets. (default: %s)' % ROOT_PATH))
parser.add_o... |
def read_topics(topics_file):
lines = list(map(str.strip, open(topics_file).readlines()))
qry_list = []
for line in lines:
(tnum, query) = line.split(' ', 1)
qry_list.append((tnum, query))
return qry_list
|
def wrap_topic_result(tNum, elapsedTime, topicResult):
new_res = [('<videoAdhocSearchTopicResult tNum="%s" elapsedTime="%g">' % (tNum, elapsedTime))]
for (i, shot_id) in enumerate(topicResult):
new_res.append(('<item seqNum="%d" shotId="%s" />' % ((i + 1), shot_id)))
new_res.append('</videoAdhocSe... |
def process(options, collection, input_txt_file):
rootpath = options.rootpath
overwrite = options.overwrite
trtype = options.trtype
pclass = options.pclass
pid = options.pid
priority = options.priority
edition = options.edition
desc = options.desc
etime = options.etime
topk = o... |
def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
from optparse import OptionParser
parser = OptionParser(usage='usage: %prog [options] collection input_txt_file')
parser.add_option('--rootpath', type=str, default=ROOT_PATH, help=('path to datasets. (default: %s)' % ROOT_PATH))
p... |
def checkToSkip(filename, overwrite):
if os.path.exists(filename):
(print(('%s exists.' % filename)),)
if overwrite:
print('overwrite')
return 0
else:
print('skip')
return 1
return 0
|
def process(feat_dim, inputTextFiles, resultdir, overwrite):
res_binary_file = os.path.join(resultdir, 'feature.bin')
res_id_file = os.path.join(resultdir, 'id.txt')
if checkToSkip(res_binary_file, overwrite):
return 0
if (os.path.isdir(resultdir) is False):
os.makedirs(resultdir)
... |
def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
parser = OptionParser(usage='usage: %prog [options] nDims inputTextFile isFileList resultDir')
parser.add_option('--overwrite', default=0, type='int', help='overwrite existing file (default=0)')
(options, args) = parser.parse_args(arg... |
def get_lang(data_path):
return 'en'
|
class Txt2Vec(object):
'\n norm: 0 no norm, 1 l_1 norm, 2 l_2 norm\n '
def __init__(self, data_path, norm=0, clean=True):
logger.info((self.__class__.__name__ + ' initializing ...'))
self.data_path = data_path
self.norm = norm
self.lang = get_lang(data_path)
self... |
class BowVec(Txt2Vec):
def __init__(self, data_path, norm=0, clean=True):
super(BowVec, self).__init__(data_path, norm, clean)
self.vocab = pickle.load(open(data_path, 'rb'))
self.ndims = len(self.vocab)
logger.info(('vob size: %d, vec dim: %d' % (len(self.vocab), self.ndims)))
... |
class W2Vec(Txt2Vec):
def __init__(self, data_path, norm=0, clean=True):
super(W2Vec, self).__init__(data_path, norm, clean)
self.w2v = BigFile(data_path)
(vocab_size, self.ndims) = self.w2v.shape()
logger.info(('vob size: %d, vec dim: %d' % (vocab_size, self.ndims)))
def _en... |
class IndexVec(Txt2Vec):
def __init__(self, data_path, clean=True):
super(IndexVec, self).__init__(data_path, 0, clean)
self.vocab = pickle.load(open(data_path, 'rb'))
self.ndims = len(self.vocab)
logger.info(('vob size: %s' % len(self.vocab)))
def _preprocess(self, query):
... |
class BowVecNSW(BowVec):
def __init__(self, data_path, norm=0, clean=True):
super(BowVecNSW, self).__init__(data_path, norm, clean)
if ('_nsw' not in data_path):
logger.error('WARNING: loaded a vocabulary that contains stopwords')
def _preprocess(self, query):
words = Tex... |
class W2VecNSW(W2Vec):
def _preprocess(self, query):
words = TextTool.tokenize(query, clean=self.clean, language=self.lang, remove_stopword=True)
return words
|
def get_txt2vec(name):
assert (name in NAME_TO_T2V)
return NAME_TO_T2V[name]
|
def checkToSkip(filename, overwrite):
'\n 如果文件存在,是否进行覆盖\n :param filename:\n :param overwrite:\n :return:\n '
if os.path.exists(filename):
if overwrite:
logging.info('%s exists. overwrite', filename)
return 0
else:
logging.info('%s exists. qui... |
def makedirs(path):
if (not os.path.exists(path)):
os.makedirs(path)
|
def makedirsforfile(filename):
makedirs(os.path.dirname(filename))
|
def timer(fn):
@wraps(fn)
def compute_time(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = (time.time() - start_time)
print((fn.__name__ + (' execution time: %.3f seconds\n' % elapsed_time)))
return ret
return compute_time
|
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
class LogCollector(object):
'A collection of logging objects that can change from train to val'
def __init__(self):
self.meters = OrderedDict()
def update(self, k, v, n=1):
if (k not in self.meters):
self.meters[k] = AverageMeter()
self.meters[k].update(v, n)
def... |
def train_nn(neurons=(20,), **kwargs):
is_categorical = dataset.get('is_categorical', None)
model = MLPClassifier(hidden_layer_sizes=neurons, **kwargs)
if (is_categorical is not None):
model = Pipeline([('one_hot', OneHotEncoder(categorical_features=is_categorical)), ('mlp', model)])
model.fit... |
def train_surrogate(model, sampling_rate=2.0, **kwargs):
surrogate = rule_surrogate(model.predict, train_x, sampling_rate=sampling_rate, is_continuous=is_continuous, is_categorical=is_categorical, is_integer=is_integer, rlargs={'feature_names': feature_names, 'verbose': 2}, **kwargs)
train_fidelity = surrogat... |
def label2binary(y):
return OneHotEncoder().fit_transform(y.reshape([(- 1), 1])).toarray()
|
def auc_score(y_true, y_pred, average=None):
return roc_auc_score(label2binary(y_true), y_pred, average=average)
|
def accuracy(y_true, y_pred, weights=None):
score = (y_true == y_pred)
return np.average(score, weights=weights)
|
def mse(y_true, y_pred, weights=None):
return np.average(((y_true - y_pred) ** 2), weights=weights)
|
def evaluate_classifier(classifier, x, y, verbose=True):
acc = accuracy(y, classifier.predict(x))
y_proba = classifier.predict_proba(x)
loss = log_loss(y, y_proba)
auc = auc_score(y, y_proba, average='macro')
if verbose:
print('Accuracy: {:.4f}; loss: {:.4f}; auc: {:.4f}'.format(acc, loss,... |
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
|
class HashableList(list):
def __hash__(self):
return hash(json.jsonify(self))
|
def model_name2file(model_name):
return Config.get_path(Config.model_dir(), (model_name + FILE_EXTENSION))
|
class ModelCache():
'A wrapper that '
def __init__(self):
self.cache = {}
self.model2dataset = {}
def init(self, config_path=None):
if (config_path is None):
config_path = Config.config_dir()
config = json2dict(config_path)
if ('models' in config):
... |
def get_model(model_name):
return _cache.get_model(model_name)
|
def available_models():
return list(_cache.model2dataset.keys())
|
def get_model_data(model_name):
return _cache.get_model_data(model_name)
|
def register_model_dataset(model_name, dataset):
_cache.model2dataset[model_name] = dataset
|
def parse_filter(query_json):
if (query_json is None):
return query_json
return HashableList(query_json)
|
@app.route('/static/js/<path:path>')
def send_js(path):
return send_from_directory(safe_join(app.config['STATIC_FOLDER'], 'js'), path)
|
@app.route('/static/css/<path:path>')
def send_css(path):
return send_from_directory(safe_join(app.config['STATIC_FOLDER'], 'css'), path)
|
@app.route('/static/fonts/<path:path>')
def send_fonts(path):
return send_from_directory(safe_join(app.config['STATIC_FOLDER'], 'fonts'), path)
|
@app.route('/')
def index():
return send_from_directory(app.config['FRONT_END_ROOT'], 'index.html')
|
@app.route('/<string:model>', methods=['GET'])
def send_index(model):
if (model == 'service-worker.js'):
return send_from_directory(app.config['FRONT_END_ROOT'], 'service-worker.js')
if (model == 'favicon.ico'):
return send_from_directory(app.config['FRONT_END_ROOT'], 'favicon.ico')
return... |
@app.route('/api/model', methods=['GET'])
def models():
return jsonify(available_models())
|
@app.route('/api/model/<string:model_name>', methods=['GET'])
def model_info(model_name):
model_json = model2json(model_name)
if (model_json is None):
return abort(404)
return model_json
|
@app.route('/api/model_data/<string:model_name>', methods=['GET', 'POST'])
def model_data(model_name):
if (model_name is None):
return abort(404)
data_type = request.args.get('data', 'train')
bins = int(request.args.get('bins', '20'))
if (request.method == 'GET'):
data_json = model_dat... |
@app.route('/api/metric/<string:model_name>', methods=['GET'])
def metric(model_name):
data = request.args.get('data', 'test')
ret_json = model_metric(model_name, data)
if (ret_json is None):
abort(404)
else:
return ret_json
|
@app.route('/api/support/<string:model_name>', methods=['GET', 'POST'])
def support(model_name):
data_type = request.args.get('data', 'train')
support_type = request.args.get('support', 'simple')
if (request.method == 'GET'):
ret_json = get_support(model_name, data_type, support_type)
else:
... |
@app.route('/api/stream/<string:model_name>', methods=['GET', 'POST'])
def stream(model_name):
data_type = request.args.get('data', 'train')
conditional = (request.args.get('conditional', 'true') == 'true')
bins = int(request.args.get('bins', '20'))
if (request.method == 'GET'):
ret_json = get... |
@app.route('/api/query/<string:model_name>', methods=['POST'])
def query(model_name):
if (model_name is None):
abort(404)
data_type = request.args.get('data', 'train')
start = int(request.args.get('start', '0'))
end = int(request.args.get('end', '100'))
query_json = request.get_json()
... |
@app.route('/api/predict', methods=['POST'])
def predict():
name = request.args.get('name')
data = request.args.get('data')
if (name is None):
abort(404)
else:
return get_model(name).predict(data)
|
def get_path(path, filename=None, absolute=False):
'\n A helper function that get the real/abs path of a file on disk, with the project dir as the base dir.\n Note: there is no checking on the illegality of the args!\n :param path: a relative path to ROOT_DIR, optional file_name to use\n :param filena... |
def write2file(s_io, filename=None, mode='w', encoding=None):
'\n This is a wrapper function for writing files to disks,\n it will automatically check for dir existence and create dir or file if needed\n :param s_io: a io.StringIO instance or a str\n :param filename: the path of the file to write to\n... |
def obj2pkl(obj, filename=None, *args, **kwargs):
if (filename is not None):
before_save(filename)
with open(filename, 'wb') as f:
return pickle.dump(obj, f, *args, **kwargs)
return pickle.dumps(obj, **kwargs)
|
def pkl2obj(filename=None):
assert_file_exists(filename)
with open(filename, 'rb') as f:
return pickle.load(f)
|
def dict2json(obj, filename=None, *args, **kwargs):
if (filename is not None):
before_save(filename)
with open(filename, 'w') as f:
return json.dump(obj, f, *args, **kwargs)
return json.dumps(obj, **kwargs)
|
def json2dict(filename, *args, **kwargs):
assert_file_exists(filename)
with open(filename, 'r') as f:
return json.load(f, *args, **kwargs)
|
def df2csv(df, filename, **kwargs):
if (not isinstance(df, pd.DataFrame)):
df = pd.DataFrame(df)
return df.to_csv(filename, index=False, **kwargs)
|
def csv2df(filename):
assert_file_exists(filename)
return pd.read_csv(filename)
|
def array2csv(array, filename, **kwargs):
df = pd.DataFrame(array)
return df.to_csv(filename, index=False, **kwargs)
|
def csv2array(filename):
assert_file_exists(filename)
return pd.read_csv(filename).as_matrix()
|
def array2npy(array: np.ndarray, filename, *args, **kwargs):
return np.save(filename, array, *args, **kwargs)
|
def npy2array(filename, *args, **kwargs):
assert_file_exists(filename)
return np.load(filename, *args, **kwargs)
|
def lists2csv(list_of_list, file_path, delimiter=',', encoding=None):
with io.StringIO() as s_io:
writer = csv.writer(s_io, delimiter=delimiter)
for ls in list_of_list:
writer.writerow([str(i) for i in ls])
write2file(s_io, file_path, 'w', encoding=encoding)
|
def csv2lists(file_path, delimiter=',', mode='r', encoding=None, skip=0):
assert_file_exists(file_path)
lists = []
with open(file_path, mode, newline='', encoding=encoding) as f:
csv_reader = csv.reader(f, delimiter=delimiter)
for i in range(skip):
next(csv_reader)
for ... |
def text2list(file_path, delimiter='|', mode='r'):
assert_file_exists(file_path)
with open(file_path, mode) as f:
s = f.read()
return s.split(delimiter)
|
def save2text(a_list, file_path, delimiter='|'):
s = delimiter.join([str(e) for e in a_list])
write2file(s, file_path, 'w')
|
def path_exists(file_or_dir):
return os.path.exists(file_or_dir)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.