code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def forward(self, x): ''' Forward pass through the encoder block. @param x: input with a shape of [batch_size, ranking_size, num_features] @return: ''' for layer in self.layers: x = layer(x) if 'AllRank' == self.encoder_type: return self.n...
Forward pass through the encoder block. @param x: input with a shape of [batch_size, ranking_size, num_features] @return:
forward
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def __init__(self, hid_dim, encoder_type=None, dropout=None): ''' @param hid_dim: number of input/output features @param dropout: dropout probability ''' super(SublayerConnection, self).__init__() self.encoder_type = encoder_type self.norm = LayerNorm(hid_dim=hid_...
@param hid_dim: number of input/output features @param dropout: dropout probability
__init__
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def forward(self, x, sublayer): ''' Foward pass through the sublayer connection module, applying the residual connection to any sublayer with the same size. @param x: input with a shape of [batch_size, ranking_size, num_features] @param sublayer: the layer through which to pass the input...
Foward pass through the sublayer connection module, applying the residual connection to any sublayer with the same size. @param x: input with a shape of [batch_size, ranking_size, num_features] @param sublayer: the layer through which to pass the input prior to applying the sum @return:...
forward
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def __init__(self, hid_dim, eps=1e-6): ''' @param hid_dim: shape of normalised features @param eps: epsilon for standard deviation ''' super(LayerNorm, self).__init__() self.a_2 = nn.Parameter(torch.ones(hid_dim)) self.b_2 = nn.Parameter(torch.zeros(hid_dim)) ...
@param hid_dim: shape of normalised features @param eps: epsilon for standard deviation
__init__
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def forward(self, x): ''' Forward pass through the layer normalization @param x: input shape, i.e., [batch_size, ranking_size, num_features] @return: normalized input with a shape of [batch_size, ranking_size, num_features] ''' mean = x.mean(-1, keepdim=True) std ...
Forward pass through the layer normalization @param x: input shape, i.e., [batch_size, ranking_size, num_features] @return: normalized input with a shape of [batch_size, ranking_size, num_features]
forward
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def __init__(self, hid_dim, n_heads, dropout=0.1, device=None): ''' :param hid_dim: number of features, i.e., input/output dimensionality :param n_heads: number of heads :param dropout: dropout probability ''' super(MultiheadAttention, self).__init__() self.hid_di...
:param hid_dim: number of features, i.e., input/output dimensionality :param n_heads: number of heads :param dropout: dropout probability
__init__
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def forward(self, batch_rankings): ''' Forward pass through the multi-head attention block. :param batch_rankings: [batch_size, ranking_size, num_features] :return: ''' bsz = batch_rankings.shape[0] Q = self.w_q(batch_rankings) K = self.w_k(batch_rankings)...
Forward pass through the multi-head attention block. :param batch_rankings: [batch_size, ranking_size, num_features] :return:
forward
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def __init__(self, num_features, hid_dim, dropout=0.1): """ :param num_features: input/output dimensionality :param hid_dim: hidden dimensionality :param dropout: dropout probability """ super(PositionwiseFeedForward, self).__init__() self.w1 = nn.Linear(num_featu...
:param num_features: input/output dimensionality :param hid_dim: hidden dimensionality :param dropout: dropout probability
__init__
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def ini_listsf(self, num_features=None, ff_dims=[128, 256, 512], out_dim=1, AF='R', TL_AF='GE', apply_tl_af=False, BN=True, bn_type=None, bn_affine=False, n_heads=2, encoder_layers=3, dropout=0.1, encoder_type=None): ''' Initialization of a permutation equivariant neural network ...
Initialization of a permutation equivariant neural network
ini_listsf
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def forward(self, batch_q_doc_vectors): ''' Forward pass through the scoring function, where the documents associated with the same query are scored jointly. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vector...
Forward pass through the scoring function, where the documents associated with the same query are scored jointly. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vectors associated with the same query. @return: ...
forward
python
wildltr/ptranking
ptranking/base/list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/list_ranker.py
MIT
def ini_pointsf(self, num_features=None, h_dim=100, out_dim=1, num_layers=3, AF='R', TL_AF='S', apply_tl_af=False, BN=True, bn_type=None, bn_affine=False, dropout=0.1): ''' Initialization of a feed-forward neural network ''' ff_dims = [num_features] for i in r...
Initialization of a feed-forward neural network
ini_pointsf
python
wildltr/ptranking
ptranking/base/point_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/point_ranker.py
MIT
def forward(self, batch_q_doc_vectors): ''' Forward pass through the scoring function, where each document is scored independently. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vectors associated with the same...
Forward pass through the scoring function, where each document is scored independently. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vectors associated with the same query. @return:
forward
python
wildltr/ptranking
ptranking/base/point_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/point_ranker.py
MIT
def ndcg_at_k(self, test_data=None, k=10, label_type=LABEL_TYPE.MultiLabel, presort=False, device='cpu'): ''' Compute nDCG@k with the given data An underlying assumption is that there is at least one relevant document, or ZeroDivisionError appears. ''' self.eval_mode() # switch e...
Compute nDCG@k with the given data An underlying assumption is that there is at least one relevant document, or ZeroDivisionError appears.
ndcg_at_k
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def ndcg_at_ks(self, test_data=None, ks=[1, 5, 10], label_type=LABEL_TYPE.MultiLabel, presort=False, device='cpu'): ''' Compute nDCG with multiple cutoff values with the given data An underlying assumption is that there is at least one relevant document, or ZeroDivisionError appears. '''...
Compute nDCG with multiple cutoff values with the given data An underlying assumption is that there is at least one relevant document, or ZeroDivisionError appears.
ndcg_at_ks
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def ap_at_k(self, test_data=None, k=10, presort=False, device='cpu'): ''' Compute the performance using multiple metrics ''' self.eval_mode() # switch evaluation mode num_queries = 0 sum_ap_at_k = torch.zeros(1) for batch_ids, batch_q_doc_vectors, batch_std_labe...
Compute the performance using multiple metrics
ap_at_k
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def alpha_ndcg_at_k(self, test_data=None, k=5, device='cpu'): ''' Compute alpha-nDCG@k with the given data @param test_data: @param k: @return: ''' self.eval_mode() assert test_data.presort is True cnt = torch.zeros(1) sum_alpha_nDCG_at_k ...
Compute alpha-nDCG@k with the given data @param test_data: @param k: @return:
alpha_ndcg_at_k
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def alpha_ndcg_at_ks(self, test_data=None, ks=[1, 5, 10], device='cpu'): ''' Compute alpha-nDCG with multiple cutoff values with the given data There is no check based on the assumption (say light_filtering() is called) that each test instance Q includes at least k documents, and at leas...
Compute alpha-nDCG with multiple cutoff values with the given data There is no check based on the assumption (say light_filtering() is called) that each test instance Q includes at least k documents, and at least one relevant document. Or there will be errors.
alpha_ndcg_at_ks
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def err_ia_at_k(self, test_data=None, k=5, max_label=None, device='cpu'): ''' Compute ERR-IA@k with the given data @param test_data: @param k: @return: ''' self.eval_mode() cnt = torch.zeros(1) sum_err_ia_at_k = torch.zeros(1) for qid, q_r...
Compute ERR-IA@k with the given data @param test_data: @param k: @return:
err_ia_at_k
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def nerr_ia_at_k(self, test_data=None, k=5, max_label=None, device='cpu'): ''' Compute nERR-IA@k with the given data @param test_data: @param k: @return: ''' self.eval_mode() assert test_data.presort is True cnt = torch.zeros(1) sum_nerr_i...
Compute nERR-IA@k with the given data @param test_data: @param k: @return:
nerr_ia_at_k
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def stop_training(self, batch_preds): ''' Stop training if the predictions are all zeros or include nan value(s) ''' #if torch.nonzero(preds).size(0) <= 0: # todo-as-note: 'preds.byte().any()' seems wrong operation w.r.t. gpu if torch.nonzero(batch_preds, as_tuple=False).size(0)...
Stop training if the predictions are all zeros or include nan value(s)
stop_training
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def train(self, train_data, epoch_k=None, **kwargs): ''' One epoch training using the entire training data ''' self.train_mode() assert 'label_type' in kwargs and 'presort' in kwargs label_type, presort = kwargs['label_type'], kwargs['presort'] num_queries = 0 ...
One epoch training using the entire training data
train
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def train_op(self, batch_q_doc_vectors, batch_std_labels, **kwargs): ''' The training operation over a batch of queries. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vectors associated with the same query. ...
The training operation over a batch of queries. @param batch_q_doc_vectors: [batch_size, num_docs, num_features], the latter two dimensions {num_docs, num_features} denote feature vectors associated with the same query. @param batch_std_labels: [batch, ranking_size] each row represents the stan...
train_op
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def div_train_op(self, q_repr, doc_reprs, q_doc_rele_mat, **kwargs): ''' Per-query training based on the documents that are associated with the same query. ''' stop_training = False batch_pred = self.div_forward(q_repr, doc_reprs) if 'epoch_k' in kwargs and kwargs['epoch...
Per-query training based on the documents that are associated with the same query.
div_train_op
python
wildltr/ptranking
ptranking/base/ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/ranker.py
MIT
def forward(ctx, input, sigma=1.0): ''' :param ctx: :param input: the input tensor :param sigma: the scaling constant :return: ''' x = input if 1.0==sigma else sigma * input sigmoid_x = 1. / (1. + torch.exp(-x)) grad = sigmoid_x * (1. - sigmoid_x...
:param ctx: :param input: the input tensor :param sigma: the scaling constant :return:
forward
python
wildltr/ptranking
ptranking/base/utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/utils.py
MIT
def backward(ctx, grad_output): ''' :param ctx: :param grad_output: backpropagated gradients from upper module(s) :return: ''' grad = ctx.saved_tensors[0] bg = grad_output * grad # chain rule return bg, None
:param ctx: :param grad_output: backpropagated gradients from upper module(s) :return:
backward
python
wildltr/ptranking
ptranking/base/utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/utils.py
MIT
def __init__(self, num_features, momentum=0.1, affine=True, track_running_stats=False): ''' @param num_features: C from an expected input of size (N, C, L) or from input of size (N, L) @param momentum: the value used for the running_mean and running_var computation. Can be set to None for cumula...
@param num_features: C from an expected input of size (N, C, L) or from input of size (N, L) @param momentum: the value used for the running_mean and running_var computation. Can be set to None for cumulative moving average (i.e. simple average). Default: 0.1 @param affine: a boolean value that...
__init__
python
wildltr/ptranking
ptranking/base/utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/utils.py
MIT
def __init__(self, num_features, momentum=0.1, affine=True, device=None): ''' In the context of learning-to-rank, batch normalization is conducted at a per-query level, namely across documents associated with the same query. @param num_features: the number of features @param num_dims: is...
In the context of learning-to-rank, batch normalization is conducted at a per-query level, namely across documents associated with the same query. @param num_features: the number of features @param num_dims: is assumed to be [num_queries, num_docs, num_features]
__init__
python
wildltr/ptranking
ptranking/base/utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/utils.py
MIT
def get_stacked_FFNet(ff_dims=None, AF=None, TL_AF=None, apply_tl_af=False, dropout=0.1, BN=True, bn_type=None, bn_affine=False, device='cpu', split_penultimate_layer=False): ''' Generate one stacked feed-forward network. ''' # '2' refers to the simplest case: num_features, out_dim...
Generate one stacked feed-forward network.
get_stacked_FFNet
python
wildltr/ptranking
ptranking/base/utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/base/utils.py
MIT
def get_data_meta(data_id=None): """ Get the meta-information corresponding to the specified dataset """ if data_id in MSLRWEB: max_rele_level = 4 label_type = LABEL_TYPE.MultiLabel num_features = 136 has_comment = False fold_num = 5 elif data_id in MSLETOR_SUPER: ...
Get the meta-information corresponding to the specified dataset
get_data_meta
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def get_scaler_setting(data_id, scaler_id=None): """ A default scaler-setting for loading a dataset :param data_id: :param grid_search: used for grid-search :return: """ ''' According to {Introducing {LETOR} 4.0 Datasets}, "QueryLevelNorm version: Conduct query level normalization based on d...
A default scaler-setting for loading a dataset :param data_id: :param grid_search: used for grid-search :return:
get_scaler_setting
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def iter_lines(lines, has_targets=True, one_indexed=True, missing=0.0, has_comment=False): """ Transforms an iterator of lines to an iterator of LETOR rows. Each row is represented by a (x, y, qid, comment) tuple. Parameters ---------- lines : iterable of lines Lines to parse. has_targets : bool...
Transforms an iterator of lines to an iterator of LETOR rows. Each row is represented by a (x, y, qid, comment) tuple. Parameters ---------- lines : iterable of lines Lines to parse. has_targets : bool, optional, i.e., the relevance label Whether the file contains targets. If True, will exp...
iter_lines
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def parse_letor(source, has_targets=True, one_indexed=True, missing=0.0, has_comment=False): """ Parses a LETOR dataset from `source`. Parameters ---------- source : string or iterable of lines String, file, or other file-like object to parse. has_targets : bool, optional one_indexed : bool,...
Parses a LETOR dataset from `source`. Parameters ---------- source : string or iterable of lines String, file, or other file-like object to parse. has_targets : bool, optional one_indexed : bool, optional missing : float, optional Returns ------- X : array of arrays of floats Fe...
parse_letor
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def clip_query_data(qid, list_docids=None, feature_mat=None, std_label_vec=None, binary_rele=False, unknown_as_zero=False, clip_query=None, min_docs=None, min_rele=1, presort=None): """ Clip the data associated with the same query if required """ if binary_rele: std_label_vec = np.clip(std_l...
Clip the data associated with the same query if required
clip_query_data
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def iter_queries(in_file, presort=None, data_dict=None, scale_data=None, scaler_id=None, perquery_file=None, buffer=True): ''' Transforms an iterator of rows to an iterator of queries (i.e., a unit of all the documents and labels associated with the same query). Each query is represented by a (qid, feature_...
Transforms an iterator of rows to an iterator of queries (i.e., a unit of all the documents and labels associated with the same query). Each query is represented by a (qid, feature_mat, std_label_vec) tuple. :param in_file: :param has_comment: :param query_level_scale: perform query-level scaling, ...
iter_queries
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def pre_allocate_batch(dict_univ_bin, num_docs_per_batch): ''' Based on the expected number of documents to process within a single batch, we merge the queries that have the same number of documents to form a batch @param dict_univ_bin: [unique_value, bin of index] @param num_docs_per_batch: @return...
Based on the expected number of documents to process within a single batch, we merge the queries that have the same number of documents to form a batch @param dict_univ_bin: [unique_value, bin of index] @param num_docs_per_batch: @return:
pre_allocate_batch
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def __init__(self, data_source, percent=.01): ''' @param data_source: dataset to sample from @param percent: the ratio of being used part ''' num_queries = data_source.__len__() #print('num_queries', num_queries) num_used_queries = int(num_queries * percent) ...
@param data_source: dataset to sample from @param percent: the ratio of being used part
__init__
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def get_buffer_file_name_libsvm(in_file, data_id=None, eval_dict=None, need_group=True): """ get absolute paths of data file and group file """ if data_id in MSLETOR or data_id in MSLRWEB: buffer_prefix = in_file.replace('Fold', 'BufferedFold') file_buffered_data = buffer_prefix.replace(...
get absolute paths of data file and group file
get_buffer_file_name_libsvm
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def letor_to_libsvm(doc_reprs=None, doc_labels=None, output_feature=None, output_group=None, need_group=False): ''' convert query-level letor-data to libsvm data ''' num_docs = doc_reprs.shape[0] if need_group: output_group.write(str(num_docs) + "\n") # group file for i in range(num_docs): # per documen...
convert query-level letor-data to libsvm data
letor_to_libsvm
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def load_letor_data_as_libsvm_data(in_file, split_type=None, data_id=None, min_docs=None, min_rele=None, data_dict=None, eval_dict=None, need_group=True, presort=None, scaler_id=None): """ Load data by firstly converting letor data as libsvm data :param in_file: :param...
Load data by firstly converting letor data as libsvm data :param in_file: :param min_docs: :param min_rele: :param data_id: :param eval_dict: :param need_group: required w.r.t. xgboost, lightgbm :return:
load_letor_data_as_libsvm_data
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def random_mask_all_labels(batch_ranking, batch_label, mask_ratio, mask_value=0, presort=False): ''' Mask the ground-truth labels with the specified ratio as '0'. Meanwhile, re-sort according to the labels if required. :param doc_reprs: :param doc_labels: :param mask_ratio: the ratio of labels to be...
Mask the ground-truth labels with the specified ratio as '0'. Meanwhile, re-sort according to the labels if required. :param doc_reprs: :param doc_labels: :param mask_ratio: the ratio of labels to be masked :param mask_value: :param presort: :return:
random_mask_all_labels
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def np_random_mask_all_labels(batch_label, mask_ratio, mask_value=0): ''' Mask the ground-truth labels with the specified ratio as '0'. ''' size_ranking = len(batch_label) num_to_mask = int(size_ranking*mask_ratio) mask_ind = np.random.choice(size_ranking, size=num_to_mask, replace=False) b...
Mask the ground-truth labels with the specified ratio as '0'.
np_random_mask_all_labels
python
wildltr/ptranking
ptranking/data/data_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/data/data_utils.py
MIT
def display_information(self, data_dict, model_para_dict, reproduce=False): """ Display some information. :param data_dict: :param model_para_dict: :return: """ if self.gpu: print('-- GPU({}) is launched --'.format(self.device)) else: ...
Display some information. :param data_dict: :param model_para_dict: :return:
display_information
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def check_consistency(self, data_dict, eval_dict, sf_para_dict): """ Check whether the settings are reasonable in the context of adhoc learning-to-rank """ ''' Part-1: data loading ''' if data_dict['data_id'] == 'Istella': assert eval_dict['do_validation'] is not Tru...
Check whether the settings are reasonable in the context of adhoc learning-to-rank
check_consistency
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def determine_files(self, data_dict, fold_k=None): """ Determine the file path correspondingly. :param data_dict: :param fold_k: :return: """ if data_dict['data_id'] in YAHOO_LTR: file_train, file_vali, file_test = os.path.join(data_dict['dir_data'], d...
Determine the file path correspondingly. :param data_dict: :param fold_k: :return:
determine_files
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def load_data(self, eval_dict, data_dict, fold_k): """ Load the dataset correspondingly. :param eval_dict: :param data_dict: :param fold_k: :param model_para_dict: :return: """ file_train, file_vali, file_test = self.determine_files(data_dict, fold...
Load the dataset correspondingly. :param eval_dict: :param data_dict: :param fold_k: :param model_para_dict: :return:
load_data
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def load_ranker(self, sf_para_dict, model_para_dict): """ Load a ranker correspondingly :param sf_para_dict: :param model_para_dict: :param kwargs: :return: """ model_id = model_para_dict['model_id'] if model_id in ['RankMSE', 'ListMLE', 'ListNet'...
Load a ranker correspondingly :param sf_para_dict: :param model_para_dict: :param kwargs: :return:
load_ranker
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def setup_output(self, data_dict=None, eval_dict=None): """ Update output directory :param data_dict: :param eval_dict: :param sf_para_dict: :param model_para_dict: :return: """ model_id = self.model_parameter.model_id grid_search, do_vali,...
Update output directory :param data_dict: :param eval_dict: :param sf_para_dict: :param model_para_dict: :return:
setup_output
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def setup_eval(self, data_dict, eval_dict, sf_para_dict, model_para_dict): """ Finalize the evaluation setting correspondingly :param data_dict: :param eval_dict: :param sf_para_dict: :param model_para_dict: :return: """ sf_para_dict[sf_para_dict['...
Finalize the evaluation setting correspondingly :param data_dict: :param eval_dict: :param sf_para_dict: :param model_para_dict: :return:
setup_eval
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def log_max(self, data_dict=None, max_cv_avg_scores=None, sf_para_dict=None, eval_dict=None, log_para_str=None): ''' Log the best performance across grid search and the corresponding setting ''' dir_root, cutoffs = eval_dict['dir_root'], eval_dict['cutoffs'] data_id = data_dict['data_id'] ...
Log the best performance across grid search and the corresponding setting
log_max
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def kfold_cv_eval(self, data_dict=None, eval_dict=None, sf_para_dict=None, model_para_dict=None): """ Evaluation learning-to-rank methods via k-fold cross validation if there are k folds, otherwise one fold. :param data_dict: settings w.r.t. data :param eval_dict: settings w....
Evaluation learning-to-rank methods via k-fold cross validation if there are k folds, otherwise one fold. :param data_dict: settings w.r.t. data :param eval_dict: settings w.r.t. evaluation :param sf_para_dict: settings w.r.t. scoring function :param model_para_di...
kfold_cv_eval
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def naive_train(self, ranker, eval_dict, train_data=None, test_data=None): """ A simple train and test, namely train based on training data & test based on testing data :param ranker: :param eval_dict: :param train_data: :param test_data: :param vali_data: ...
A simple train and test, namely train based on training data & test based on testing data :param ranker: :param eval_dict: :param train_data: :param test_data: :param vali_data: :return:
naive_train
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def set_model_setting(self, model_id=None, dir_json=None, debug=False): """ Initialize the parameter class for a specified model :param debug: :param model_id: :return: """ if model_id in ['RankMSE', 'ListMLE', 'ListNet', 'RankCosine', 'DASALC', 'HistogramAP']: # ...
Initialize the parameter class for a specified model :param debug: :param model_id: :return:
set_model_setting
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def declare_global(self, model_id=None): """ Declare global variants if required, such as for efficiency :param model_id: :return: """ if model_id == 'WassRank': # global buffering across a number of runs with different model parameters self.dict_cost_mats, se...
Declare global variants if required, such as for efficiency :param model_id: :return:
declare_global
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def point_run(self, debug=False, model_id=None, sf_id=None, data_id=None, dir_data=None, dir_output=None, dir_json=None, reproduce=False): """ Perform one-time run based on given setting. :param debug: :param model_id: :param data_id: :param dir_data: ...
Perform one-time run based on given setting. :param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return:
point_run
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def grid_run(self, model_id=None, sf_id=None, dir_json=None, debug=False, data_id=None, dir_data=None, dir_output=None): """ Explore the effects of different hyper-parameters of a model based on grid-search :param debug: :param model_id: :param data_id: :param dir_data: ...
Explore the effects of different hyper-parameters of a model based on grid-search :param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return:
grid_run
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/ltr.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/ltr.py
MIT
def load_para_json(self, para_json): """ load json file of parameter setting """ with open(para_json) as json_file: json_dict = json.load(json_file) return json_dict
load json file of parameter setting
load_para_json
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def default_pointsf_para_dict(self): """ A default setting of the hyper-parameters of the stump neural scoring function. """ # common default settings for a scoring function based on feed-forward neural networks self.sf_para_dict = dict() if self.use_json: o...
A default setting of the hyper-parameters of the stump neural scoring function.
default_pointsf_para_dict
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def default_listsf_para_dict(self): """ A default setting of the hyper-parameters of the permutation-equivariant neural scoring function. """ self.sf_para_dict = dict() self.sf_para_dict['opt'] = 'Adagrad' # Adam | RMS | Adagrad self.sf_para_dict['lr'] = 0.001 # learnin...
A default setting of the hyper-parameters of the permutation-equivariant neural scoring function.
default_listsf_para_dict
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def pointsf_grid_search(self): """ Iterator of hyper-parameters of the stump neural scoring function. """ if self.use_json: choice_opt = self.json_dict['opt'] choice_lr = self.json_dict['lr'] pointsf_json_dict = self.json_dict[self.sf_id] c...
Iterator of hyper-parameters of the stump neural scoring function.
pointsf_grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def pointsf_to_para_string(self, log=False): ''' Get the identifier of scoring function ''' s1, s2 = (':', '\n') if log else ('_', '_') sf_para_dict = self.sf_para_dict[self.sf_id] sf_str_1 = self.get_stacked_FFNet_str(ff_para_dict=sf_para_dict, point=True, log=log, s1=s1, s2=s2) ...
Get the identifier of scoring function
pointsf_to_para_string
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def to_eval_setting_string(self, log=False): """ String identifier of eval-setting :param log: :return: """ eval_dict = self.eval_dict s1, s2 = (':', '\n') if log else ('_', '_') do_vali, epochs = eval_dict['do_validation'], eval_dict['epochs'] if...
String identifier of eval-setting :param log: :return:
to_eval_setting_string
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def default_setting(self): """ A default setting for evaluation :param debug: :param data_id: :param dir_output: :return: """ if self.use_json: dir_output = self.json_dict['dir_output'] epochs = self.json_dict['epochs'] # debug is a...
A default setting for evaluation :param debug: :param data_id: :param dir_output: :return:
default_setting
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def default_setting(self): """ A default setting for data loading :return: """ if self.use_json: scaler_id = self.json_dict['scaler_id'] min_docs = self.json_dict['min_docs'][0] min_rele = self.json_dict['min_rele'][0] binary_rele =...
A default setting for data loading :return:
default_setting
python
wildltr/ptranking
ptranking/ltr_adhoc/eval/parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/eval/parameter.py
MIT
def get_approx_ranks(input, alpha=10, device=None): ''' get approximated rank positions: Equation-11 in the paper''' batch_pred_diffs = torch.unsqueeze(input, dim=2) - torch.unsqueeze(input, dim=1) # computing pairwise differences, i.e., Sij or Sxy batch_indicators = robust_sigmoid(torch.transpose(batch_p...
get approximated rank positions: Equation-11 in the paper
get_approx_ranks
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/approxNDCG.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/approxNDCG.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard releva...
@param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents associated with the same query @param kwargs: ...
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/approxNDCG.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/approxNDCG.py
MIT
def to_para_string(self, log=False, given_para_dict=None): """ String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return: """ # using specified para-dict or inner para-dict ...
String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return:
to_para_string
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/approxNDCG.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/approxNDCG.py
MIT
def grid_search(self): """ Iterator of parameter settings for ApproxNDCG """ if self.use_json: choice_alpha = self.json_dict['alpha'] else: choice_alpha = [10.0] if self.debug else [10.0] # 1.0, 10.0, 50.0, 100.0 for alpha in choice_alpha: ...
Iterator of parameter settings for ApproxNDCG
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/approxNDCG.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/approxNDCG.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' The Top-1 approximated ListNet loss, which reduces to a softmax and simple cross entropy. @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param...
The Top-1 approximated ListNet loss, which reduces to a softmax and simple cross entropy. @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard rele...
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/dasalc.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/dasalc.py
MIT
def grid_search(self): """ Iterator of parameter settings for LambdaLoss :param debug: :return: """ if self.use_json: choice_k = self.json_dict['k'] choice_mu = self.json_dict['mu'] choice_sigma = self.json_dict['sigma'] cho...
Iterator of parameter settings for LambdaLoss :param debug: :return:
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/lambdaloss.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/lambdaloss.py
MIT
def grid_search(self): """ Iterator of parameter settings for LambdaRank """ if self.use_json: choice_sigma = self.json_dict['sigma'] else: choice_sigma = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0 for sigma in choice_sigma: ...
Iterator of parameter settings for LambdaRank
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/lambdarank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/lambdarank.py
MIT
def forward(ctx, input): ''' In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context object that can be used to stash informat...
In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context object that can be used to stash information for backward computation. ...
forward
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/listmle.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/listmle.py
MIT
def backward(ctx, grad_output): ''' In the backward pass we receive the context object and a Tensor containing the gradient of the loss with respect to the output produced during the forward pass (i.e., forward's output). We can retrieve cached data from the context object, and must compute and return the gra...
In the backward pass we receive the context object and a Tensor containing the gradient of the loss with respect to the output produced during the forward pass (i.e., forward's output). We can retrieve cached data from the context object, and must compute and return the gradient of the loss with respect to the...
backward
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/listmle.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/listmle.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades f...
@param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents associated with the same query @param kwargs: @return:
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/listmle.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/listmle.py
MIT
def to_para_string(self, log=False, given_para_dict=None): """ String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search """ # using specified para-dict or inner para-dict MDPRank_para_di...
String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search
to_para_string
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/mdprank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/mdprank.py
MIT
def grid_search(self): """ Iterator of parameter settings for FastMDPRank """ if self.use_json: #choice_metric = json_dict['metric'] choice_topk = self.json_dict['top_k'] choice_distribution = self.json_dict['distribution'] choice_temperatu...
Iterator of parameter settings for FastMDPRank
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/mdprank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/mdprank.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' @param batch_preds: [batch, ranking_size] each row represents the mean predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for do...
@param batch_preds: [batch, ranking_size] each row represents the mean predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents associated with the same query @param kwargs: @return:
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/softrank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/softrank.py
MIT
def to_para_string(self, log=False, given_para_dict=None): """ String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return: """ # using specified para-dict or inner para-dict soft_para_dict = given_para_dict if given_para...
String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return:
to_para_string
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/softrank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/softrank.py
MIT
def grid_search(self): """ Iterator of parameter settings for SoftRank """ if self.use_json: choice_topk = self.json_dict['top_k'] choice_delta = self.json_dict['delta'] choice_metric = self.json_dict['metric'] else: choice_delta = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0 c...
Iterator of parameter settings for SoftRank
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/softrank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/softrank.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' The Top-1 approximated ListNet loss, which reduces to a softmax and simple cross entropy. @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same qu...
The Top-1 approximated ListNet loss, which reduces to a softmax and simple cross entropy. @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the s...
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/st_listnet.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/st_listnet.py
MIT
def grid_search(self): """ Iterator of parameter settings for STListNet :param debug: :return: """ if self.use_json: choice_temperature = self.json_dict['temperature'] else: choice_temperature = [1.0] if self.debug else [1.0] # 1.0, 10.0, ...
Iterator of parameter settings for STListNet :param debug: :return:
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/st_listnet.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/st_listnet.py
MIT
def __init__(self, eps, max_iter, reduction='mean'): """ eps (float): regularization coefficient max_iter (int): maximum number of Sinkhorn iterations """ super(EntropicOT, self).__init__() self.eps = eps self.max_iter = max_iter self.reduction = reduction
eps (float): regularization coefficient max_iter (int): maximum number of Sinkhorn iterations
__init__
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/pytorch_wasserstein.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/pytorch_wasserstein.py
MIT
def forward(ctx, pred, target, cost, lam, sh_num_iter): """ pred: Batch * K: K = # mass points target: Batch * L: L = # mass points """ na, nb = cost.size(0), cost.size(1) assert pred.size(1) == na and target.size(1) == nb K = torch.exp(-cost / lam) KM = ...
pred: Batch * K: K = # mass points target: Batch * L: L = # mass points
forward
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/pytorch_wasserstein.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/pytorch_wasserstein.py
MIT
def _cost_mat_group(cpu_tor_batch_std_label_vec, non_rele_gap=100.0, var_penalty=0.01, gain_base=4.0): """ Numpy reference Take into account the group information among documents, namely whether two documents are of the same standard relevance degree @param non_rele_gap the gap between a relevant docume...
Numpy reference Take into account the group information among documents, namely whether two documents are of the same standard relevance degree @param non_rele_gap the gap between a relevant document and an irrelevant document @param var_penalty variance penalty @param gain_base the base for comput...
_cost_mat_group
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def torch_cost_mat_dist(batch_std_labels, exponent=1.0, gpu=False): """ Viewing the absolute difference (with a exponent value) between two rank positions as the cost """ batch_size = batch_std_labels.size(0) ranking_size = batch_std_labels.size(1) positions = (torch.arange(ranking_size) + 1.0).type(to...
Viewing the absolute difference (with a exponent value) between two rank positions as the cost
torch_cost_mat_dist
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def get_delta_gains(batch_stds, discount=False, gpu=False): ''' Delta-gains w.r.t. pairwise swapping of the ideal ltr_adhoc :param batch_stds: the standard labels sorted in a descending order :return: ''' batch_gains = torch.pow(2.0, batch_stds) - 1.0 batch_g_diffs = torch.unsqueeze(batch_ga...
Delta-gains w.r.t. pairwise swapping of the ideal ltr_adhoc :param batch_stds: the standard labels sorted in a descending order :return:
get_delta_gains
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def torch_cost_mat_group(batch_std_labels, non_rele_gap=100.0, var_penalty=0.01, gain_base=2.0, gpu=False): """ Take into account the group information among documents, namely whether two documents are of the same standard relevance degree :param batch_std_labels: standard relevance labels :param non_re...
Take into account the group information among documents, namely whether two documents are of the same standard relevance degree :param batch_std_labels: standard relevance labels :param non_rele_gap: the gap between a relevant document and an irrelevant document :param var_penalty: variance pe...
torch_cost_mat_group
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def get_explicit_cost_mat(batch_std_labels, wass_para_dict=None, gpu=False): """ Initialize the cost matrix based on pre-defined (prior) knowledge :param batch_std_labels: :param wass_para_dict: :return: """ cost_type = wass_para_dict['cost_type'] if cost_type == 'p1': # |x-y| ...
Initialize the cost matrix based on pre-defined (prior) knowledge :param batch_std_labels: :param wass_para_dict: :return:
get_explicit_cost_mat
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def get_standard_normalized_histogram_ST(batch_std_labels, non_rele_as=0.0, adjust_softmax=True): """ Convert to a normalized histogram based on softmax The underlying trick is to down-weight the mass of non-relevant labels: treat them as one, then average the probability mass """ if adjust_softmax:...
Convert to a normalized histogram based on softmax The underlying trick is to down-weight the mass of non-relevant labels: treat them as one, then average the probability mass
get_standard_normalized_histogram_ST
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def get_standard_normalized_histogram_GN(batch_std_labels, gain_base=2.0): """ Convert to a normalized histogram based on gain values, i.e., each entry equals to gain_value/sum_gain_value :param batch_std_labels: :return: """ batch_std_gains = torch.pow(gain_base, batch_std_labels) - 1.0 bat...
Convert to a normalized histogram based on gain values, i.e., each entry equals to gain_value/sum_gain_value :param batch_std_labels: :return:
get_standard_normalized_histogram_GN
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def get_normalized_histograms(batch_std_labels=None, batch_preds=None, wass_dict_std_dists=None, qid=None, wass_para_dict=None, TL_AF=None): """ Convert both standard labels and predictions w.r.t. a query to normalized histograms """ smooth_type, norm_type = wass_para_dict['smooth_...
Convert both standard labels and predictions w.r.t. a query to normalized histograms
get_normalized_histograms
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wasserstein_cost_mat.py
MIT
def default_para_dict(self): """ Default parameter setting for WassRank. EntropicOT | SinkhornOT :return: """ self.wass_para_dict = dict(model_id=self.model_id, mode='SinkhornOT', sh_itr=20, lam=0.1, smooth_type='ST', norm_type='BothST', cost_ty...
Default parameter setting for WassRank. EntropicOT | SinkhornOT :return:
default_para_dict
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wassRank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wassRank.py
MIT
def grid_search(self): """ Iterator of parameter settings for WassRank """ if self.use_json: wass_choice_mode = self.json_dict['mode'] wass_choice_itr = self.json_dict['itr'] wass_choice_lam = self.json_dict['lam'] wass_cost_type = self.js...
Iterator of parameter settings for WassRank
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/listwise/wassrank/wassRank.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/listwise/wassrank/wassRank.py
MIT
def grid_search(self): """ Iterator of parameter settings for RankNet """ if self.use_json: choice_sigma = self.json_dict['sigma'] else: choice_sigma = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0 for sigma in choice_sigma: ...
Iterator of parameter settings for RankNet
grid_search
python
wildltr/ptranking
ptranking/ltr_adhoc/pairwise/ranknet.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/pairwise/ranknet.py
MIT
def rankMSE_loss_function(relevance_preds=None, std_labels=None): ''' Ranking loss based on mean square error TODO adjust output scale w.r.t. output layer activation function @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param b...
Ranking loss based on mean square error TODO adjust output scale w.r.t. output layer activation function @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standar...
rankMSE_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/pointwise/rank_mse.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/pointwise/rank_mse.py
MIT
def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' :param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents within a ltr_adhoc :param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents withi...
:param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents within a ltr_adhoc :param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents within a ltr_adhoc :return:
custom_loss_function
python
wildltr/ptranking
ptranking/ltr_adhoc/pointwise/rank_mse.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/pointwise/rank_mse.py
MIT
def batch_count(batch_std_labels=None, max_rele_grade=None, descending=False, gpu=False): """ Todo now an api is already provided by pytorch :param batch_std_labels: :param max_rele_grade: :param descending: :param gpu: :return: """ rele_grades = torch.arange(max_rele_grade+1).type(t...
Todo now an api is already provided by pytorch :param batch_std_labels: :param max_rele_grade: :param descending: :param gpu: :return:
batch_count
python
wildltr/ptranking
ptranking/ltr_adhoc/util/bin_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/bin_utils.py
MIT
def torch_batch_triu(batch_mats=None, k=0, pair_type='All', batch_std_labels=None, gpu=False, device=None): ''' Get unique document pairs being consistent with the specified pair_type. This function is used to avoid duplicate computation. All: pairs including both pairs of documents across different...
Get unique document pairs being consistent with the specified pair_type. This function is used to avoid duplicate computation. All: pairs including both pairs of documents across different relevance levels and pairs of documents having the same relevance level. NoTies: the pairs c...
torch_batch_triu
python
wildltr/ptranking
ptranking/ltr_adhoc/util/gather_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/gather_utils.py
MIT
def torch_triu_indice(k=0, pair_type='All', batch_label=None, gpu=False, device=None): ''' Get unique document pairs being consistent with the specified pair_type. This function is used to avoid duplicate computation. All: pairs including both pairs of documents across different relevance levels and...
Get unique document pairs being consistent with the specified pair_type. This function is used to avoid duplicate computation. All: pairs including both pairs of documents across different relevance levels and pairs of documents having the same relevance level. NoTies: the pairs...
torch_triu_indice
python
wildltr/ptranking
ptranking/ltr_adhoc/util/gather_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/gather_utils.py
MIT
def get_pairwise_comp_probs(batch_preds, batch_std_labels, sigma=None): ''' Get the predicted and standard probabilities p_ij which denotes d_i beats d_j @param batch_preds: @param batch_std_labels: @param sigma: @return: ''' # computing pairwise differences w.r.t. predictions, i.e., s_i...
Get the predicted and standard probabilities p_ij which denotes d_i beats d_j @param batch_preds: @param batch_std_labels: @param sigma: @return:
get_pairwise_comp_probs
python
wildltr/ptranking
ptranking/ltr_adhoc/util/lambda_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/lambda_utils.py
MIT
def get_one_hot_reprs(batch_stds, gpu=False): """ Get one-hot representation of batch ground-truth labels """ batch_size = batch_stds.size(0) hist_size = batch_stds.size(1) int_batch_stds = batch_stds.type(torch.cuda.LongTensor) if gpu else batch_stds.type(torch.LongTensor) hot_batch_stds = torch.c...
Get one-hot representation of batch ground-truth labels
get_one_hot_reprs
python
wildltr/ptranking
ptranking/ltr_adhoc/util/one_hot_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/one_hot_utils.py
MIT