XGBoost › Ranking Example
Machine Learning from ScratchAll chapters XGBoost › Ranking ExampleSection view · Sections in this chapter6 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's work through a concrete ranking example to demonstrate how XGBoost handles learning-to-rank problems. We'll use a search engine scenario where we want to rank documents for a given query.
Consider a query "machine learning tutorial" with 4 documents that need to be ranked:
| Document | Features | Relevance Score |
|---|---|---|
| Doc 1 | [0.8, 0.9, 0.7] | 3 (Highly relevant) |
| Doc 2 | [0.6, 0.5, 0.8] | 1 (Not relevant) |
| Doc 3 | [0.9, 0.8, 0.6] | 2 (Somewhat relevant) |
| Doc 4 | [0.7, 0.7, 0.9] | 2 (Somewhat relevant) |
Step 1: Initialize predictions We start with initial predictions (typically zeros or small random values):
- Doc 1:
- Doc 2:
- Doc 3:
- Doc 4:
Step 2: Calculate pairwise ranking loss For the pairwise ranking loss, we consider all pairs where one document should be ranked higher than another based on relevance scores.
Relevant pairs (Doc i should rank higher than Doc j):
- (Doc 1, Doc 2): relevance 3 > 1
- (Doc 1, Doc 3): relevance 3 > 2
- (Doc 1, Doc 4): relevance 3 > 2
- (Doc 3, Doc 2): relevance 2 > 1
- (Doc 4, Doc 2): relevance 2 > 1
The pairwise loss for each pair is:
Since all initial predictions are 0, the loss for each pair is:
Step 3: Calculate gradients for ranking For ranking problems, the gradient calculation is more complex as it involves the pairwise relationships. The gradient for document is:
With initial predictions of 0, this simplifies to:
- Doc 1: (should rank higher than 3 docs)
- Doc 2: (should rank lower than 3 docs)
- Doc 3: (should rank higher than 1, lower than 1)
- Doc 4: (should rank higher than 1, lower than 1)
Step 4: Build the first ranking tree Let's say we create a tree that splits on the first feature < 0.75:
- Left leaf (feature 1 < 0.75): Doc 2, Doc 4
- Right leaf (feature 1 ≥ 0.75): Doc 1, Doc 3
For the left leaf:
For the right leaf:
With :
Step 5: Update predictions After the first tree:
- Doc 1:
- Doc 2:
- Doc 3:
- Doc 4:
The ranking after the first tree is: Doc 2, Doc 4 (tied), Doc 1, Doc 3 (tied). This is not the correct ranking yet, so subsequent trees will continue to refine the predictions to achieve the desired ranking order.
VisualizationOut [13]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
1 comment
Thank you so much for breaking down the math behind XGB. The visualization after the math, helped me to actually understand how the algorithm works.