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 arg_shuffle_ties(batch_rankings, descending=True, device=None): '''Shuffle ties, and return the corresponding indice ''' batch_size, ranking_size = batch_rankings.size() if batch_size > 1: list_rperms = [] for _ in range(batch_size): list_rperms.append(torch.randperm(ranking_...
Shuffle ties, and return the corresponding indice
arg_shuffle_ties
python
wildltr/ptranking
ptranking/ltr_adhoc/util/sampling_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/sampling_utils.py
MIT
def sample_ranking_PL(batch_preds, only_indices=True, temperature=1.0): ''' Sample one ranking per query based on Plackett-Luce model @param batch_preds: [batch_size, ranking_size] each row denotes the relevance predictions for documents associated with the same query @param only_indices: only return th...
Sample one ranking per query based on Plackett-Luce model @param batch_preds: [batch_size, ranking_size] each row denotes the relevance predictions for documents associated with the same query @param only_indices: only return the indices or not
sample_ranking_PL
python
wildltr/ptranking
ptranking/ltr_adhoc/util/sampling_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/sampling_utils.py
MIT
def sample_ranking_PL_gumbel_softmax(batch_preds, only_indices=True, temperature=1.0, device=None): ''' Sample a ranking based stochastic Plackett-Luce model, where gumble noise is added @param batch_preds: [batch_size, ranking_size] each row denotes the relevance predictions for documents associated with t...
Sample a ranking based stochastic Plackett-Luce model, where gumble noise is added @param batch_preds: [batch_size, ranking_size] each row denotes the relevance predictions for documents associated with the same query @param only_indices: only return the indices or not
sample_ranking_PL_gumbel_softmax
python
wildltr/ptranking
ptranking/ltr_adhoc/util/sampling_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adhoc/util/sampling_utils.py
MIT
def default_pointsf_para_dict(self): """ A default setting of the hyper-parameters of the stump neural scoring function for adversarial ltr. """ self.sf_para_dict = dict() self.sf_para_dict['sf_id'] = self.sf_id self.sf_para_dict['opt'] = 'Adam' # Adam | RMS | Adagrad self.sf_para_dict['lr'] = 0.001 # l...
A default setting of the hyper-parameters of the stump neural scoring function for adversarial ltr.
default_pointsf_para_dict
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_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'] eval_string = s2.join([s1.join(['epochs', str(epochs)])...
String identifier of eval-setting :param log: :return:
to_eval_setting_string
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def default_setting(self): """ A default setting for evaluation when performing adversarial ltr :param debug: :param data_id: :param dir_output: :return: """ do_log = False if self.debug else True do_validation, do_summary = True, False log_step = 1 epochs = 10 if self.debug else 50 vali_k = 5 ...
A default setting for evaluation when performing adversarial ltr :param debug: :param data_id: :param dir_output: :return:
default_setting
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def grid_search(self): """ Iterator of settings for evaluation when performing adversarial ltr """ if self.use_json: dir_output = self.json_dict['dir_output'] epochs = 5 if self.debug else self.json_dict['epochs'] do_validation, vali_k = self.json_dict['do_validation'], self.json_dict['vali_k'] cuto...
Iterator of settings for evaluation when performing adversarial ltr
grid_search
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def to_data_setting_string(self, log=False): """ String identifier of data-setting :param log: :return: """ data_dict = self.data_dict s1, s2 = (':', '\n') if log else ('_', '_') data_id, binary_rele = data_dict['data_id'], data_dict['binary_rele'] min_docs, min_rele, train_rough_batch_size, train_pr...
String identifier of data-setting :param log: :return:
to_data_setting_string
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def default_setting(self): """ A default setting for data loading when performing adversarial ltr """ unknown_as_zero = False binary_rele = False # using the original values train_presort, validation_presort, test_presort = True, True, True train_rough_batch_size, validation_rough_batch_size, test_rough_...
A default setting for data loading when performing adversarial ltr
default_setting
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def grid_search(self): """ Iterator of settings for data loading when performing adversarial ltr """ if self.use_json: scaler_id = self.json_dict['scaler_id'] choice_min_docs = self.json_dict['min_docs'] choice_min_rele = self.json_dict['min_rele'] choice_binary_rele = self.json_dict['binary_rele'] ...
Iterator of settings for data loading when performing adversarial ltr
grid_search
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ad_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ad_parameter.py
MIT
def check_consistency(self, data_dict, eval_dict, sf_para_dict): """ Check whether the settings are reasonable in the context of adversarial learning-to-rank """ ''' Part-1: data loading ''' assert 1 == data_dict['train_rough_batch_size'] # the required setting w.r.t. adversaria...
Check whether the settings are reasonable in the context of adversarial learning-to-rank
check_consistency
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ltr_adversarial.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ltr_adversarial.py
MIT
def get_ad_machine(self, eval_dict=None, data_dict=None, sf_para_dict=None, ad_para_dict=None): """ Initialize the adversarial model correspondingly. :param eval_dict: :param data_dict: :param sf_para_dict: :param ad_para_dict: :return: """ model_i...
Initialize the adversarial model correspondingly. :param eval_dict: :param data_dict: :param sf_para_dict: :param ad_para_dict: :return:
get_ad_machine
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ltr_adversarial.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ltr_adversarial.py
MIT
def ad_cv_eval(self, data_dict=None, eval_dict=None, ad_para_dict=None, sf_para_dict=None): """ Adversarial training and evaluation :param data_dict: :param eval_dict: :param ad_para_dict: :param sf_para_dict: :return: """ self.display_information(...
Adversarial training and evaluation :param data_dict: :param eval_dict: :param ad_para_dict: :param sf_para_dict: :return:
ad_cv_eval
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ltr_adversarial.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ltr_adversarial.py
MIT
def grid_run(self, debug=True, model_id=None, data_id=None, dir_data=None, dir_output=None, dir_json=None): """ Perform adversarial learning-to-rank based on grid search of optimal parameter setting """ if dir_json is not None: ad_data_eval_sf_json = dir_json + 'Ad_Data_Eval_...
Perform adversarial learning-to-rank based on grid search of optimal parameter setting
grid_run
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ltr_adversarial.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ltr_adversarial.py
MIT
def point_run(self, debug=False, model_id=None, sf_id=None, data_id=None, dir_data=None, dir_output=None): """ :param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return: """ self.set_eval_setting(debug=debug, dir_...
:param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return:
point_run
python
wildltr/ptranking
ptranking/ltr_adversarial/eval/ltr_adversarial.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/eval/ltr_adversarial.py
MIT
def __init__(self, eval_dict, data_dict, sf_para_dict=None, ad_para_dict=None, optimal_train=False, gpu=False, device=None): ''' :param optimal_train: training with supervised generator or discriminator ''' super(IRFGAN_List, self).__init__(eval_dict=eval_dict, data_dict=data_dict, gpu=g...
:param optimal_train: training with supervised generator or discriminator
__init__
python
wildltr/ptranking
ptranking/ltr_adversarial/listwise/irfgan_list.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/listwise/irfgan_list.py
MIT
def per_query_generation(self, qid=None, batch_ranking=None, batch_label=None, pos_and_neg=None, generator=None, samples_per_query=None, top_k=None, temperature=None): ''' :param pos_and_neg: corresponding to discriminator optimization or generator optimization ''' ...
:param pos_and_neg: corresponding to discriminator optimization or generator optimization
per_query_generation
python
wildltr/ptranking
ptranking/ltr_adversarial/listwise/irfgan_list.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/listwise/irfgan_list.py
MIT
def fill_global_buffer(self, train_data, dict_buffer=None): ''' Buffer the number of positive documents, and the number of non-positive documents per query ''' assert self.data_dict['train_presort'] is True # this is required for efficient truth exampling if self.data_dict['data_id'] in MSLETO...
Buffer the number of positive documents, and the number of non-positive documents per query
fill_global_buffer
python
wildltr/ptranking
ptranking/ltr_adversarial/pairwise/irfgan_pair.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pairwise/irfgan_pair.py
MIT
def mini_max_train(self, train_data=None, generator=None, discriminator=None, global_buffer=None): ''' Here it can not use the way of training like irgan-pair (still relying on single documents rather thank pairs), since ir-fgan requires to sample with two distributions. ''' stop...
Here it can not use the way of training like irgan-pair (still relying on single documents rather thank pairs), since ir-fgan requires to sample with two distributions.
mini_max_train
python
wildltr/ptranking
ptranking/ltr_adversarial/pairwise/irfgan_pair.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pairwise/irfgan_pair.py
MIT
def train_discriminator_generator_single_step(self, train_data=None, generator=None, discriminator=None, global_buffer=None): ''' Train both discriminator and generator with a single step per query ''' stop_training = False generator.train_mode()...
Train both discriminator and generator with a single step per query
train_discriminator_generator_single_step
python
wildltr/ptranking
ptranking/ltr_adversarial/pairwise/irfgan_pair.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pairwise/irfgan_pair.py
MIT
def __init__(self, eval_dict, data_dict, sf_para_dict=None, ad_para_dict=None, gpu=False, device=None): ''' :param sf_para_dict: :param temperature: according to the description around Eq-10, temperature is deployed, while it is not used within the provided code ''' super(IRGAN_P...
:param sf_para_dict: :param temperature: according to the description around Eq-10, temperature is deployed, while it is not used within the provided code
__init__
python
wildltr/ptranking
ptranking/ltr_adversarial/pairwise/irgan_pair.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pairwise/irgan_pair.py
MIT
def generate_data(self, train_data=None, generator=None, global_buffer=None): ''' Sampling for training discriminator This is a re-implementation as the released irgan-tensorflow, but it seems that this part of irgan-tensorflow is not consistent with the discription of the paper (i.e., t...
Sampling for training discriminator This is a re-implementation as the released irgan-tensorflow, but it seems that this part of irgan-tensorflow is not consistent with the discription of the paper (i.e., the description below Eq. 7)
generate_data
python
wildltr/ptranking
ptranking/ltr_adversarial/pairwise/irgan_pair.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pairwise/irgan_pair.py
MIT
def fill_global_buffer(self, train_data, dict_buffer=None): ''' Buffer the number of positive documents per query ''' assert self.data_dict['train_presort'] is True # this is required for efficient truth exampling for entry in train_data: qid, _, batch_label = entry[0], entry[1], e...
Buffer the number of positive documents per query
fill_global_buffer
python
wildltr/ptranking
ptranking/ltr_adversarial/pointwise/irfgan_point.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pointwise/irfgan_point.py
MIT
def __init__(self, eval_dict, data_dict, sf_para_dict=None, ad_para_dict=None, gpu=False, device=None): ''' :param ad_training_order: really matters, DG is preferred than GD ''' super(IRGAN_Point, self).__init__(eval_dict=eval_dict, data_dict=data_dict, gpu=gpu, device=device) '...
:param ad_training_order: really matters, DG is preferred than GD
__init__
python
wildltr/ptranking
ptranking/ltr_adversarial/pointwise/irgan_point.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/pointwise/irgan_point.py
MIT
def get_f_divergence_functions(f_div_str=None): ''' the activation function is chosen as a monotone increasing function ''' if 'TVar' == f_div_str: # Total variation def activation_f(v): return 0.5 * torch.tanh(v) def conjugate_f(t): return t elif 'KL' == f_...
the activation function is chosen as a monotone increasing function
get_f_divergence_functions
python
wildltr/ptranking
ptranking/ltr_adversarial/util/f_divergence.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/f_divergence.py
MIT
def gumbel_softmax(logits, samples_per_query, temperature=1.0, cuda=False, cuda_device=None): ''' :param logits: [1, ranking_size] :param num_samples_per_query: number of stochastic rankings to generate :param temperature: :return: ''' assert 1 == logits.size(0) and 2 == len(logits.size()) ...
:param logits: [1, ranking_size] :param num_samples_per_query: number of stochastic rankings to generate :param temperature: :return:
gumbel_softmax
python
wildltr/ptranking
ptranking/ltr_adversarial/util/list_sampling.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/list_sampling.py
MIT
def sample_ranking_PL_gumbel_softmax(batch_preds, num_sample_ranking=1, only_indices=True, temperature=1.0, gpu=False, device=None): ''' Sample a ranking based stochastic Plackett-Luce model, where gumble noise is added @param batch_preds: [1, ranking_size] vector of relevance predictions for documents asso...
Sample a ranking based stochastic Plackett-Luce model, where gumble noise is added @param batch_preds: [1, ranking_size] vector of relevance predictions for documents associated with the same query @param num_sample_ranking: number of rankings to sample @param only_indices: only return the indices or n...
sample_ranking_PL_gumbel_softmax
python
wildltr/ptranking
ptranking/ltr_adversarial/util/list_sampling.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/list_sampling.py
MIT
def arg_shuffle_ties(target_batch_stds, descending=True, gpu=False, device=None): ''' Shuffle ties, and return the corresponding indice ''' batch_size, ranking_size = target_batch_stds.size() if batch_size > 1: list_rperms = [] for _ in range(batch_size): list_rperms.append(torch...
Shuffle ties, and return the corresponding indice
arg_shuffle_ties
python
wildltr/ptranking
ptranking/ltr_adversarial/util/list_sampling.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/list_sampling.py
MIT
def get_weighted_clipped_pos_diffs(qid, sorted_std_labels, global_buffer=None): ''' Get total true pairs based on explicit labels. In particular, the difference values are discounted based on positions. ''' num_pos, num_explicit, num_neg_unk, num_unk, num_unique_labels = global_buffer[qid] mat_d...
Get total true pairs based on explicit labels. In particular, the difference values are discounted based on positions.
get_weighted_clipped_pos_diffs
python
wildltr/ptranking
ptranking/ltr_adversarial/util/pair_sampling.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/pair_sampling.py
MIT
def sample_pairs_BT(point_vals=None, num_pairs=None): ''' The probability of observing a pair of ordered documents is formulated based on Bradley-Terry model, i.e., p(d_i > d_j)=1/(1+exp(-delta(s_i - s_j))) ''' # the rank information is not taken into account, and all pairs are treated equally. #total_item...
The probability of observing a pair of ordered documents is formulated based on Bradley-Terry model, i.e., p(d_i > d_j)=1/(1+exp(-delta(s_i - s_j)))
sample_pairs_BT
python
wildltr/ptranking
ptranking/ltr_adversarial/util/pair_sampling.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_adversarial/util/pair_sampling.py
MIT
def ini_listsf(self, num_features=None, n_heads=2, encoder_layers=2, dropout=0.1, encoder_type=None, ff_dims=[256, 128, 64], out_dim=1, AF='R', TL_AF='GE', apply_tl_af=False, BN=True, bn_type=None, bn_affine=False): ''' Initialization the univariate scoring function...
Initialization the univariate scoring function for diversified ranking.
ini_listsf
python
wildltr/ptranking
ptranking/ltr_diversification/base/div_list_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/base/div_list_ranker.py
MIT
def get_diff_normal(self, batch_mus, batch_vars, batch_cocos=None): ''' The difference of two normal random variables is another normal random variable. In particular, we consider two cases: (1) correlated (2) independent. @param batch_mus: the predicted mean @param batch_vars: t...
The difference of two normal random variables is another normal random variable. In particular, we consider two cases: (1) correlated (2) independent. @param batch_mus: the predicted mean @param batch_vars: the predicted variance @param batch_cocos: the predicted correlation coe...
get_diff_normal
python
wildltr/ptranking
ptranking/ltr_diversification/base/div_mdn_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/base/div_mdn_ranker.py
MIT
def div_predict(self, q_repr, doc_reprs): ''' The relevance prediction. In the context of diversified ranking, the shape is interpreted as: @param q_repr: @param doc_reprs: @return: ''' if self.sf_id.endswith("co"): batch_mus, batch_vars, batch_cocos =...
The relevance prediction. In the context of diversified ranking, the shape is interpreted as: @param q_repr: @param doc_reprs: @return:
div_predict
python
wildltr/ptranking
ptranking/ltr_diversification/base/div_mdn_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/base/div_mdn_ranker.py
MIT
def default_pointsf_para_dict(self): """ The default setting of the hyper-parameters of the stump neural scoring function. """ self.sf_para_dict = dict() if self.use_json: opt = self.json_dict['opt'][0] lr = self.json_dict['lr'][0] pointsf_jso...
The default setting of the hyper-parameters of the stump neural scoring function.
default_pointsf_para_dict
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def default_listsf_para_dict(self): """ The default setting of the hyper-parameters of the permutation-equivariant neural scoring function. """ self.sf_para_dict = dict() if self.use_json: opt = self.json_dict['opt'][0] lr = self.json_dict['lr'][0] ...
The default setting of the hyper-parameters of the permutation-equivariant neural scoring function.
default_listsf_para_dict
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def default_setting(self): """ A default setting for evaluation when performing diversified ranking. :param debug: :param data_id: :param dir_output: :return: """ if self.use_json: dir_output = self.json_dict['dir_output'] epochs = ...
A default setting for evaluation when performing diversified ranking. :param debug: :param data_id: :param dir_output: :return:
default_setting
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def grid_search(self): """ Iterator of settings for evaluation when performing diversified ranking. """ if self.use_json: dir_output = self.json_dict['dir_output'] epochs = 5 if self.debug else self.json_dict['epochs'] do_validation = self.json_dict['...
Iterator of settings for evaluation when performing diversified ranking.
grid_search
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def to_data_setting_string(self, log=False): """ String identifier of data-setting :param log: :return: """ data_dict = self.data_dict setting_string, add_noise = data_dict['data_id'], data_dict['add_noise'] if add_noise: std_delta = data_dict[...
String identifier of data-setting :param log: :return:
to_data_setting_string
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def default_setting(self): """ A default setting for data loading when performing diversified ranking """ if self.use_json: add_noise = self.json_dict['add_noise'][0] std_delta = self.json_dict['std_delta'][0] if add_noise else None self.data_dict = di...
A default setting for data loading when performing diversified ranking
default_setting
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def grid_search(self): """ Iterator of settings for data loading when performing adversarial ltr """ if self.use_json: choice_add_noise = self.json_dict['add_noise'] choice_std_delta = self.json_dict['std_delta'] if True in choice_add_noise else None s...
Iterator of settings for data loading when performing adversarial ltr
grid_search
python
wildltr/ptranking
ptranking/ltr_diversification/eval/div_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/div_parameter.py
MIT
def load_data(self, eval_dict=None, data_dict=None, fold_k=None, discriminator=None): """ We note that it is impossible to perform processing over multiple queries, since q_doc_rele_mat may differ from query to query. @param eval_dict: @param data_dict: @param fold_k: ...
We note that it is impossible to perform processing over multiple queries, since q_doc_rele_mat may differ from query to query. @param eval_dict: @param data_dict: @param fold_k: @return:
load_data
python
wildltr/ptranking
ptranking/ltr_diversification/eval/ltr_diversification.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/ltr_diversification.py
MIT
def grid_run(self, debug=True, model_id=None, sf_id=None, data_id=None, dir_data=None, dir_output=None, dir_json=None): """ Perform diversified ranking based on grid search of optimal parameter setting """ if dir_json is not None: div_data_eval_sf_json = dir_json + 'Div_Data_...
Perform diversified ranking based on grid search of optimal parameter setting
grid_run
python
wildltr/ptranking
ptranking/ltr_diversification/eval/ltr_diversification.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/ltr_diversification.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): """ :param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return: """...
:param debug: :param model_id: :param data_id: :param dir_data: :param dir_output: :return:
point_run
python
wildltr/ptranking
ptranking/ltr_diversification/eval/ltr_diversification.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/eval/ltr_diversification.py
MIT
def get_approx_ranks(batch_preds, rt=None, device=None, q_doc_rele_mat=None): ''' get approximated rank positions: Equation-7 in the paper''' batch_pred_diffs = torch.unsqueeze(batch_preds, dim=2) - torch.unsqueeze(batch_preds, dim=1) # computing pairwise differences, i.e., Sij or Sxy batch_indicators = r...
get approximated rank positions: Equation-7 in the paper
get_approx_ranks
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/daletor.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/daletor.py
MIT
def alphaDCG_as_a_loss(batch_preds=None, q_doc_rele_mat=None, rt=10, device=None, alpha=0.5, top_k=10): """ There are two ways to formulate the loss: (1) using the ideal order; (2) using the predicted order (TBA) """ batch_hat_pis, prior_cover_cnts = get_approx_ranks(batch_preds, rt=rt, device=device, q...
There are two ways to formulate the loss: (1) using the ideal order; (2) using the predicted order (TBA)
alphaDCG_as_a_loss
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/daletor.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/daletor.py
MIT
def div_custom_loss_function(self, batch_preds, q_doc_rele_mat, **kwargs): ''' :param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents within a ltr_adhoc :param batch_stds: [batch, ranking_size] each row represents the standard relevance grades for d...
:param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents within a ltr_adhoc :param batch_stds: [batch, ranking_size] each row represents the standard relevance grades for documents within a ltr_adhoc :return:
div_custom_loss_function
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/daletor.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/daletor.py
MIT
def default_para_dict(self): """ Default parameter setting for DALETOR. Here rt (reversed T) corresponds to 1/T in paper. :return: """ if self.use_json: top_k = self.json_dict['top_k'][0] rt = self.json_dict['rt'][0] # corresponds to 1/T in paper ...
Default parameter setting for DALETOR. Here rt (reversed T) corresponds to 1/T in paper. :return:
default_para_dict
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/daletor.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/daletor.py
MIT
def alpha_dcg_as_a_loss(top_k=None, batch_mus=None, batch_vars=None, batch_cocos=None, q_doc_rele_mat=None, opt_ideal=True, presort=False, beta=0.5, const=False, const_var=None): ''' Alpha_nDCG as the optimization objective. @param top_k: @param batch_mus: @param batch_vars: ...
Alpha_nDCG as the optimization objective. @param top_k: @param batch_mus: @param batch_vars: @param batch_cocos: @param q_doc_rele_mat: @param opt_ideal: @param presort: @param beta: @return:
alpha_dcg_as_a_loss
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
MIT
def err_ia_as_a_loss(top_k=None, batch_mus=None, batch_vars=None, batch_cocos=None, q_doc_rele_mat=None, opt_ideal=True, presort=False, max_label=1.0, device=None, const=False, const_var=None): ''' ERR-IA as the optimization objective. @param top_k: @param batch_mus: @param batc...
ERR-IA as the optimization objective. @param top_k: @param batch_mus: @param batch_vars: @param batch_cocos: @param q_doc_rele_mat: @param opt_ideal: @param presort: @return:
err_ia_as_a_loss
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
MIT
def div_custom_loss_function(self, batch_mus, batch_vars, q_doc_rele_mat, **kwargs): ''' In the context of SRD, batch_size is commonly 1. @param batch_mus: [batch_size, ranking_size] each row represents the mean predictions for documents associated with the same query @param batch_vars: ...
In the context of SRD, batch_size is commonly 1. @param batch_mus: [batch_size, ranking_size] each row represents the mean predictions for documents associated with the same query @param batch_vars: [batch_size, ranking_size] each row represents the variance predictions for documents associated...
div_custom_loss_function
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
MIT
def grid_search(self): """ Iterator of parameter settings for MiDeExpectedUtility """ if self.use_json: choice_topk = self.json_dict['top_k'] choice_opt_id = self.json_dict['opt_id'] choice_K = self.json_dict['K'] choice_cluster = self.json_dict['cluster']...
Iterator of parameter settings for MiDeExpectedUtility
grid_search
python
wildltr/ptranking
ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/score_and_sort/div_prob_ranker.py
MIT
def deploy_1st_stage_div_discriminating(discriminator, rerank_k, q_repr, doc_reprs, gpu, device): ''' Perform 1st-stage ranking as a discriminating process. ''' sys_rele_preds = discriminator.div_predict(q_repr, doc_reprs) # [1, ranking_size] if gpu: sys_rele_preds = sys_rele_preds.cpu() _, sys_sorted...
Perform 1st-stage ranking as a discriminating process.
deploy_1st_stage_div_discriminating
python
wildltr/ptranking
ptranking/ltr_diversification/util/div_data.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/div_data.py
MIT
def get_pairwise_comp_probs(batch_preds, std_q_doc_rele_mat, sigma=None): ''' Get the predicted and standard probabilities p_ij which denotes d_i beats d_j, the subtopic labels are aggregated. @param batch_preds: @param batch_std_labels: @param sigma: @return: ''' # standard pairwise dif...
Get the predicted and standard probabilities p_ij which denotes d_i beats d_j, the subtopic labels are aggregated. @param batch_preds: @param batch_std_labels: @param sigma: @return:
get_pairwise_comp_probs
python
wildltr/ptranking
ptranking/ltr_diversification/util/div_lambda_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/div_lambda_utils.py
MIT
def get_prob_pairwise_comp_probs(batch_pairsub_mus, batch_pairsub_vars, q_doc_rele_mat): ''' The difference of two normal random variables is another normal random variable. pairsub_mu & pairsub_var denote the corresponding mean & variance of the difference of two normal random variables p_ij denotes th...
The difference of two normal random variables is another normal random variable. pairsub_mu & pairsub_var denote the corresponding mean & variance of the difference of two normal random variables p_ij denotes the probability that d_i beats d_j @param batch_pairsub_mus: @param batch_pairsub_vars: ...
get_prob_pairwise_comp_probs
python
wildltr/ptranking
ptranking/ltr_diversification/util/div_lambda_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/div_lambda_utils.py
MIT
def get_diff_normal(batch_mus, batch_vars, batch_cocos=None): ''' The difference of two normal random variables is another normal random variable. In particular, we consider two cases: (1) correlated (2) independent. @param batch_mus: the predicted mean @param batch_vars: the predicted variance ...
The difference of two normal random variables is another normal random variable. In particular, we consider two cases: (1) correlated (2) independent. @param batch_mus: the predicted mean @param batch_vars: the predicted variance @param batch_cocos: the predicted correlation coefficient in [-1, 1],...
get_diff_normal
python
wildltr/ptranking
ptranking/ltr_diversification/util/prob_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/prob_utils.py
MIT
def get_diff_normal_resort(batch_mus, batch_vars, batch_cocos=None, batch_resort_inds=None): ''' Compared with get_diff_normal(), resort is conducted first. ''' batch_resorted_mus = torch.gather(batch_mus, dim=1, index=batch_resort_inds) batch_resorted_vars = torch.gather(batch_vars, dim=1, index=ba...
Compared with get_diff_normal(), resort is conducted first.
get_diff_normal_resort
python
wildltr/ptranking
ptranking/ltr_diversification/util/prob_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/prob_utils.py
MIT
def neg_log_likelihood(batch_pairsub_mus, batch_pairsub_vars, top_k=None, device=None): ''' Compute the negative log-likelihood w.r.t. rankings, where the likelihood is formulated as the joint probability of consistent pairwise comparisons. @param batch_pairsub_mus: mean w.r.t. a pair comparison @pa...
Compute the negative log-likelihood w.r.t. rankings, where the likelihood is formulated as the joint probability of consistent pairwise comparisons. @param batch_pairsub_mus: mean w.r.t. a pair comparison @param batch_pairsub_vars: variance w.r.t. a pair comparison @return:
neg_log_likelihood
python
wildltr/ptranking
ptranking/ltr_diversification/util/prob_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/prob_utils.py
MIT
def batch_cosine_similarity(x1, x2=None, eps=1e-8): ''' :param x1: [batch_size, num_docs, num_features] :param x2: the same shape or None :param eps: :return: ''' x2 = x1 if x2 is None else x2 w1 = x1.norm(p=2, dim=2, keepdim=True) #print('w1', w1.size(), '\n', w1) w2 = w1 if x2 ...
:param x1: [batch_size, num_docs, num_features] :param x2: the same shape or None :param eps: :return:
batch_cosine_similarity
python
wildltr/ptranking
ptranking/ltr_diversification/util/sim_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_diversification/util/sim_utils.py
MIT
def check_consistency(self, data_dict, eval_dict): """ Check whether the settings are reasonable in the context of gbdt learning-to-rank """ ''' Part-1: data loading ''' if data_dict['data_id'] == 'Istella': assert eval_dict['do_validation'] is not True # since ther...
Check whether the settings are reasonable in the context of gbdt learning-to-rank
check_consistency
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def setup_output(self, data_dict=None, eval_dict=None): """ Determine the output. :param data_dict: :param eval_dict: :return: """ dir_output, grid_search, mask_label = eval_dict['dir_output'], eval_dict['grid_search'],\ ...
Determine the output. :param data_dict: :param eval_dict: :return:
setup_output
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def result_to_str(self, list_scores=None, list_cutoffs=None, split_str=', ', metric_str=None): """ Convert metric results to a string :param list_scores: :param list_cutoffs: :param split_str: :param metric_str: :return: """ list_str = [] f...
Convert metric results to a string :param list_scores: :param list_cutoffs: :param split_str: :param metric_str: :return:
result_to_str
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def cal_metric_at_ks(self, model_id, all_std_labels=None, all_preds=None, group=None, ks=[1, 3, 5, 10], label_type=None): """ Compute metric values with different cutoff values :param model: :param all_std_labels: :param all_preds: :param group: :param ks: ...
Compute metric values with different cutoff values :param model: :param all_std_labels: :param all_preds: :param group: :param ks: :return:
cal_metric_at_ks
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def setup_eval(self, data_dict, eval_dict): """ Perform some checks, and revise some setting due to the debug mode :param data_dict: :param eval_dict: :return: """ # required setting to be consistent with the dataset if data_dict['data_id'] == 'Istella': ...
Perform some checks, and revise some setting due to the debug mode :param data_dict: :param eval_dict: :return:
setup_eval
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def update_save_model_dir(self, data_dict=None, fold_k=None): """ Update the directory for saving model file when there are multiple folds :param data_dict: :param fold_k: :return: """ if data_dict['data_id'] in MSLETOR or data_dict['data_id'] in MSLRWEB: ...
Update the directory for saving model file when there are multiple folds :param data_dict: :param fold_k: :return:
update_save_model_dir
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def kfold_cv_eval(self, data_dict=None, eval_dict=None, model_para_dict=None): """ Evaluation based on k-fold cross validation if multiple folds exist :param data_dict: :param eval_dict: :param model_para_dict: :return: """ self.display_information(data_di...
Evaluation based on k-fold cross validation if multiple folds exist :param data_dict: :param eval_dict: :param model_para_dict: :return:
kfold_cv_eval
python
wildltr/ptranking
ptranking/ltr_tree/eval/ltr_tree.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/ltr_tree.py
MIT
def default_setting(self): """ A default setting for data loading when running lambdaMART """ scaler_id = None unknown_as_zero = True if self.data_id in MSLETOR_SEMI else False # since lambdaMART is a supervised method binary_rele = False # using the original values ...
A default setting for data loading when running lambdaMART
default_setting
python
wildltr/ptranking
ptranking/ltr_tree/eval/tree_parameter.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/eval/tree_parameter.py
MIT
def default_para_dict(self): """ Default parameter setting for LambdaMART :return: """ # for custom setting #custom_dict = dict(custom=False, custom_obj_id='lambdarank', use_LGBMRanker=True) # custom_dict = dict(custom=False, custom_obj_id=None) # common ...
Default parameter setting for LambdaMART :return:
default_para_dict
python
wildltr/ptranking
ptranking/ltr_tree/lambdamart/lightgbm_lambdaMART.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/lambdamart/lightgbm_lambdaMART.py
MIT
def get_delta_ndcg(ideally_sorted_labels, labels_sorted_via_preds): ''' Delta-nDCG w.r.t. pairwise swapping of the currently predicted ranking ''' idcg = ideal_dcg(ideally_sorted_labels) # ideal discount cumulative gains gains = np.power(2.0, labels_sorted_via_preds) - 1.0 n_gains = gains / idc...
Delta-nDCG w.r.t. pairwise swapping of the currently predicted ranking
get_delta_ndcg
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def per_query_gradient_hessian_lambda(preds=None, labels=None, first_order=False, weighting=False, weighting_type='DeltaNDCG', pair_type='NoTies', epsilon=1.0): ''' Compute the corresponding gradient & hessian cf. LightGBM https://github.com/microsoft/LightGBM/blob/master/src/objective/rank_objective.hpp ...
Compute the corresponding gradient & hessian cf. LightGBM https://github.com/microsoft/LightGBM/blob/master/src/objective/rank_objective.hpp cf. XGBoost https://github.com/dmlc/xgboost/blob/master/src/objective/rank_obj.cc :param preds: 1-dimension predicted scores :param labels: 1-dimension gro...
per_query_gradient_hessian_lambda
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def lightgbm_custom_obj_ranknet(labels=None, preds=None, group=None): """ :param labels: numpy.ndarray of shape (size_data, ) :param preds: :param group: # numpy.ndarray of shape (num_queries, ) :return: """ size_data = len(labels) if FIRST_ORDER: all_grad, all_hess = np.zeros((s...
:param labels: numpy.ndarray of shape (size_data, ) :param preds: :param group: # numpy.ndarray of shape (num_queries, ) :return:
lightgbm_custom_obj_ranknet
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def lightgbm_custom_obj_ranknet_fobj(preds, train_data): ''' The traditional ranknet :param preds: numpy.ndarray of shape (size_data, ) :param train_data: :return: ''' all_labels = train_data.get_label() # numpy.ndarray of shape (size_data, ) group = train_data.get_group() # nu...
The traditional ranknet :param preds: numpy.ndarray of shape (size_data, ) :param train_data: :return:
lightgbm_custom_obj_ranknet_fobj
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def lightgbm_custom_obj_lambdarank(labels=None, preds=None, group=None): """ :param labels: numpy.ndarray of shape (size_data, ) :param preds: :param group: numpy.ndarray of shape (num_queries, ) :return: """ size_data = len(labels) if FIRST_ORDER: all_grad, all_hess = np.zeros(...
:param labels: numpy.ndarray of shape (size_data, ) :param preds: :param group: numpy.ndarray of shape (num_queries, ) :return:
lightgbm_custom_obj_lambdarank
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def lightgbm_custom_obj_lambdarank_fobj(preds, train_data): ''' :param preds: numpy.ndarray of shape (size_data, ) :param train_data: :return: ''' all_labels = train_data.get_label() # numpy.ndarray of shape (size_data, ) group = train_data.get_group() # numpy.ndarray of shape (n...
:param preds: numpy.ndarray of shape (size_data, ) :param train_data: :return:
lightgbm_custom_obj_lambdarank_fobj
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def lightgbm_custom_obj_listnet(labels=None, preds=None, group=None): """ :param labels: numpy.ndarray of shape (size_data, ) :param preds: numpy.ndarray of shape (size_data, ) :param group: numpy.ndarray of shape (num_queries, ) :return: """ size_data = len(labels) if FIRST_ORDER: ...
:param labels: numpy.ndarray of shape (size_data, ) :param preds: numpy.ndarray of shape (size_data, ) :param group: numpy.ndarray of shape (num_queries, ) :return:
lightgbm_custom_obj_listnet
python
wildltr/ptranking
ptranking/ltr_tree/util/lightgbm_util.py
https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/util/lightgbm_util.py
MIT
def get_delta_ndcg(batch_ideal_rankings, batch_predict_rankings, label_type=LABEL_TYPE.MultiLabel, device='cpu'): ''' Delta-nDCG w.r.t. pairwise swapping of the currently predicted ltr_adhoc :param batch_ideal_rankings: the standard labels sorted in a descending order :param batch_predicted_rankings: th...
Delta-nDCG w.r.t. pairwise swapping of the currently predicted ltr_adhoc :param batch_ideal_rankings: the standard labels sorted in a descending order :param batch_predicted_rankings: the standard labels sorted based on the corresponding predictions :return:
get_delta_ndcg
python
wildltr/ptranking
ptranking/metric/metric_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/metric_utils.py
MIT
def metric_results_to_string(list_scores=None, list_cutoffs=None, split_str=', ', metric='nDCG'): """ Convert metric results to a string representation :param list_scores: :param list_cutoffs: :param split_str: :return: """ list_str = [] for i in range(len(list_scores)): list...
Convert metric results to a string representation :param list_scores: :param list_cutoffs: :param split_str: :return:
metric_results_to_string
python
wildltr/ptranking
ptranking/metric/metric_utils.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/metric_utils.py
MIT
def torch_precision_at_k(batch_predict_rankings, k=None, device='cpu'): ''' Precision at k :param batch_predict_rankings: [batch_size, ranking_size] each ranking consists of labels corresponding to the ranked predictions :param k: cutoff value ''' max_cutoff = batch_predict_rankings.size(1) used_cutoff = min(max_...
Precision at k :param batch_predict_rankings: [batch_size, ranking_size] each ranking consists of labels corresponding to the ranked predictions :param k: cutoff value
torch_precision_at_k
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def torch_precision_at_ks(batch_predict_rankings, ks=None, device='cpu'): ''' Precision at ks :param batch_predict_rankings: [batch_size, ranking_size] each ranking consists of labels corresponding to the ranked predictions :param ks: cutoff values :return: [batch_size, len(ks)] ''' valid_max_cutoff = batch_predi...
Precision at ks :param batch_predict_rankings: [batch_size, ranking_size] each ranking consists of labels corresponding to the ranked predictions :param ks: cutoff values :return: [batch_size, len(ks)]
torch_precision_at_ks
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def torch_ap_at_k(batch_predict_rankings, batch_ideal_rankings, k=None, device='cpu'): ''' AP(average precision) at ks (i.e., different cutoff values) :param batch_ideal_rankings: [batch_size, ranking_size] the ideal ltr_adhoc of labels :param batch_predict_rankings: [batch_size, ranking_size] system's predicted lt...
AP(average precision) at ks (i.e., different cutoff values) :param batch_ideal_rankings: [batch_size, ranking_size] the ideal ltr_adhoc of labels :param batch_predict_rankings: [batch_size, ranking_size] system's predicted ltr_adhoc of labels in a descending order :param ks: :return: [batch_size, len(ks)]
torch_ap_at_k
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def torch_nerr_at_ks(batch_predict_rankings, batch_ideal_rankings, ks=None, device='cpu', label_type=LABEL_TYPE.MultiLabel, max_label=None): ''' :param batch_predict_rankings: [batch_size, ranking_size] the standard labels sorted in descending order according to predicted relevance scores :param ks: :return: [batch...
:param batch_predict_rankings: [batch_size, ranking_size] the standard labels sorted in descending order according to predicted relevance scores :param ks: :return: [batch_size, len(ks)]
torch_nerr_at_ks
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def torch_dcg_at_k(batch_rankings, cutoff=None, label_type=LABEL_TYPE.MultiLabel, device='cpu'): ''' ICML-nDCG, which places stronger emphasis on retrieving relevant documents :param batch_rankings: [batch_size, ranking_size] rankings of labels (either standard or predicted by a system) :param cutoff: the cutoff po...
ICML-nDCG, which places stronger emphasis on retrieving relevant documents :param batch_rankings: [batch_size, ranking_size] rankings of labels (either standard or predicted by a system) :param cutoff: the cutoff position :param label_type: either the case of multi-level relevance or the case of listwise int-value...
torch_dcg_at_k
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def torch_dcg_at_ks(batch_rankings, max_cutoff, label_type=LABEL_TYPE.MultiLabel, device='cpu'): ''' :param batch_rankings: [batch_size, ranking_size] rankings of labels (either standard or predicted by a system) :param max_cutoff: the maximum cutoff value :param label_type: either the case of multi-level relevance...
:param batch_rankings: [batch_size, ranking_size] rankings of labels (either standard or predicted by a system) :param max_cutoff: the maximum cutoff value :param label_type: either the case of multi-level relevance or the case of listwise int-value, e.g., MQ2007-list :return: [batch_size, max_cutoff] cumulative g...
torch_dcg_at_ks
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def np_metric_at_ks(ranker=None, test_Qs=None, ks=[1, 5, 10], label_type=LABEL_TYPE.MultiLabel, max_rele_level=None, gpu=False, device=None): ''' There is no check based on the assumption (say light_filtering() is called) that each test instance Q includes at least k(k=max(ks)) documents, and at least one relevant d...
There is no check based on the assumption (say light_filtering() is called) that each test instance Q includes at least k(k=max(ks)) documents, and at least one relevant document. Or there will be errors.
np_metric_at_ks
python
wildltr/ptranking
ptranking/metric/adhoc/adhoc_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/adhoc/adhoc_metric.py
MIT
def precision_as_opt_objective(top_k=None, batch_smooth_ranks=None, batch_std_labels=None, presort=False, opt_ideal=False, device=None): ''' Precision expectation maximization. @param top_k: only use the top-k results if not None @param batch_std_labels: @param presort...
Precision expectation maximization. @param top_k: only use the top-k results if not None @param batch_std_labels: @param presort: whether the standard labels are already sorted in descending order or not @param opt_ideal: optimise the ideal ranking or sort results each time @return:
precision_as_opt_objective
python
wildltr/ptranking
ptranking/metric/smooth_metric/metric_as_opt_objective.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/smooth_metric/metric_as_opt_objective.py
MIT
def get_delta_alpha_dcg(ideal_q_doc_rele_mat=None, sys_q_doc_rele_mat=None, alpha=0.5, device='cpu', normalization=True): ''' Get the delta-nDCG w.r.t. pairwise swapping of the currently predicted order. @param ideal_q_doc_rele_mat: the standard labels sorted in an ideal order @param sys_q_doc_rele_mat:...
Get the delta-nDCG w.r.t. pairwise swapping of the currently predicted order. @param ideal_q_doc_rele_mat: the standard labels sorted in an ideal order @param sys_q_doc_rele_mat: the standard labels sorted based on the corresponding predictions @param alpha: @param device: @return:
get_delta_alpha_dcg
python
wildltr/ptranking
ptranking/metric/srd/diversity_metric.py
https://github.com/wildltr/ptranking/blob/master/ptranking/metric/srd/diversity_metric.py
MIT
def np_shuffle_ties(vec, descending=True): ''' namely, randomly permuate ties :param vec: :param descending: the sorting order w.r.t. the input vec :return: ''' if len(vec.shape) > 1: raise NotImplementedError else: length = vec.shape[0] perm = np.random.permutati...
namely, randomly permuate ties :param vec: :param descending: the sorting order w.r.t. the input vec :return:
np_shuffle_ties
python
wildltr/ptranking
ptranking/utils/numpy/np_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/numpy/np_extensions.py
MIT
def np_arg_shuffle_ties(vec, descending=True): ''' the same as np_shuffle_ties, but return the corresponding indice ''' if len(vec.shape) > 1: raise NotImplementedError else: length = vec.shape[0] perm = np.random.permutation(length) if descending: sorted_shuffled...
the same as np_shuffle_ties, but return the corresponding indice
np_arg_shuffle_ties
python
wildltr/ptranking
ptranking/utils/numpy/np_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/numpy/np_extensions.py
MIT
def np_plackett_luce_sampling(items, probs, softmaxed=False): ''' sample a ltr_adhoc based on the Plackett-Luce model :param vec: a vector of values, the higher, the more possible the corresponding entry will be sampled :return: the indice of the corresponding ltr_adhoc ''' if softmaxed: ...
sample a ltr_adhoc based on the Plackett-Luce model :param vec: a vector of values, the higher, the more possible the corresponding entry will be sampled :return: the indice of the corresponding ltr_adhoc
np_plackett_luce_sampling
python
wildltr/ptranking
ptranking/utils/numpy/np_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/numpy/np_extensions.py
MIT
def arg_shuffle_ties(vec, descending=True): ''' the same as shuffle_ties, but return the corresponding indice ''' if len(vec.size()) > 1: raise NotImplementedError else: length = vec.size()[0] perm = torch.randperm(length) sorted_shuffled_vec_inds = torch.argsort(vec[perm], d...
the same as shuffle_ties, but return the corresponding indice
arg_shuffle_ties
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def soft_rank_sampling(loc, covariance_matrix=None, inds_style=True, descending=True): ''' :param loc: mean of the distribution :param covariance_matrix: positive-definite covariance matrix :param inds_style: true means the indice leading to the ltr_adhoc :return: ''' m = MultivariateNormal(...
:param loc: mean of the distribution :param covariance_matrix: positive-definite covariance matrix :param inds_style: true means the indice leading to the ltr_adhoc :return:
soft_rank_sampling
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def forward(ctx, MU, sigma, gpu): ''' :param ctx: :param mu: :param sigma: a float value :return: ''' #print('MU', MU) tmp_MU = MU.detach() tmp_MU = tmp_MU.view(1, -1) np_MU = tmp_MU.cpu().numpy() if gpu else tmp_MU.numpy() #print('...
:param ctx: :param mu: :param sigma: a float value :return:
forward
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def sinkhorn_2D(x, num_iter=5): ''' Sinkhorn (1964) showed that if X is a positive square matrix, there exist positive diagonal matrices D1 and D2 such that D1XD2 is doubly stochastic. The method of proof is based on an iterative procedure of alternatively normalizing the rows and columns of X. :param x...
Sinkhorn (1964) showed that if X is a positive square matrix, there exist positive diagonal matrices D1 and D2 such that D1XD2 is doubly stochastic. The method of proof is based on an iterative procedure of alternatively normalizing the rows and columns of X. :param x: the given positive square matrix
sinkhorn_2D
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def logsumexp(inputs, dim=None, keepdim=False): """Numerically stable logsumexp. Args: inputs: A Variable with any shape. dim: An integer. keepdim: A boolean. Returns: Equivalent of log(sum(exp(inputs), dim=dim, keepdim=keepdim)). """ # For a 1-D array x (any array ...
Numerically stable logsumexp. Args: inputs: A Variable with any shape. dim: An integer. keepdim: A boolean. Returns: Equivalent of log(sum(exp(inputs), dim=dim, keepdim=keepdim)).
logsumexp
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def sinkhorn_batch_(batch_x, num_iter=20, eps=1e-10, tau=0.05): ''' Temperature (tau) -controlled Sinkhorn layer. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via ...
Temperature (tau) -controlled Sinkhorn layer. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity, ...
sinkhorn_batch_
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def pl_normalize(batch_scores=None): ''' Normalization based on the 'Plackett_Luce' model :param batch_scores: [batch, ranking_size] :return: the i-th entry represents the probability of being ranked at the i-th position ''' m, _ = torch.max(batch_scores, dim=1, keepdim=True) # for higher stabi...
Normalization based on the 'Plackett_Luce' model :param batch_scores: [batch, ranking_size] :return: the i-th entry represents the probability of being ranked at the i-th position
pl_normalize
python
wildltr/ptranking
ptranking/utils/pytorch/pt_extensions.py
https://github.com/wildltr/ptranking/blob/master/ptranking/utils/pytorch/pt_extensions.py
MIT
def get_doc_num(dataset): ''' compute the number of documents in a dataset ''' doc_num = 0 for qid, torch_batch_rankings, torch_batch_std_labels in dataset: doc_num += torch_batch_std_labels.size(1) return doc_num
compute the number of documents in a dataset
get_doc_num
python
wildltr/ptranking
testing/data/testing_data_utils.py
https://github.com/wildltr/ptranking/blob/master/testing/data/testing_data_utils.py
MIT
def get_min_max_docs(train_dataset, vali_dataset, test_dataset, semi_supervised=False): ''' get the minimum / maximum number of documents per query ''' min_doc = 10000000 max_doc = 0 sum_rele = 0 if semi_supervised: sum_unknown = 0 for qid, torch_batch_rankings, torch_batch_std_labels i...
get the minimum / maximum number of documents per query
get_min_max_docs
python
wildltr/ptranking
testing/data/testing_data_utils.py
https://github.com/wildltr/ptranking/blob/master/testing/data/testing_data_utils.py
MIT
def get_min_max_feature(train_dataset, vali_dataset, test_dataset): ''' get the minimum / maximum feature values in a dataset ''' min_f = 0 max_f = 1000 for qid, torch_batch_rankings, torch_batch_std_labels in train_dataset: mav = torch.max(torch_batch_rankings) if torch.isinf(mav): ...
get the minimum / maximum feature values in a dataset
get_min_max_feature
python
wildltr/ptranking
testing/data/testing_data_utils.py
https://github.com/wildltr/ptranking/blob/master/testing/data/testing_data_utils.py
MIT
def check_dataset_statistics(data_id, dir_data, buffer=False): ''' Get the basic statistics on the specified dataset ''' if data_id in YAHOO_LTR: data_prefix = dir_data + data_id.lower() + '.' file_train, file_vali, file_test = data_prefix + 'train.txt', data_prefix + 'valid.txt', data_p...
Get the basic statistics on the specified dataset
check_dataset_statistics
python
wildltr/ptranking
testing/data/testing_data_utils.py
https://github.com/wildltr/ptranking/blob/master/testing/data/testing_data_utils.py
MIT
def test_ap(): ''' todo-as-note: the denominator should be carefully checked when using AP@k ''' # here we assume that there five relevant documents, but the system just retrieves three of them sys_sorted_labels = torch.Tensor([1.0, 0.0, 1.0, 0.0, 1.0]) std_sorted_labels = torch.Tensor([1.0, 1.0, 1.0, 1...
todo-as-note: the denominator should be carefully checked when using AP@k
test_ap
python
wildltr/ptranking
testing/metric/testing_metric.py
https://github.com/wildltr/ptranking/blob/master/testing/metric/testing_metric.py
MIT