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 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 point_run(self, debug=False, model_id=None, data_id=None, dir_data=None, dir_output=None):
"""
Perform one-time run based on given setting.
:param debug:
:param model_id:
:param data_id:
:param dir_data:
:param dir_output:
:return:
"""
... |
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_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 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 ('_', '_')
early_stop_or_boost_round, do_validation = eval_dict['early_stop_or_boost_ro... |
String identifier of eval-setting
:param log:
:return:
| to_eval_setting_string | 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 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_tree/lambdamart/lightgbm_lambdaMART.py | https://github.com/wildltr/ptranking/blob/master/ptranking/ltr_tree/lambdamart/lightgbm_lambdaMART.py | MIT |
def grid_search(self):
"""
Iterator of parameter settings for LambdaRank
"""
# for custom setting
#custom_dict = dict(custom=False, custom_obj_id='lambdarank', use_LGBMRanker=False)
custom_dict = dict(custom=False, custom_obj_id=None)
if self.use_json:
... |
Iterator of parameter settings for LambdaRank
| grid_search | 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 triu_indice(k=1, pair_type='NoTies', labels=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
pairs of docume... |
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... | triu_indice | 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(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 per_query_gradient_hessian_listnet(preds=None, labels=None, gain_type='Power', first_order=False):
'''
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... |
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_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 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 lightgbm_custom_obj_listnet_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 (num_... |
:param preds: numpy.ndarray of shape (size_data, )
:param train_data:
:return:
| lightgbm_custom_obj_listnet_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 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_ap_at_ks(batch_predict_rankings, batch_ideal_rankings, ks=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 ... |
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_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_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 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.size()) > 1:
raise NotImplementedError
else:
length = vec.size()[0]
perm = torch.randperm(lengt... |
namely, randomly permuate ties
:param vec:
:param descending: the sorting order w.r.t. the input vec
:return:
| 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 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 plackett_luce_sampling(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:
inds = to... |
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
| plackett_luce_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 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 |
def run(
self,
times=1,
models=None,
dataset="Alpha360",
universe="",
exclude=False,
qlib_uri: str = "git+https://github.com/microsoft/qlib#egg=pyqlib",
exp_folder_name: str = "run_all_model_records",
wait_before_rm_env: bool = False,
wait_... |
Please be aware that this function can only work under Linux. MacOS and Windows will be supported in the future.
Any PR to enhance this method is highly welcomed. Besides, this script doesn't support parallel running the same model
for multiple times, and this will be fixed in the future develo... | run | python | microsoft/qlib | examples/run_all_model.py | https://github.com/microsoft/qlib/blob/master/examples/run_all_model.py | MIT |
def process_qlib_data(df, dataset, fillna=False):
"""Prepare data to fit the TFT model.
Args:
df: Original DataFrame.
fillna: Whether to fill the data with the mean values.
Returns:
Transformed DataFrame.
"""
# Several features selected manually
feature_col = DATASET_SETTING... | Prepare data to fit the TFT model.
Args:
df: Original DataFrame.
fillna: Whether to fill the data with the mean values.
Returns:
Transformed DataFrame.
| process_qlib_data | python | microsoft/qlib | examples/benchmarks/TFT/tft.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py | MIT |
def process_predicted(df, col_name):
"""Transform the TFT predicted data into Qlib format.
Args:
df: Original DataFrame.
fillna: New column name.
Returns:
Transformed DataFrame.
"""
df_res = df.copy()
df_res = df_res.rename(columns={"forecast_time": "datetime", "identifier":... | Transform the TFT predicted data into Qlib format.
Args:
df: Original DataFrame.
fillna: New column name.
Returns:
Transformed DataFrame.
| process_predicted | python | microsoft/qlib | examples/benchmarks/TFT/tft.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py | MIT |
def to_pickle(self, path: Union[Path, str]):
"""
Tensorflow model can't be dumped directly.
So the data should be save separately
**TODO**: Please implement the function to load the files
Parameters
----------
path : Union[Path, str]
the target path ... |
Tensorflow model can't be dumped directly.
So the data should be save separately
**TODO**: Please implement the function to load the files
Parameters
----------
path : Union[Path, str]
the target path to be dumped
| to_pickle | python | microsoft/qlib | examples/benchmarks/TFT/tft.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py | MIT |
def get_column_definition(self):
"""Returns formatted column definition in order expected by the TFT."""
column_definition = self._column_definition
# Sanity checks first.
# Ensure only one ID and time column exist
def _check_single_column(input_type):
length = len(... | Returns formatted column definition in order expected by the TFT. | get_column_definition | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/base.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py | MIT |
def _get_tft_input_indices(self):
"""Returns the relevant indexes and input sizes required by TFT."""
# Functions
def _extract_tuples_from_data_type(data_type, defn):
return [tup for tup in defn if tup[1] == data_type and tup[2] not in {InputTypes.ID, InputTypes.TIME}]
def ... | Returns the relevant indexes and input sizes required by TFT. | _get_tft_input_indices | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/base.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py | MIT |
def get_experiment_params(self):
"""Returns fixed model parameters for experiments."""
required_keys = [
"total_time_steps",
"num_encoder_steps",
"num_epochs",
"early_stopping_patience",
"multiprocessing_workers",
]
fixed_para... | Returns fixed model parameters for experiments. | get_experiment_params | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/base.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py | MIT |
def split_data(self, df, valid_boundary=2016, test_boundary=2018):
"""Splits data frame into training-validation-test data frames.
This also calibrates scaling object, and transforms data for each split.
Args:
df: Source data frame to split.
valid_boundary: Starting year fo... | Splits data frame into training-validation-test data frames.
This also calibrates scaling object, and transforms data for each split.
Args:
df: Source data frame to split.
valid_boundary: Starting year for validation data
test_boundary: Starting year for test data
... | split_data | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | MIT |
def set_scalers(self, df):
"""Calibrates scalers using the data supplied.
Args:
df: Data to use to calibrate scalers.
"""
print("Setting scalers with training data...")
column_definitions = self.get_column_definition()
id_column = utils.get_single_col_by_input... | Calibrates scalers using the data supplied.
Args:
df: Data to use to calibrate scalers.
| set_scalers | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | MIT |
def transform_inputs(self, df):
"""Performs feature transformations.
This includes both feature engineering, preprocessing and normalisation.
Args:
df: Data frame to transform.
Returns:
Transformed data frame.
"""
output = df.copy()
if sel... | Performs feature transformations.
This includes both feature engineering, preprocessing and normalisation.
Args:
df: Data frame to transform.
Returns:
Transformed data frame.
| transform_inputs | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | MIT |
def format_predictions(self, predictions):
"""Reverts any normalisation to give predictions in original scale.
Args:
predictions: Dataframe of model predictions.
Returns:
Data frame of unnormalised predictions.
"""
output = predictions.copy()
column... | Reverts any normalisation to give predictions in original scale.
Args:
predictions: Dataframe of model predictions.
Returns:
Data frame of unnormalised predictions.
| format_predictions | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | MIT |
def get_fixed_params(self):
"""Returns fixed model parameters for experiments."""
fixed_params = {
"total_time_steps": 6 + 6,
"num_encoder_steps": 6,
"num_epochs": 100,
"early_stopping_patience": 10,
"multiprocessing_workers": 5,
}
... | Returns fixed model parameters for experiments. | get_fixed_params | python | microsoft/qlib | examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py | MIT |
def __init__(self, experiment="volatility", root_folder=None):
"""Creates configs based on default experiment chosen.
Args:
experiment: Name of experiment.
root_folder: Root folder to save all outputs of training.
"""
if experiment not in self.default_experiments:
... | Creates configs based on default experiment chosen.
Args:
experiment: Name of experiment.
root_folder: Root folder to save all outputs of training.
| __init__ | python | microsoft/qlib | examples/benchmarks/TFT/expt_settings/configs.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/expt_settings/configs.py | MIT |
def make_data_formatter(self):
"""Gets a data formatter object for experiment.
Returns:
Default DataFormatter per experiment.
"""
data_formatter_class = {
"Alpha158": data_formatters.qlib_Alpha158.Alpha158Formatter,
}
return data_formatter_class[s... | Gets a data formatter object for experiment.
Returns:
Default DataFormatter per experiment.
| make_data_formatter | python | microsoft/qlib | examples/benchmarks/TFT/expt_settings/configs.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/expt_settings/configs.py | MIT |
def __init__(self, param_ranges, fixed_params, model_folder, override_w_fixed_params=True):
"""Instantiates model.
Args:
param_ranges: Discrete hyperparameter range for random search.
fixed_params: Fixed model parameters per experiment.
model_folder: Folder to store optimi... | Instantiates model.
Args:
param_ranges: Discrete hyperparameter range for random search.
fixed_params: Fixed model parameters per experiment.
model_folder: Folder to store optimisation artifacts.
override_w_fixed_params: Whether to override serialsed fixed model
... | __init__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def load_results(self):
"""Loads results from previous hyperparameter optimisation.
Returns:
A boolean indicating if previous results can be loaded.
"""
print("Loading results from", self.hyperparam_folder)
results_file = os.path.join(self.hyperparam_folder, "results.... | Loads results from previous hyperparameter optimisation.
Returns:
A boolean indicating if previous results can be loaded.
| load_results | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _get_params_from_name(self, name):
"""Returns previously saved parameters given a key."""
params = self.saved_params
selected_params = dict(params[name])
if self._override_w_fixed_params:
for k in self.fixed_params:
selected_params[k] = self.fixed_params... | Returns previously saved parameters given a key. | _get_params_from_name | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def clear(self):
"""Clears all previous results and saved parameters."""
shutil.rmtree(self.hyperparam_folder)
os.makedirs(self.hyperparam_folder)
self.results = pd.DataFrame()
self.saved_params = pd.DataFrame() | Clears all previous results and saved parameters. | clear | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _check_params(self, params):
"""Checks that parameter map is properly defined."""
valid_fields = list(self.param_ranges.keys()) + list(self.fixed_params.keys())
invalid_fields = [k for k in params if k not in valid_fields]
missing_fields = [k for k in valid_fields if k not in params... | Checks that parameter map is properly defined. | _check_params | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _get_name(self, params):
"""Returns a unique key for the supplied set of params."""
self._check_params(params)
fields = list(params.keys())
fields.sort()
return "_".join([str(params[k]) for k in fields]) | Returns a unique key for the supplied set of params. | _get_name | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def get_next_parameters(self, ranges_to_skip=None):
"""Returns the next set of parameters to optimise.
Args:
ranges_to_skip: Explicitly defines a set of keys to skip.
"""
if ranges_to_skip is None:
ranges_to_skip = set(self.results.index)
if not isinstance... | Returns the next set of parameters to optimise.
Args:
ranges_to_skip: Explicitly defines a set of keys to skip.
| get_next_parameters | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _get_next():
"""Returns next hyperparameter set per try."""
parameters = {k: np.random.choice(self.param_ranges[k]) for k in param_range_keys}
# Adds fixed params
for k in self.fixed_params:
parameters[k] = self.fixed_params[k]
return pa... | Returns next hyperparameter set per try. | _get_next | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def update_score(self, parameters, loss, model, info=""):
"""Updates the results from last optimisation run.
Args:
parameters: Hyperparameters used in optimisation.
loss: Validation loss obtained.
model: Model to serialised if required.
info: Any ancillary inform... | Updates the results from last optimisation run.
Args:
parameters: Hyperparameters used in optimisation.
loss: Validation loss obtained.
model: Model to serialised if required.
info: Any ancillary information to tag on to results.
Returns:
Boolean flag ... | update_score | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def __init__(
self,
param_ranges,
fixed_params,
root_model_folder,
worker_number,
search_iterations=1000,
num_iterations_per_worker=5,
clear_serialised_params=False,
):
"""Instantiates optimisation manager.
This hyperparameter optimisa... | Instantiates optimisation manager.
This hyperparameter optimisation pre-generates #search_iterations
hyperparameter combinations and serialises them
at the start. At runtime, each worker goes through their own set of
parameter ranges. The pregeneration
allows for multiple worker... | __init__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def get_next_parameters(self):
"""Returns next dictionary of hyperparameters to optimise."""
param_name = self.worker_search_queue.pop()
params = self.global_hyperparam_df.loc[param_name, :].to_dict()
# Always override!
for k in self.fixed_params:
print("Overriding ... | Returns next dictionary of hyperparameters to optimise. | get_next_parameters | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def load_serialised_hyperparam_df(self):
"""Loads serialsed hyperparameter ranges from file.
Returns:
DataFrame containing hyperparameter combinations.
"""
print(
"Loading params for {} search iterations form {}".format(
self.total_search_iterations... | Loads serialsed hyperparameter ranges from file.
Returns:
DataFrame containing hyperparameter combinations.
| load_serialised_hyperparam_df | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def update_serialised_hyperparam_df(self):
"""Regenerates hyperparameter combinations and saves to file.
Returns:
DataFrame containing hyperparameter combinations.
"""
search_df = self._generate_full_hyperparam_df()
print(
"Serialising params for {} search... | Regenerates hyperparameter combinations and saves to file.
Returns:
DataFrame containing hyperparameter combinations.
| update_serialised_hyperparam_df | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _generate_full_hyperparam_df(self):
"""Generates actual hyperparameter combinations.
Returns:
DataFrame containing hyperparameter combinations.
"""
np.random.seed(131) # for reproducibility of hyperparam list
name_list = []
param_list = []
for _ ... | Generates actual hyperparameter combinations.
Returns:
DataFrame containing hyperparameter combinations.
| _generate_full_hyperparam_df | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def clear(self): # reset when cleared
"""Clears results for hyperparameter manager and resets."""
super().clear()
self.worker_search_queue = self._get_worker_search_queue() | Clears results for hyperparameter manager and resets. | clear | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def load_results(self):
"""Load results from file and queue parameter combinations to try.
Returns:
Boolean indicating if results were successfully loaded.
"""
success = super().load_results()
if success:
self.worker_search_queue = self._get_worker_search_... | Load results from file and queue parameter combinations to try.
Returns:
Boolean indicating if results were successfully loaded.
| load_results | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def _get_worker_search_queue(self):
"""Generates the queue of param combinations for current worker.
Returns:
Queue of hyperparameter combinations outstanding.
"""
global_df = self.assign_worker_numbers(self.global_hyperparam_df)
worker_df = global_df[global_df["worker... | Generates the queue of param combinations for current worker.
Returns:
Queue of hyperparameter combinations outstanding.
| _get_worker_search_queue | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def assign_worker_numbers(self, df):
"""Updates parameter combinations with the index of the worker used.
Args:
df: DataFrame of parameter combinations.
Returns:
Updated DataFrame with worker number.
"""
output = df.copy()
n = self.total_search_iter... | Updates parameter combinations with the index of the worker used.
Args:
df: DataFrame of parameter combinations.
Returns:
Updated DataFrame with worker number.
| assign_worker_numbers | python | microsoft/qlib | examples/benchmarks/TFT/libs/hyperparam_opt.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py | MIT |
def linear_layer(size, activation=None, use_time_distributed=False, use_bias=True):
"""Returns simple Keras linear layer.
Args:
size: Output size
activation: Activation function to apply if required
use_time_distributed: Whether to apply layer across time
use_bias: Whether bias should b... | Returns simple Keras linear layer.
Args:
size: Output size
activation: Activation function to apply if required
use_time_distributed: Whether to apply layer across time
use_bias: Whether bias should be included in layer
| linear_layer | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def apply_mlp(
inputs, hidden_size, output_size, output_activation=None, hidden_activation="tanh", use_time_distributed=False
):
"""Applies simple feed-forward network to an input.
Args:
inputs: MLP inputs
hidden_size: Hidden state size
output_size: Output size of MLP
output_activat... | Applies simple feed-forward network to an input.
Args:
inputs: MLP inputs
hidden_size: Hidden state size
output_size: Output size of MLP
output_activation: Activation function to apply on output
hidden_activation: Activation function to apply on input
use_time_distributed: Wheth... | apply_mlp | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def apply_gating_layer(x, hidden_layer_size, dropout_rate=None, use_time_distributed=True, activation=None):
"""Applies a Gated Linear Unit (GLU) to an input.
Args:
x: Input to gating layer
hidden_layer_size: Dimension of GLU
dropout_rate: Dropout rate to apply if any
use_time_distribut... | Applies a Gated Linear Unit (GLU) to an input.
Args:
x: Input to gating layer
hidden_layer_size: Dimension of GLU
dropout_rate: Dropout rate to apply if any
use_time_distributed: Whether to apply across time
activation: Activation function to apply to the linear feature transform if
... | apply_gating_layer | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def add_and_norm(x_list):
"""Applies skip connection followed by layer normalisation.
Args:
x_list: List of inputs to sum for skip connection
Returns:
Tensor output from layer.
"""
tmp = Add()(x_list)
tmp = LayerNorm()(tmp)
return tmp | Applies skip connection followed by layer normalisation.
Args:
x_list: List of inputs to sum for skip connection
Returns:
Tensor output from layer.
| add_and_norm | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def gated_residual_network(
x,
hidden_layer_size,
output_size=None,
dropout_rate=None,
use_time_distributed=True,
additional_context=None,
return_gate=False,
):
"""Applies the gated residual network (GRN) as defined in paper.
Args:
x: Network inputs
hidden_layer_size: In... | Applies the gated residual network (GRN) as defined in paper.
Args:
x: Network inputs
hidden_layer_size: Internal state size
output_size: Size of output layer
dropout_rate: Dropout rate if dropout is applied
use_time_distributed: Whether to apply network across time dimension
ad... | gated_residual_network | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def get_decoder_mask(self_attn_inputs):
"""Returns causal mask to apply for self-attention layer.
Args:
self_attn_inputs: Inputs to self attention layer to determine mask shape
"""
len_s = tf.shape(self_attn_inputs)[1]
bs = tf.shape(self_attn_inputs)[:1]
mask = K.cumsum(tf.eye(len_s, batc... | Returns causal mask to apply for self-attention layer.
Args:
self_attn_inputs: Inputs to self attention layer to determine mask shape
| get_decoder_mask | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def __call__(self, q, k, v, mask):
"""Applies scaled dot product attention.
Args:
q: Queries
k: Keys
v: Values
mask: Masking if required -- sets softmax to very large value
Returns:
Tuple of (layer outputs, attention weights)
"""
... | Applies scaled dot product attention.
Args:
q: Queries
k: Keys
v: Values
mask: Masking if required -- sets softmax to very large value
Returns:
Tuple of (layer outputs, attention weights)
| __call__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def __init__(self, n_head, d_model, dropout):
"""Initialises layer.
Args:
n_head: Number of heads
d_model: TFT state dimensionality
dropout: Dropout discard rate
"""
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = d_model // n_head
s... | Initialises layer.
Args:
n_head: Number of heads
d_model: TFT state dimensionality
dropout: Dropout discard rate
| __init__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def __call__(self, q, k, v, mask=None):
"""Applies interpretable multihead attention.
Using T to denote the number of time steps fed into the transformer.
Args:
q: Query tensor of shape=(?, T, d_model)
k: Key of shape=(?, T, d_model)
v: Values of shape=(?, T, d_mo... | Applies interpretable multihead attention.
Using T to denote the number of time steps fed into the transformer.
Args:
q: Query tensor of shape=(?, T, d_model)
k: Key of shape=(?, T, d_model)
v: Values of shape=(?, T, d_model)
mask: Masking if required with shape... | __call__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def __init__(self, raw_params, use_cudnn=False):
"""Builds TFT from parameters.
Args:
raw_params: Parameters to define TFT
use_cudnn: Whether to use CUDNN GPU optimised LSTM
"""
self.name = self.__class__.__name__
params = dict(raw_params) # copy locally
... | Builds TFT from parameters.
Args:
raw_params: Parameters to define TFT
use_cudnn: Whether to use CUDNN GPU optimised LSTM
| __init__ | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def get_tft_embeddings(self, all_inputs):
"""Transforms raw inputs to embeddings.
Applies linear transformation onto continuous variables and uses embeddings
for categorical variables.
Args:
all_inputs: Inputs to transform
Returns:
Tensors for transformed i... | Transforms raw inputs to embeddings.
Applies linear transformation onto continuous variables and uses embeddings
for categorical variables.
Args:
all_inputs: Inputs to transform
Returns:
Tensors for transformed inputs.
| get_tft_embeddings | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def cache_batched_data(self, data, cache_key, num_samples=-1):
"""Batches and caches data once for using during training.
Args:
data: Data to batch and cache
cache_key: Key used for cache
num_samples: Maximum number of samples to extract (-1 to use all data)
"""
... | Batches and caches data once for using during training.
Args:
data: Data to batch and cache
cache_key: Key used for cache
num_samples: Maximum number of samples to extract (-1 to use all data)
| cache_batched_data | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def _batch_sampled_data(self, data, max_samples):
"""Samples segments into a compatible format.
Args:
data: Sources data to sample and batch
max_samples: Maximum number of samples in batch
Returns:
Dictionary of batched data with the maximum samples specified.
... | Samples segments into a compatible format.
Args:
data: Sources data to sample and batch
max_samples: Maximum number of samples in batch
Returns:
Dictionary of batched data with the maximum samples specified.
| _batch_sampled_data | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def _batch_data(self, data):
"""Batches data for training.
Converts raw dataframe from a 2-D tabular format to a batched 3-D array
to feed into Keras model.
Args:
data: DataFrame to batch
Returns:
Batched Numpy array with shape=(?, self.time_steps, self.inp... | Batches data for training.
Converts raw dataframe from a 2-D tabular format to a batched 3-D array
to feed into Keras model.
Args:
data: DataFrame to batch
Returns:
Batched Numpy array with shape=(?, self.time_steps, self.input_size)
| _batch_data | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def _build_base_graph(self):
"""Returns graph defining layers of the TFT."""
# Size definitions.
time_steps = self.time_steps
combined_input_size = self.input_size
encoder_steps = self.num_encoder_steps
# Inputs.
all_inputs = tf.keras.layers.Input(
s... | Returns graph defining layers of the TFT. | _build_base_graph | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def static_combine_and_mask(embedding):
"""Applies variable selection network to static inputs.
Args:
embedding: Transformed static inputs
Returns:
Tensor output for variable selection network
"""
# Add temporal features
... | Applies variable selection network to static inputs.
Args:
embedding: Transformed static inputs
Returns:
Tensor output for variable selection network
| static_combine_and_mask | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def lstm_combine_and_mask(embedding):
"""Apply temporal variable selection networks.
Args:
embedding: Transformed inputs.
Returns:
Processed tensor outputs.
"""
# Add temporal features
_, time_steps, embedding_dim, nu... | Apply temporal variable selection networks.
Args:
embedding: Transformed inputs.
Returns:
Processed tensor outputs.
| lstm_combine_and_mask | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def get_lstm(return_state):
"""Returns LSTM cell initialized with default parameters."""
if self.use_cudnn:
lstm = tf.keras.layers.CuDNNLSTM(
self.hidden_layer_size,
return_sequences=True,
return_state=return_state,
... | Returns LSTM cell initialized with default parameters. | get_lstm | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
def build_model(self):
"""Build model and defines training losses.
Returns:
Fully defined Keras model.
"""
with tf.variable_scope(self.name):
transformer_layer, all_inputs, attention_components = self._build_base_graph()
outputs = tf.keras.layers.Time... | Build model and defines training losses.
Returns:
Fully defined Keras model.
| build_model | python | microsoft/qlib | examples/benchmarks/TFT/libs/tft_model.py | https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.