| 1 |
context('Learning to rank') |
| 2 |
|
| 3 |
n_threads <- 2 |
| 4 |
|
| 5 |
test_that('Test ranking with unweighted data', { |
| 6 |
X <- Matrix::sparseMatrix( |
| 7 |
i = c(2, 3, 7, 9, 12, 15, 17, 18) |
| 8 |
, j = c(1, 1, 2, 2, 3, 3, 4, 4) |
| 9 |
, x = rep(1.0, 8) |
| 10 |
, dims = c(20, 4) |
| 11 |
) |
| 12 |
y <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0) |
| 13 |
group <- c(5, 5, 5, 5) |
| 14 |
dtrain <- xgb.DMatrix(X, label = y, group = group, nthread = n_threads) |
| 15 |
|
| 16 |
params <- xgb.params( |
| 17 |
learning_rate = 1, |
| 18 |
tree_method = 'exact', |
| 19 |
objective = 'rank:pairwise', |
| 20 |
max_depth = 1, |
| 21 |
eval_metric = c('auc', 'aucpr'), |
| 22 |
nthread = n_threads |
| 23 |
) |
| 24 |
bst <- xgb.train(params, dtrain, nrounds = 10, evals = list(train = dtrain), verbose = 0) |
| 25 |
# Check if the metric is monotone increasing |
| 26 |
expect_true(all(diff(attributes(bst)$evaluation_log$train_auc) >= 0)) |
| 27 |
expect_true(all(diff(attributes(bst)$evaluation_log$train_aucpr) >= 0)) |
| 28 |
}) |
| 29 |
|
| 30 |
test_that('Test ranking with weighted data', { |
| 31 |
X <- Matrix::sparseMatrix( |
| 32 |
i = c(2, 3, 7, 9, 12, 15, 17, 18) |
| 33 |
, j = c(1, 1, 2, 2, 3, 3, 4, 4) |
| 34 |
, x = rep(1.0, 8) |
| 35 |
, dims = c(20, 4) |
| 36 |
) |
| 37 |
y <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0) |
| 38 |
group <- c(5, 5, 5, 5) |
| 39 |
weight <- c(1.0, 2.0, 3.0, 4.0) |
| 40 |
dtrain <- xgb.DMatrix( |
| 41 |
X, label = y, group = group, weight = weight, nthread = n_threads |
| 42 |
) |
| 43 |
|
| 44 |
params <- xgb.params( |
| 45 |
learning_rate = 1, |
| 46 |
tree_method = "exact", |
| 47 |
objective = "rank:pairwise", |
| 48 |
max_depth = 1, |
| 49 |
eval_metric = c("auc", "aucpr"), |
| 50 |
nthread = n_threads |
| 51 |
) |
| 52 |
bst <- xgb.train(params, dtrain, nrounds = 10, evals = list(train = dtrain), verbose = 0) |
| 53 |
# Check if the metric is monotone increasing |
| 54 |
expect_true(all(diff(attributes(bst)$evaluation_log$train_auc) >= 0)) |
| 55 |
expect_true(all(diff(attributes(bst)$evaluation_log$train_aucpr) >= 0)) |
| 56 |
for (i in 1:10) { |
| 57 |
pred <- predict(bst, newdata = dtrain, iterationrange = c(1, i)) |
| 58 |
# is_sorted[i]: is i-th group correctly sorted by the ranking predictor? |
| 59 |
is_sorted <- lapply(seq(1, 20, by = 5), |
| 60 |
function(k) { |
| 61 |
ind <- order(-pred[k:(k + 4)]) |
| 62 |
z <- y[ind + (k - 1)] |
| 63 |
all(diff(z) <= 0) # Check if z is monotone decreasing |
| 64 |
}) |
| 65 |
# Since we give weights 1, 2, 3, 4 to the four query groups, |
| 66 |
# the ranking predictor will first try to correctly sort the last query group |
| 67 |
# before correctly sorting other groups. |
| 68 |
expect_true(all(diff(as.numeric(is_sorted)) >= 0)) |
| 69 |
} |
| 70 |
}) |