code stringlengths 17 6.64M |
|---|
def store_args(method):
'Stores provided method args as instance attributes.\n '
argspec = inspect.getfullargspec(method)
defaults = {}
if (argspec.defaults is not None):
defaults = dict(zip(argspec.args[(- len(argspec.defaults)):], argspec.defaults))
if (argspec.kwonlydefaults is not N... |
def import_function(spec):
'Import a function identified by a string like "pkg.module:fn_name".\n '
(mod_name, fn_name) = spec.split(':')
module = importlib.import_module(mod_name)
fn = getattr(module, fn_name)
return fn
|
def flatten_grads(var_list, grads):
'Flattens a variables and their gradients.\n '
return tf.concat([tf.reshape(grad, [U.numel(v)]) for (v, grad) in zip(var_list, grads)], 0)
|
def nn(input, layers_sizes, reuse=None, flatten=False, name=''):
'Creates a simple neural network\n '
for (i, size) in enumerate(layers_sizes):
activation = (tf.nn.relu if (i < (len(layers_sizes) - 1)) else None)
input = tf.layers.dense(inputs=input, units=size, kernel_initializer=tf.contri... |
def install_mpi_excepthook():
import sys
from mpi4py import MPI
old_hook = sys.excepthook
def new_hook(a, b, c):
old_hook(a, b, c)
sys.stdout.flush()
sys.stderr.flush()
MPI.COMM_WORLD.Abort()
sys.excepthook = new_hook
|
def mpi_fork(n, binding='core'):
'Re-launches the current script with workers\n Returns "parent" for original parent, "child" for MPI children\n '
if (n <= 1):
return 'child'
if (os.getenv('IN_MPI') is None):
env = os.environ.copy()
env.update(MKL_NUM_THREADS='1', OMP_NUM_THR... |
def convert_episode_to_batch_major(episode):
'Converts an episode to have the batch dimension in the major (first)\n dimension.\n '
episode_batch = {}
for key in episode.keys():
val = np.array(episode[key]).copy()
episode_batch[key] = val.swapaxes(0, 1)
return episode_batch
|
def transitions_in_episode_batch(episode_batch):
'Number of transitions in a given episode batch.\n '
shape = episode_batch['u'].shape
return (shape[0] * shape[1])
|
def reshape_for_broadcasting(source, target):
'Reshapes a tensor (source) to have the correct shape and dtype of the target\n before broadcasting it with MPI.\n '
dim = len(target.get_shape())
shape = (([1] * (dim - 1)) + [(- 1)])
return tf.reshape(tf.cast(source, target.dtype), shape)
|
def split_observation_np(env_name, obs):
obs_excludes_goal = np.zeros(0)
obs_achieved_goal = np.zeros(0)
if (env_name in ['FetchPush-v1', 'FetchSlide-v1', 'FetchPickAndPlace-v1']):
assert (obs.shape[(- 1)] == 25), 'Observation dimension changed.'
(grip_pos, object_pos, object_rel_pos, grip... |
def split_observation_tf(env_name, o):
dimo = o.get_shape().as_list()[(- 1)]
if (env_name in ['FetchPush-v1', 'FetchSlide-v1', 'FetchPickAndPlace-v1']):
assert (dimo == 25), 'Observation dimension changed.'
(grip_pos, object_pos, object_rel_pos, gripper_state, object_rot, object_velp, object_v... |
def make_dir(filename):
folder = os.path.dirname(filename)
if (not os.path.exists(folder)):
os.makedirs(folder)
|
def save_video(ims, filename, lib='cv2'):
make_dir(filename)
fps = 30.0
(height, width, _) = ims[0].shape
if (lib == 'cv2'):
import cv2
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(filename, fourcc, fps, (width, height))
elif (lib == 'imageio'):
... |
def dumpJson(dirname, episodes, epoch, rank):
os = []
for episode in episodes:
episode['o'] = episode['o'].tolist()
os.append(episode['o'])
with open((dirname + '/rollout_{0}_{1}.txt'.format(epoch, rank)), 'w') as file:
file.write(json.dumps(os))
|
def loadJson(dirname, epoch, rank):
filename = '/rollout_{0}_{1}.txt'.format(epoch, rank)
with open((dirname + filename), 'r') as file:
os = json.loads(file.read())
return os
|
def save_weight(sess, collection=tf.GraphKeys.GLOBAL_VARIABLES):
return {v.name: sess.run(v) for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=(('ddpg' + '/') + ''))}
|
def load_weight(sess, data, include=[]):
for scope in include:
for v in tf.global_variables():
if ((v.name in data.keys()) and (scope in v.name)):
if (v.shape == data[v.name].shape):
sess.run(v.assign(data[v.name]))
print('load weight: ',... |
class KVWriter(object):
def writekvs(self, kvs):
raise NotImplementedError
|
class SeqWriter(object):
def writeseq(self, seq):
raise NotImplementedError
|
class HumanOutputFormat(KVWriter, SeqWriter):
def __init__(self, filename_or_file):
if isinstance(filename_or_file, str):
self.file = open(filename_or_file, 'wt')
self.own_file = True
else:
assert hasattr(filename_or_file, 'read'), ('expected file or str, got %... |
class JSONOutputFormat(KVWriter):
def __init__(self, filename):
self.file = open(filename, 'wt')
def writekvs(self, kvs):
for (k, v) in sorted(kvs.items()):
if hasattr(v, 'dtype'):
v = v.tolist()
kvs[k] = float(v)
self.file.write((json.dump... |
class CSVOutputFormat(KVWriter):
def __init__(self, filename):
self.file = open(filename, 'w+t')
self.keys = []
self.sep = ','
def writekvs(self, kvs):
extra_keys = (kvs.keys() - self.keys)
if extra_keys:
self.keys.extend(extra_keys)
self.file.... |
class TensorBoardOutputFormat(KVWriter):
"\n Dumps key/value pairs into TensorBoard's numeric format.\n "
def __init__(self, dir):
os.makedirs(dir, exist_ok=True)
self.dir = dir
self.step = 1
prefix = 'events'
path = osp.join(osp.abspath(dir), prefix)
imp... |
def make_output_format(format, ev_dir, log_suffix=''):
os.makedirs(ev_dir, exist_ok=True)
if (format == 'stdout'):
return HumanOutputFormat(sys.stdout)
elif (format == 'log'):
return HumanOutputFormat(osp.join(ev_dir, ('log%s.txt' % log_suffix)))
elif (format == 'json'):
return... |
def logkv(key, val):
'\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n '
Logger.CURRENT.logkv(key, val)
|
def logkv_mean(key, val):
'\n The same as logkv(), but if called many times, values averaged.\n '
Logger.CURRENT.logkv_mean(key, val)
|
def logkvs(d):
'\n Log a dictionary of key-value pairs\n '
for (k, v) in d.items():
logkv(k, v)
|
def dumpkvs():
"\n Write all of the diagnostics from the current iteration\n\n level: int. (see logger.py docs) If the global logger level is higher than\n the level argument here, don't print to stdout.\n "
Logger.CURRENT.dumpkvs()
|
def getkvs():
return Logger.CURRENT.name2val
|
def log(*args, level=INFO):
"\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n "
Logger.CURRENT.log(*args, level=level)
|
def debug(*args):
log(*args, level=DEBUG)
|
def info(*args):
log(*args, level=INFO)
|
def warn(*args):
log(*args, level=WARN)
|
def error(*args):
log(*args, level=ERROR)
|
def set_level(level):
'\n Set logging threshold on current logger.\n '
Logger.CURRENT.set_level(level)
|
def get_dir():
"\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n "
return Logger.CURRENT.get_dir()
|
class ProfileKV():
'\n Usage:\n with logger.ProfileKV("interesting_scope"):\n code\n '
def __init__(self, n):
self.n = ('wait_' + n)
def __enter__(self):
self.t1 = time.time()
def __exit__(self, type, value, traceback):
Logger.CURRENT.name2val[self.n] += (tim... |
def profile(n):
'\n Usage:\n @profile("my_func")\n def my_func(): code\n '
def decorator_with_name(func):
def func_wrapper(*args, **kwargs):
with ProfileKV(n):
return func(*args, **kwargs)
return func_wrapper
return decorator_with_name
|
class Logger(object):
DEFAULT = None
CURRENT = None
def __init__(self, dir, output_formats):
self.name2val = defaultdict(float)
self.name2cnt = defaultdict(int)
self.level = INFO
self.dir = dir
self.output_formats = output_formats
def logkv(self, key, val):
... |
def configure(dir=None, format_strs=None):
if (dir is None):
dir = os.getenv('OPENAI_LOGDIR')
if (dir is None):
dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('openai-%Y-%m-%d-%H-%M-%S-%f'))
assert isinstance(dir, str)
os.makedirs(dir, exist_ok=True)
log_suf... |
def reset():
if (Logger.CURRENT is not Logger.DEFAULT):
Logger.CURRENT.close()
Logger.CURRENT = Logger.DEFAULT
log('Reset logger')
|
class scoped_configure(object):
def __init__(self, dir=None, format_strs=None):
self.dir = dir
self.format_strs = format_strs
self.prevlogger = None
def __enter__(self):
self.prevlogger = Logger.CURRENT
configure(dir=self.dir, format_strs=self.format_strs)
def __... |
def _demo():
info('hi')
debug("shouldn't appear")
set_level(DEBUG)
debug('should appear')
dir = '/tmp/testlogging'
if os.path.exists(dir):
shutil.rmtree(dir)
configure(dir=dir)
logkv('a', 3)
logkv('b', 2.5)
dumpkvs()
logkv('b', (- 2.5))
logkv('a', 5.5)
dumpk... |
def read_json(fname):
import pandas
ds = []
with open(fname, 'rt') as fh:
for line in fh:
ds.append(json.loads(line))
return pandas.DataFrame(ds)
|
def read_csv(fname):
import pandas
return pandas.read_csv(fname, index_col=None, comment='#')
|
def read_tb(path):
'\n path : a tensorboard file OR a directory, where we will find all TB files\n of the form events.*\n '
import pandas
import numpy as np
from glob import glob
from collections import defaultdict
import tensorflow as tf
if osp.isdir(path):
fnames ... |
def rolling_window(a, window):
shape = (a.shape[:(- 1)] + (((a.shape[(- 1)] - window) + 1), window))
strides = (a.strides + (a.strides[(- 1)],))
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
|
def window_func(x, y, window, func):
yw = rolling_window(y, window)
yw_func = func(yw, axis=(- 1))
return (x[(window - 1):], yw_func)
|
def ts2xy(ts, xaxis):
if (xaxis == X_TIMESTEPS):
x = np.cumsum(ts.l.values)
y = ts.r.values
elif (xaxis == X_EPISODES):
x = np.arange(len(ts))
y = ts.r.values
elif (xaxis == X_WALLTIME):
x = (ts.t.values / 3600.0)
y = ts.r.values
else:
raise NotI... |
def plot_curves(xy_list, xaxis, title):
plt.figure(figsize=(8, 2))
maxx = max((xy[0][(- 1)] for xy in xy_list))
minx = 0
for (i, (x, y)) in enumerate(xy_list):
color = COLORS[i]
plt.scatter(x, y, s=2)
(x, y_mean) = window_func(x, y, EPISODES_WINDOW, np.mean)
plt.plot(x,... |
def plot_results(dirs, num_timesteps, xaxis, task_name):
tslist = []
for dir in dirs:
ts = load_results(dir)
ts = ts[(ts.l.cumsum() <= num_timesteps)]
tslist.append(ts)
xy_list = [ts2xy(ts, xaxis) for ts in tslist]
plot_curves(xy_list, xaxis, task_name)
|
def main():
import argparse
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dirs', help='List of log directories', nargs='*', default=['./log'])
parser.add_argument('--num_timesteps', type=int, default=int(10000000.0))
p... |
class Attention(Layer):
def __init__(self, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs):
'\n Keras Layer that implements an Content Attention mechanism.\n Supports Masking.\n '
self.supports_masking = True
self.ini... |
class WeightedSum(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(WeightedSum, self).__init__(**kwargs)
def call(self, input_tensor, mask=None):
assert (type(input_tensor) == list)
assert (type(mask) == list)
x = input_tensor[0]
a = in... |
class Average(Layer):
def __init__(self, mask_zero=True, **kwargs):
self.mask_zero = mask_zero
self.supports_masking = True
super(Average, self).__init__(**kwargs)
def call(self, x, mask=None):
if self.mask_zero:
mask = K.cast(mask, K.floatx())
mask = ... |
def get_optimizer(args):
clipvalue = 0
clipnorm = 10
if (args.algorithm == 'rmsprop'):
optimizer = opt.RMSprop(lr=0.001, rho=0.9, epsilon=1e-06, clipnorm=clipnorm, clipvalue=clipvalue)
elif (args.algorithm == 'sgd'):
optimizer = opt.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False,... |
class W2VEmbReader():
def __init__(self, args, emb_path):
logger.info(('Loading embeddings from: ' + emb_path))
self.embeddings = {}
emb_file = codecs.open(emb_path, 'r', encoding='utf8')
self.vocab_size = 0
self.emb_dim = (- 1)
for line in emb_file:
to... |
class W2VEmbReader():
def __init__(self, emb_path, emb_dim=None):
logger.info(('Loading embeddings from: ' + emb_path))
self.embeddings = {}
emb_file = codecs.open(emb_path, 'r', encoding='utf8')
self.vocab_size = 0
self.emb_dim = (- 1)
for line in emb_file:
... |
class BatchIter():
def __init__(self, dataset, batch_size, batch_first=False):
self.dataset = dataset
self.batch_size = batch_size
self.id = 0
self.batch_first = batch_first
def __len__(self):
return math.ceil((len(self.dataset) / self.batch_size))
def __getitem_... |
class Corpus(Dataset):
def __init__(self, path, word_dic=None, min_word_count=4):
print('start to load Corpus data')
with open(path, 'r') as f:
corpus = f.readlines()
corpus = [self._split(i.strip()) for i in corpus]
corpus = [(t, len(t)) for t in corpus]
corpu... |
class Discriminator_MLP(nn.Module):
def __init__(self, h_d, c_d, device):
super(Discriminator_MLP, self).__init__()
self.f = nn.Linear(c_d, h_d)
self.act = nn.ReLU()
self.device = device
for m in self.modules():
self.weights_init(m)
def weights_init(self, ... |
class Discriminator_Bilinear(nn.Module):
def __init__(self, n_h, n_c, device):
super(Discriminator_Bilinear, self).__init__()
self.f_k = nn.Bilinear(n_h, n_c, 1)
self.device = device
for m in self.modules():
self.weights_init(m)
def weights_init(self, m):
... |
class HGNN(nn.Module):
def __init__(self, in_ch, out_ch, device):
super(HGNN, self).__init__()
self.device = device
self.f = nn.Sequential(nn.Linear(in_ch, in_ch), nn.ReLU())
def forward(self, x, H, batch):
'\n x: the embedding of the vectors (V, d)\n H: the edg... |
class INFOMAX(nn.Module):
def __init__(self, n_h, n_neg, device):
super(INFOMAX, self).__init__()
'\n n_h: the dimension of the embedding\n n_neg: the number of negative samples for each positive samples\n '
self.sigm = nn.Sigmoid()
self.disc_hc = Discriminato... |
class Disc_INFOMIN(nn.Module):
def __init__(self, n_h, n_neg, device):
super(Disc_INFOMIN, self).__init__()
self.sigm = nn.Sigmoid()
self.disc = Discriminator_Bilinear(n_h, n_h, device)
self.n_neg = n_neg
self.device = device
self.drop = nn.Dropout(0.1)
sel... |
class MLPReadout(nn.Module):
def __init__(self, in_dim, out_dim, act):
'\n out_dim: the final prediction dim, usually 1\n act: the final activation, if rating then None, if CTR then sigmoid\n '
super(MLPReadout, self).__init__()
self.layer1 = nn.Linear(in_dim, out_dim... |
def evaluation(model, data_loader, device, is_test=False, epoch=(- 1)):
model.eval()
predictions = []
labels = []
user_ids = []
record = True
for data in data_loader:
data = data.to(device)
node_index = torch.squeeze(data.x)
edge_index = data.edge_index
batch = ... |
class HyperInfomax(nn.Module):
def __init__(self, args, n_features, device, writer):
super(HyperInfomax, self).__init__()
self.feature_emb = nn.Embedding(n_features, args.dim)
self.feature_emb_edge = nn.Embedding(n_features, args.dim)
self.hgnn = HGNN(args.dim, args.hid_units, dev... |
class Dataset(InMemoryDataset):
def __init__(self, root, dataset, rating_file, sep=',', sufix='', transform=None, pre_transform=None):
self.path = root
self.dataset = dataset
self.rating_file = rating_file
self.sep = sep
self.sufix = sufix
self.store_backup = True
... |
def cal_ndcg(predicts, labels, user_ids, k_list):
d = {'user': np.squeeze(user_ids), 'predict': np.squeeze(predicts), 'label': np.squeeze(labels)}
df = pd.DataFrame(d)
user_unique = df.user.unique()
ndcgs = [[] for _ in range(len(k_list))]
for user_id in user_unique:
user_srow = df.loc[(df... |
def cal_recall(predicts, labels, user_ids, k):
d = {'user': np.squeeze(user_ids), 'predict': np.squeeze(predicts), 'label': np.squeeze(labels)}
df = pd.DataFrame(d)
user_unique = df.user.unique()
recall = []
for user_id in user_unique:
user_sdf = df[(df['user'] == user_id)]
if (use... |
def eval_metrics(predictions, labels, user_ids, test=False):
predictions = np.concatenate(predictions, 0)
labels = np.concatenate(labels, 0)
user_ids = np.concatenate(user_ids, 0)
labels = labels.astype(int)
ndcg_list = cal_ndcg(predictions, labels, user_ids, [5, 10, 20])
if test:
reca... |
class BigFile():
def __init__(self, datadir, bin_file='feature.bin'):
(self.nr_of_images, self.ndims) = list(map(int, open(os.path.join(datadir, 'shape.txt')).readline().split()))
id_file = os.path.join(datadir, 'id.txt')
self.names = open(id_file, 'r').read().strip().split('\n')
... |
class StreamFile():
def __init__(self, datadir):
self.feat_dir = datadir
(self.nr_of_images, self.ndims) = list(map(int, open(os.path.join(datadir, 'shape.txt')).readline().split()))
id_file = os.path.join(datadir, 'id.txt')
self.names = open(id_file, 'r').read().strip().split('\n... |
def read_from_txt_file(cap_file):
'\n 从 id string 格式文档中读取 string\n :param cap_file:\n :return:\n '
captions = []
with open(cap_file, 'r') as fr:
for line in fr:
if (len(line.strip().split(' ', 1)) < 2):
cap_id = line.strip().split(' ', 1)[0]
... |
def build_vocab(cap_file, encoding, threshold, lang):
'\n 预处理,返回单词 index,以及 bow 字典\n :param cap_file:\n :param encoding: 词编码方法,bow, w2v, gru 等\n :param threshold:\n :param lang:\n :return:\n '
nosw = ('_nsw' in encoding)
logger.info('Build a simple vocabulary wrapper from %s', cap_fil... |
def process(options, collection):
overwrite = options.overwrite
rootpath = options.rootpath
threshold = options.threshold
encoding = options.encoding
language = options.language
folder_name = options.folder_name
caption_name = options.caption_name
vocab_file = os.path.join(rootpath, co... |
def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
from optparse import OptionParser
parser = OptionParser(usage='usage: %prog [options] collection')
parser.add_option('--overwrite', default=0, type='int', help='overwrite existing file (default: 0)')
parser.add_option('--rootpath'... |
class No():
pass
|
class config(BaseConfig.config):
model_name = 'FrameLAFF'
dropout = 0.2
activation = 'tanh'
batch_norm = True
vis_fc_layers = ['0', 4096]
txt_fc_layers = '0-4096'
text_encoding = {'bow_encoding': {'name': 'bow_nsw'}, 'w2v_encoding': {'name': 'w2v_nsw'}, 'rnn_encoding': {'name': 'gru_mean'}... |
class config(object):
def adjust_parm(self, value):
pass
def get_txt_encoder_num(self, text_encoding):
encoder_num = 0
for name in text_encoding:
encoder_value = text_encoding[name]['name']
if ('no' not in encoder_value):
encoder_num += 1
... |
class config(BaseConfig.config):
model_name = 'LAFF'
dropout = 0.2
activation = 'tanh'
vis_fc_layers = ['0', 4096]
txt_fc_layers = '0-4096'
text_encoding = {'bow_encoding': {'name': 'bow_nsw'}, 'w2v_encoding': {'name': 'w2v_nsw'}, 'rnn_encoding': {'name': 'gru_mean'}, 'bert_encoding': {'name':... |
def parse_args():
parser = argparse.ArgumentParser('check data')
parser.add_argument('--rootpath', type=str, default=ROOT_PATH, help=('path to datasets. (default: %s)' % ROOT_PATH))
parser.add_argument('dataset', type=str, help='test dataset')
args = parser.parse_args()
return args
|
def parse_args():
parser = argparse.ArgumentParser('W2VVPP training script.')
parser.add_argument('--rootpath', type=str, default=ROOT_PATH, help=('path to datasets. (default: %s)' % ROOT_PATH))
parser.add_argument('trainCollection', type=str, default='msrvtt10k', help='train collection')
parser.add_a... |
class CustomObjectScope(object):
"Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.\n\n Code within a `with` statement will be able to access custom objects\n by name. Changes to global custom objects persist\n within the enclosing `with` statement. At end of the `with` statement,\... |
def custom_object_scope(*args):
"Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.\n\n Convenience wrapper for `CustomObjectScope`.\n Code within a `with` statement will be able to access custom objects\n by name. Changes to global custom objects persist\n within the enclosing `... |
def get_custom_objects():
"Retrieves a live reference to the global dictionary of custom objects.\n\n Updating and clearing custom objects using `custom_object_scope`\n is preferred, but `get_custom_objects` can\n be used to directly access `_GLOBAL_CUSTOM_OBJECTS`.\n\n # Example\n\n ```python\n ... |
def serialize_keras_object(instance):
if (instance is None):
return None
if hasattr(instance, 'get_config'):
return {'class_name': instance.__class__.__name__, 'config': instance.get_config()}
if hasattr(instance, '__name__'):
return instance.__name__
else:
raise ValueE... |
def deserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object'):
if isinstance(identifier, dict):
config = identifier
if (('class_name' not in config) or ('config' not in config)):
raise ValueError(('Improper config format: ' + str(con... |
def func_dump(func):
'Serializes a user defined function.\n\n # Arguments\n func: the function to serialize.\n\n # Returns\n A tuple `(code, defaults, closure)`.\n '
raw_code = marshal.dumps(func.__code__)
code = codecs.encode(raw_code, 'base64').decode('ascii')
defaults = func.... |
def func_load(code, defaults=None, closure=None, globs=None):
'Deserializes a user defined function.\n\n # Arguments\n code: bytecode of the function.\n defaults: defaults of the function.\n closure: closure of the function.\n globs: dictionary of global objects.\n\n # Returns\n ... |
def has_arg(fn, name, accept_all=False):
'Checks if a callable accepts a given keyword argument.\n\n For Python 2, checks if there is an argument with the given name.\n\n For Python 3, checks if there is an argument with the given name, and\n also whether this argument can be called with a keyword (i.e. ... |
class Progbar(object):
'Displays a progress bar.\n\n # Arguments\n target: Total number of steps expected, None if unknown.\n width: Progress bar width on screen.\n verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)\n stateful_metrics: Iterable of string names of met... |
def l2norm(X, eps=1e-13, dim=1):
'L2-normalize columns of X\n '
norm = ((torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps) + 1e-14)
X = torch.div(X, norm)
return X
|
def l1norm(X, eps=1e-13, dim=1):
'L2-normalize columns of X\n '
norm = ((torch.abs(X).sum(dim=dim, keepdim=True) + eps) + 1e-14)
X = torch.div(X, norm)
return X
|
def normalization(X, dim=1):
_range = (np.max(X) - np.min(X))
return ((X - np.min(X)) / _range)
|
def cosine_sim(query, retrio):
'Cosine similarity between all the query and retrio pairs\n '
(query, retrio) = (l2norm(query), l2norm(retrio))
return query.mm(retrio.t())
|
def vector_cosine_sim(query, retrio):
'Cosine similarity between the query and retrio pairs\n '
(query, retrio) = (l2norm(query), l2norm(retrio))
return torch.sum(torch.mul(query, retrio), dim=1).unsqueeze(0)
|
def hist_sim(im, s, eps=1e-14):
bs = im.size(0)
im = im.unsqueeze(1).expand((- 1), bs, (- 1))
s = s.unsqueeze(0).expand(bs, (- 1), (- 1))
intersection = torch.min(im, s).sum((- 1))
union = (torch.max(im, s).sum((- 1)) + eps)
score = (intersection / union)
return score
|
def jaccard_sim(query, retrieval_base, eps=1e-08):
score = None
base_num = retrieval_base.size(0)
for each in query:
each = each.unsqueeze(0).repeat(base_num, 1)
intersection = torch.min(each, retrieval_base).sum((- 1))
union = (torch.max(each, retrieval_base).sum((- 1)) + eps)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.