Getting started with learning to rank
argparse
import
json
import
os
import
pickle
as
pkl
import
numpy
as
np
import
pandas
as
pd
from
sklearn.datasets
import
import
xgboost
as
xgb
from
xgboost.testing.data
import
RelDataCV
,
simulate_clicks
,
sort_ltr_samples
def
load_mslr_10k
(
data_path
:
str
,
cache_path
:
str
)
->
RelDataCV
:
"""Load the MSLR10k dataset from data_path and cache a pickle object in cache_path.
Returns
-------
A list of tuples [(X, y, qid), ...].
"""
root_path
=
(
args
.
data
)
cacheroot_path
=
(
args
.
cache
)
cache_path
=
(
cacheroot_path
,
"MSLR_10K_LETOR.pkl"
)
fold
=
1
if
not
(
cache_path
):
fold_path
=
(
root_path
,
f
"Fold
{
fold
}
"
)
train_path
=
(
fold_path
,
"train.txt"
)
valid_path
=
(
fold_path
,
"vali.txt"
)
test_path
=
(
fold_path
,
"test.txt"
)
X_train
,
y_train
,
qid_train
=
(
train_path
,
query_id
=
True
,
dtype
=
)
y_train
=
y_train
.
astype
(
)
qid_train
=
qid_train
.
astype
(
)
X_valid
,
y_valid
,
qid_valid
=
(
valid_path
,
query_id
=
True
,
dtype
=
)
y_valid
=
y_valid
.
astype
(
)
qid_valid
=
qid_valid
.
astype
(
)
X_test
,
y_test
,
qid_test
=
(
test_path
,
query_id
=
True
,
dtype
=
)
y_test
=
y_test
.
astype
(
)
qid_test
=
qid_test
.
astype
(
)
data
=
RelDataCV
(
train
=
(
X_train
,
y_train
,
qid_train
),
test
=
(
X_test
,
y_test
,
qid_test
),
max_rel
=
4
,
)
with
open
(
cache_path
,
"wb"
)
as
fd
:
(
data
,
fd
)
with
open
(
cache_path
,
"rb"
)
as
fd
:
data
=
(
fd
)
return
data
def
ranking_demo
(
args
:
)
->
None
:
"""Demonstration for learning to rank with relevance degree."""
data
=
load_mslr_10k
(
args
.
data
,
args
.
cache
)
X_train
,
y_train
,
qid_train
=
data
.
train
sorted_idx
=
(
qid_train
)
X_train
=
X_train
[
sorted_idx
]
y_train
=
y_train
[
sorted_idx
]
qid_train
=
qid_train
[
sorted_idx
]
X_test
,
y_test
,
qid_test
=
data
.
test
sorted_idx
=
(
qid_test
)
X_test
=
X_test
[
sorted_idx
]
y_test
=
y_test
[
sorted_idx
]
qid_test
=
qid_test
[
sorted_idx
]
ranker
=
xgb
.
XGBRanker
(
tree_method
=
"hist"
,
device
=
"cuda"
,
lambdarank_pair_method
=
"topk"
,
lambdarank_num_pair_per_sample
=
13
,
eval_metric
=
[
"ndcg@1"
,
"ndcg@8"
],
)
ranker
.
fit
(
X_train
,
y_train
,
qid
=
qid_train
,
eval_set
=
[(
X_test
,
y_test
)],
eval_qid
=
[
qid_test
],
verbose
=
True
,
)
def
click_data_demo
(
args
:
)
->
None
:
"""Demonstration for learning to rank with click data."""
data
=
load_mslr_10k
(
args
.
data
,
args
.
cache
)
train
,
test
=
simulate_clicks
(
data
)
assert
test
is
not
None
assert
train
.
X
.
shape
[
0
]
==
train
.
click
.
size
assert
test
.
X
.
shape
[
0
]
==
test
.
click
.
size
assert
test
.
score
.
dtype
==
assert
test
.
click
.
dtype
==
X_train
,
clicks_train
,
y_train
,
qid_train
=
sort_ltr_samples
(
train
.
X
,
train
.
y
,
train
.
qid
,
train
.
click
,
train
.
pos
,
)
X_test
,
clicks_test
,
y_test
,
qid_test
=
sort_ltr_samples
(
test
.
X
,
test
.
y
,
test
.
qid
,
test
.
click
,
test
.
pos
,
)
class
ShowPosition
(
xgb
.
callback
.
TrainingCallback
):
def
after_iteration
(
self
,
model
:
xgb
.
Booster
,
epoch
:
int
,
evals_log
:
xgb
.
callback
.
TrainingCallback
.
EvalsLog
,
)
->
bool
:
config
=
(
model
.
save_config
())
ti_plus
=
(
config
[
"learner"
][
"objective"
][
"ti+"
])
tj_minus
=
(
config
[
"learner"
][
"objective"
][
"tj-"
])
df
=
({
"ti+"
:
ti_plus
,
"tj-"
:
tj_minus
})
print
(
df
)
return
False
ranker
=
xgb
.
XGBRanker
(
n_estimators
=
512
,
tree_method
=
"hist"
,
device
=
"cuda"
,
learning_rate
=
0.01
,
reg_lambda
=
1.5
,
subsample
=
0.8
,
sampling_method
=
"gradient_based"
,
objective
=
"rank:ndcg"
,
lambdarank_unbiased
=
True
,
lambdarank_bias_norm
=
1
,
lambdarank_num_pair_per_sample
=
12
,
lambdarank_pair_method
=
"topk"
,
ndcg_exp_gain
=
True
,
eval_metric
=
[
"ndcg@1"
,
"ndcg@3"
,
"ndcg@5"
,
"ndcg@10"
],
callbacks
=
[
ShowPosition
()],
)
ranker
.
fit
(
X_train
,
clicks_train
,
qid
=
qid_train
,
eval_set
=
[(
X_test
,
y_test
),
(
X_test
,
clicks_test
)],
eval_qid
=
[
qid_test
,
qid_test
],
verbose
=
True
,
)
ranker
.
predict
(
X_test
)
if
__name__
==
"__main__"
:
parser
=
(
description
=
"Demonstration of learning to rank using XGBoost."
)
parser
.
add_argument
(
"--data"
,
type
=
str
,
help
=
"Root directory of the MSLR-WEB10K data."
,
required
=
True
,
)
parser
.
add_argument
(
"--cache"
,
type
=
str
,
help
=
"Directory for caching processed data."
,
required
=
True
,
)
args
=
parser
.
parse_args
()
ranking_demo
(
args
)
click_data_demo
(
args
)