One of the most powerful uses of machine learning technology is personalisation. In this article, we will go into detail about building an ML-powered Learning-to-Rank (LTR) algorithm for a client in the travel industry.
Secret Escapes is one of the world’s leading members-only online travel brands, offering hand-picked offers to millions of users worldwide.
They wanted to upgrade their website search experience. More specifically, they wanted to offer personalised results to members searching their website or viewing a page. The task was to create a Learning-to-Rank algorithm that would automatically order the search results, showing first the items that were most likely to drive a conversion, and moving on to the least viable offers.
This blog post will focus on the technological aspects of building this LTR solution. See the full case study on the Secret Escapes project.
Existing Secret Escapes tech stack
Our starting point was Secret Escapes’ existing tech stack because it provided a great foundation for the development of a new Learn to Rank (LRT) model to be used for searches on the website.
The stack included:
- Cloud provider: AWS — S3, OpenSearch (Elasticsearch), SageMaker
- Data warehouse: Snowflake
- Data transformation: dbt
- Orchestration: Airflow
- CI/CD: Jenkins
In Elasticsearch, the Learning-to-Rank framework leverages ML to improve the relevance of search results. Traditionally, Elasticsearch relies on a scoring mechanism based on factors like keyword matching.
LTR introduces an ML model that analyses various features of documents and user queries. This model then influences the final ranking, pushing documents deemed more relevant by the model to the top.
Think of it as this: Elasticsearch gives you a baseline ranking based on strict criteria, but LTR allows you to fine-tune that ranking based on what users actually find useful (learnt through machine learning). This can involve factors beyond simple keyword matching, leading to a more nuanced and user-centric search experience.
LTR: Judgement lists and feature sets
To illustrate these concepts at a foundational level, we will consider a hypothetical video game database.
Judgement lists act as a reference point for LTR models, representing graded search results for a specific query. These grades typically range from 0 (completely irrelevant) to 4 (exactly relevant).
Imagine searching for Call of Duty in a video game database. A judgement list might assign a grade of 4 to the game titled Call of Duty, indicating a perfect match. Crash Bandicoot, another game by the same publisher, could receive a grade of 2 due to a loose connection even though it is not directly relevant. Finally, Lost Ark, which has no connection to the search query whatsoever, would likely get a score of 0.
Such a list can be created either manually or programmatically. We opted for using dbt to generate it with the help of some predefined guidelines for grading.
Utilising dbt cloud’s job scheduling, we could ensure that data would always be up-to-date, and we would not have to manually refresh the tables.
Additionally, incorporating the creation of this list into daily pipelines with proper testing allowed us to detect any issues with the data as early as possible. Integration with communication platforms like Slack would further streamline the process, sending notifications about potential problems to data analysts
Since we decided to train the model on the fresh data every day, it became increasingly important to come up with a robust way to always have a clean, up-to-date judgement list to be used for training.
To compile the judgement list for Rank’n’Roll, we looked at past search sessions that had been made on the Secret Escapes website and graded each and one of the search results using the following guidelines based on user interaction:
1 = No user interaction has been made with the search result
2 = Click-through/view event on a deal
3 = Booking form has been opened, but the booking itself has not been completed
4 = Transaction has been completed (aka conversion, booking)
To showcase this, in the below picture we can see a snippet of the judgement list.
In this case, the user has searched for the keyword “Deutschland” and they have clicked on the deals in position 5, 13 and 32, started booking the deal in position 9, but ended up buying the deal shown in position 51 instead. The user has not interacted with any of the other results.
Another important concept is the features, which make up the so-called feature set. A feature can be anything that helps our model rate each document, such as keyword matches in fields like title, rating or description.
To understand the importance of a carefully crafted feature set, let’s go back to our game database example and consider a game titled Warzone. While the title alone might seem ambiguous, examining other features like the description or publisher would reveal it is a highly rated, fairly new game from the Call of Duty series, which justifies its high ranking within the search results.
Building the optimal feature set is an iterative process that requires analysing how each feature impacts the model's predictions. By carefully selecting and refining features, we can guide the LTR model towards more accurate rankings. As of writing this document, we are using nearly 200 features for model training.
There are features that answer deal-related questions: Does this hotel have a spa? Is it pet-friendly? Does the per-person price fall in a given range? How relevant is this document to the keyword “London”?
Others include more user-related information, such as How active has this user been in the past days? How likely are they to book again?
With these features we had already achieved an uplift from the baseline, but to reach the next level, we needed a way to extract more information out of user behaviours than of explicit features.
This is where factorisation, and in particular Alternating Least Square (ALS), came into the picture. ALS performs matrix factorisation on the user-item interaction matrix to find the latent factors that explain the observed interactions. The goal is to approximate the user-item matrix, R, as a product of two lower-dimensional matrices: U (user features) and V (item features).
We have further indexed the user ALS features and item ALS features into an Elasticsearch index to make the values available during inference. At inference time, we perform a dot-product operation, which delivers the predicted likelihood of interaction between the user who is searching and the deals.
SHAP analysis
In the SHapley Additive exPlanations (SHAP) analysis we proved that this ALS dot product was the dominant factor in providing uplift, more than any other explicit feature, due to its effectiveness in capturing user-item interaction.
Once we had a judgement list and scored documents with the help of our desired feature set, we needed to merge these two together. We would use this final table to train the model on, with the goal of uncovering what features contribute to deal conversions and in what manner. The model would learn these relations and would be able to generalise on completely unseen deals for a given user.
SHAP Analysis helps us understand what makes people more likely to book a deal through Secret Escapes. It helps us see how different features, like the price, hotel rating or hotel features influence someone while making a reservation.
Leveraging SHAP, we could understand which features were the most important and whether a feature made a hotel seem more or less attractive to the member. This way, we could see if things like highlighting free breakfast or showcasing great reviews had a more significant impact on bookings. By understanding these influences, we could make changes to the website to showcase the features that would really drive conversions (bookings).
In the iterative process of model training, we would apply SHAP Analysis with every run to check how each feature would impact the overall model performance.
The colours in the chart indicated the feature values, blue standing for a lower value and red signifying a higher value. The position on the X axis indicated the SHAP value, a negative value means it has a negative impact on the model prediction, while a positive one has the opposite effect. Lower model prediction means that the model predicts a lower chance of booking for a given deal.
Considering both the SHAP value and the feature value colours, we could identify how features impacted the model. In some cases, a higher feature value could mean that people were less likely to book; for instance, a higher feature score for hotels tagged with “village” would decrease the probability of conversion.
Automated re-training
We used a Jupyter Notebook running in either SageMaker or on our local machine for main development, as it provided interactive feedback and good plotting facility. However, to enable repeatable and reliable re-training, it was important to have a modularised codebase that we could use to orchestrate this process.
We therefore modularised most of the training code to be shared by the automated pipeline and the notebook. This way, we would need to maintain the codebase in a single place only.
To be able to run this modularised code in the automated pipeline, we used Typer, an open-source Python library, which would help us create a Command Line Interface (CLI) application in no time, where each command could be used as a Docker entry point.
We found it useful to train the model every day, so we needed an orchestrator to do the job and Secret Escapes already had an Airflow instance. Once the Airflow Directed Acyclic Graph (DAG) had finished executing, a new and updated model would be uploaded to AWS S3 for upstream processes to pick up and upload them to the OpenSearch cluster.
The client team prioritised defining success and the mechanisms to measure it for the offline model. That was the only way they could make a decision to go live with it and proceed with A/B testing.
They considered the following metrics:
| Cumulative Gain (CG) | Sum of relevance scores of items returned |
| Discounted Cumulative Gain (DCG) | Similar to CG but prioritises higher ranked items |
| Ideal Discounted Cumulative Gain (IDCG) | DCG of the ideal ranking of items |
| Normalised Discounted Cumulative Gain (NDCG) | DCG/IDCG |
Secret Escapes defined their offline metrics by Normalised Discounted Cumulative Gain (NDCG), which is a common metric in ranking problems in ML literature. Unlike simpler metrics that only consider if an item is relevant or not, NDCG dives deeper to assess how well a model ranks items based on their graded relevance.
DCG measures the usefulness, or gain, of a document based on its position in the result list. The idea is that highly relevant documents appearing lower in the ranked list should be penalised as the gain is discounted logarithmically. IDCG is the maximum possible DCG, which is achieved by an ideal ranking of documents. This means all the most relevant documents are at the top of the list. NDCG is the normalised version of DCG. It compares the DCG of the actual ranking with the IDCG to produce a score between 0 and 1, where 1 indicates the perfect ranking.
In our case, we measure relevance by inspecting the outcome of the search item. If a search item leads to a conversion, the item will be given the highest relevance (say 4). If a search item only leads to a book view, then it will be of lower relevance (say 3). Furthermore, if a search item only results in shallow click through, it will be of even lower relevance (say 2). Finally, when an item is not clicked, it will be of the lowest relevance (say 1).
An ideal list which returns the IDCG would therefore be a list of items, with the converted items all ranked at the top, followed by the items with booking views, then by the items clicked through, and finally the unclicked items.
We split our data into 80% train, 10% validation and 10% test set. We used the test set to compute the NDCG from our model. We then compared the baseline NDCG derived from the actual ranking of those items in the historical search log. A statistically significant uplift will give us confidence that the model will do well online, too.
Let’s start by explaining what NDCG is made of:
- Discounted Cumulative Gain (DCG) measures the usefulness, or gain, of a document based on its position in the result list. The idea here is that highly relevant documents appearing lower in the ranked list should be penalised, as the gain is discounted logarithmically;
- Ideal Discounted Cumulative Gain (IDCG) is the maximum possible DCG, which is achieved by an ideal ranking of documents. This means all the most relevant documents are at the top of the list;
- Normalised Discounted Cumulative Gain (NDCG) is the normalised version of DCG. It compares the DCG of the actual ranking with the IDCG to produce a score between 0 and 1, where 1 indicates the perfect ranking.
In our case, we measure relevance by inspecting the outcome of the search item. If a search item leads to a conversion, the item will be given the highest relevance (say 4). If a search item only leads to a booking view, then it will be of lower relevance (say 3). Furthermore, if a search item only results in shallow click-through, it will be of even lower relevance (say 2). Finally, when an item is not clicked, it will be of the lowest relevance (say 1).
An ideal list which returns the IDCG would therefore be a list of items, with the converted items all ranked at the top, followed by the items with booking views, then items that have been clicked through, and finally items that have not been clicked.
We split our data into 80% train, 10% validation and 10% test set. We used the test set to compute the NDCG from our model and then compared the baseline NDCG derived from the actual ranking of those items in the historical search log. A statistically significant uplift would give us confidence that the model would do well online, too.
How does NDCG work in practice?
Imagine a ranked list of items for a specific query. Each item has a relevance score assigned by the Learning-to-Rank (LTR) model, indicating how well it matches the user intent. NDCG considers both the relevance score and the position of the item in the ranking.
Highly relevant items appearing at the top of the list contribute more to the overall NDCG score compared to less relevant items lower down.
The "discounted" part of NDCG comes from assigning a decreasing weight to the relevance of items as you move down the ranking. This reflects the behavioural pattern of users prioritising items at the beginning of the list and are less likely to pay close attention to items further down.
Finally, normalisation ensures that NDCG scores are comparable across different ranking tasks and datasets, allowing for easier performance comparisons between LTR models.
In simpler terms, NDCG rewards models that surface the most relevant items for a user's query at the top of the ranked list, providing a more informative picture of the LTR model's effectiveness.
What is NDCG@K?
NDCG@k is a variation of NDCG that focuses on the top k results in a ranking. It essentially zooms in on the most crucial part of the list, where users are most likely to focus their attention.
By evaluating NDCG@k for different values of k (such as NDCG@5, NDCG@10), we would gain insights into how our model's performance changes as we move down the ranking. This would give us a far more nuanced understanding of the model's strengths and weaknesses.
So, while standard NDCG offers a comprehensive view of the entire ranking, NDCG@k provides a laser focus on the top results, making it a valuable tool for evaluating the effectiveness of LTR models in prioritising the most relevant items for our users.
A/B testing
Testing rationale
The primary metric for the A/B test was Search to Book, measuring the percentage of search sessions that led to a booking. Performance of LTR was assessed using a frequentist approach with a two-proportion Z-test to guide the launch decision.
The null hypothesis assumed the Control group (existing search) performed equally or better than the Treatment group (LTR-enabled search). Learning-to-Rank would only be launched if the Treatment group showed a significant improvement.
With a Minimum Detectable Effect of ~5% and baselines from a 2-month period, sample sizes were calculated to ensure 80% power and a 95% confidence level, defining the test duration.
Evaluating performance
Evaluating the Learning-to-Rank algorithm across territories posed challenges due to varying traffic volumes. Running separate tests for each territory was impractical, as low traffic in one territory would have extended the experiment to 12 weeks.
While Click-through-Rate (CTR) offered larger sample sizes and higher test power, it did not directly measure the business goal. Without clear alignment between CTR and Search-to-Book, we risked conflicting results between the two metrics.
We chose Search-to-Book as the primary success metric, supplemented by CTR and other guardrail metrics. Combined territory performance was evaluated during the test, with individual territory performance analyzed post-test.
The test duration was extended from 4 to 6 weeks to gather more data and capture behavioral trends effectively.
Test monitoring
A Tableau dashboard was set up to track success and guardrail metrics daily, enabling quick action if metrics showed significant declines. It was agreed that the experiment would be stopped if Search-to-Book in the Treatment group dropped more than 20% below the Control.
To monitor group balance, a Streamlit app within Snowflake was used to test the sample ratio between Control and Treatment. A chi-square test ensured a 50-50 split in session counts. Any deviation triggered a review of the A/B testing platform's assignment logic.
Next, we set out to implement A/B testing to estimate how the algorithm was performing. This is where the real rollercoaster of testing began.
Head to part 2 of this blog post to read the rest of the story.
See the full case study on the Secret Escapes project.
Reach out to tell us about your project and what challenges you face with building ML-powered solutions. We are ready to help you move your project forward.
