{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Ransaka Ravihara",
  "title_listed": "How to Implement Learning to Rank Model using Python",
  "keywords": "Learning to Rank,LambdaRank,LightGBM",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/how-to-implement-learning-to-rank-model-using-python-569cd9c49b08/",
  "publish_date": "2023-01",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "63f2e5618eb4",
  "collected_at": "2026-10-01T23:17:55",
  "title": "How to Implement Learning to Rank Model using Python | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# How to Implement Learning to Rank Model using Python\nThe step-by-step guide on how to implement the lambdarank algorithm using Python and LightGBM\n[Ransaka Ravihara](https://towardsdatascience.com/author/ransakaravihara/)\nJanuary 18, 20239 min read\n![Photo by Andrik Langfield on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/0ZUVy9A0kAzs6xHSF-scaled.jpg)\nPhoto by [Andrik Langfield](https://unsplash.com/@andriklangfield?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nIn my previous two articles, I discussed the basic concepts of Learning to Rank models and widely used evaluation metrics for evaluating LTR models. You can access those using the links listed below.\n> [**What Is Learning to Rank: A Beginner's Guide to Learning to Rank Methods**](https://towardsdatascience.com/what-is-learning-to-rank-a-beginners-guide-to-learning-to-rank-methods-23bbb99ef38c)\n> [**How to evaluate Learning to Rank Models**](https://towardsdatascience.com/how-to-evaluate-learning-to-rank-models-d12cadb99d47)\nIn this article, we will build a lambdarank algorithm for anime recommendations. A research group first introduced LambdaRank at Microsoft, and now it's available on Microsoft's LightGBM library with an easy-to-use sklearn wrapper. Let's start.\n* * *\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n### From Search Engines to Product Recommendations\nAs mentioned above, ranking is widely used in search engines. But it's not limited to search engines; we can adopt the concept and build a solution whenever applicable. Assuming that we want to develop a ranking model for a search engine, we should start with a dataset with queries, its associated documents(URLs), and the relevance score for each query document pair, as shown below.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1VZ3UXU6jNhAqwrthI6DQ2g.jpeg)\nImage by Author\nFinally, we can derive features based on each query and document pair.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1SU53hhQdMfT1nmLYPCTPKw.jpeg)\nImage by Author\nThis is the dataset format for well-known Learning to Rank research papers and datasets. Well, that's about search engines. Let's discuss how we can adapt these concepts for traditional product recommendation tasks. There are various ways to recommend products to users. You can show recommendations when the user purchases an item, or while a user is browsing the page, etc. But for simplicity, let's narrow it down to a specific scenario.\nThis article will build an anime recommendation model for users' homepage customization. When the user logs into the account, we need to show animes based on the relevance scores predicted by the ranker model. Here I will use Anime Recommendation LTR Dataset, which is available under a public license. You can access it via [this kaggle link](https://www.kaggle.com/datasets/ransakaravihara/anime-recommendation-ltr-dataset).\n* * *\nLet's read the dataset and quickly check its columns.\npython\n\n```\nimport zipfile\nimport pandas as pd\n\nzipped_data = zipfile.ZipFile(\"anime-recommendation-ltr-dataset.zip\")\n\nanime_info_df = pd.read_csv(zipped_data.open('anime_info.csv'))\nrelavence_scores = pd.read_csv(zipped_data.open('relavence_scores.csv'))\nuser_info = pd.read_csv(zipped_data.open('user_info.csv'))\n\nanime_info_df.columns.tolist()\n\n# ['anime_id',\n#  'Genres',\n#  'is_tv',\n#  'year_aired',\n#  'is_adult',\n#  'above_five_star_users',\n#  'above_five_star_ratings',\n#  'above_five_star_ratio']\n\nuser_info.columns.tolist()\n\n# ['user_id',\n#  'review_count',\n#  'avg_score',\n#  'score_stddev',\n#  'above_five_star_count',\n#  'above_five_star_ratio']\n\nrelevance_scores.columns.tolist()\n#['anime_id', 'anime_name', 'user_id', 'relevance_score']\n```\n\nAlright, let me explain the methodology I am going to use here. Unlike search engine data, we don't have query and document pairs in this use case. So we will treat users as queries and the animes they are interested in as documents. One search query can be associated with multiple documents; users can interact with many animes. You got the idea, right :)\nThe target label we predict here is _relevance _score,_ stored in the _relevance _scores_ dataset. When we build a raking model, it will learn a function to rank those anime into an optimum order where the highest relevant anime comes first for each user.\nNext, we need to create a dataset by joining the above three datasets. I will also create new features based on anime and user features. Let's create a dataset.\npython\n\n```\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\npopular_genres = ['Comedy',\n 'Action',\n 'Fantasy',\n 'Adventure',\n 'Kids',\n 'Drama',\n 'Sci-Fi',\n 'Music',\n 'Shounen',\n 'Slice of Life']\n\ndef create_genre_flags(df, popular_genres):\n    df = df.dropna(subset=['Genres'])\n    df['Genres'] = df['Genres'].apply(lambda x:\",\".join(s.strip() for s in x.split(\",\")))\n    # use MultiLabelBinarizer to create a one-hot encoded dataframe of the genres\n    mlb = MultiLabelBinarizer()\n    genre_df = pd.DataFrame(mlb.fit_transform(df['Genres'].str.split(',')),\n                            columns=mlb.classes_,\n                            index=df.index)\n    # create a new dataframe with the movie id and genre columns\n    new_df = pd.concat([df['anime_id'], genre_df[popular_genres]], axis=1)\n    new_df.columns = ['anime_id'] + popular_genres\n    return new_df\n\nanime_genre_info_df = create_genre_flags(anime_info_df,popular_genres)\nanime_info_df_final = anime_info_df.merge(anime_genre_info_df,on='anime_id')\nanime_info_df_final.columns = [col if col=='anime_id' else f\"ANIME_FEATURE {col}\".upper() for col in anime_info_df_final.columns]\nuser_info.columns = [col if col=='user_id' else f\"USER_FEATURE {col}\".upper() for col in user_info.columns]\n\ntrain_interim = relavence_scores.merge(anime_info_df_final)\ntrain = train_interim.merge(user_info,how='inner')\n```\n\nLet's quickly check a few statistics of our dataset. In total, there are 4.8Mn user-anime interactions, 15K users, and 16K animes in the dataset.\nHere is the user and anime interaction distribution.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1FYknW4HxQ0JdkAlzkgpCfg.png)\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1Go-A9MnGc3r4mSWSiPq_Fg.png)\nImage by Author\nThe below chart shows how the relevance score is distributed.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1HEEXMuQMF0sjVo52_a_ybA.png)\nImage by Author\nNow we have created the dataset for model training. But one of the main confusing points of the Learning to Rank model is the _group_ parameter. Because the _group_ is a strange parameter for us since it is not commonly used in other machine-learning algorithms. The idea of a _group_ parameter is partitioning the dataset for each query and document pair. It enables the model to learn the relative importance of different features within each group, which can improve the model's overall performance. Having ten user-anime pairs means we have ten groups in our LTR model. Each group can be different in size. But the sum of groups should be the number of samples we have. In simple words, we have to provide group boundaries using _group_ parameters. Then the model can identify each user-anime instance separately.\nFor example, if you have a 6-anime dataset with `group = [3, 2, 1]`, which means that you have three groups, where the first three records are in the first group, records 4–5 are in the second group, and record 6 is in the third group.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/19M80Da74bRerXVHYVEbFcQ.jpeg)\nImage by Author\n**So it's vital to sort the dataset by _user_id(query** _**id)**_**before creating the group parameter.**\npython\n\n```\nna_counts = (train.isna().sum() * 100/len(train))\ntrain_processed = train.drop(na_counts[na_counts > 50].index,axis=1)\ntrain_processed.sort_values(by='user_id',inplace=True)\ntrain_processed.set_index(\"user_id\",inplace=True)\n\nfeatures = ['ANIME_FEATURE IS_TV',\n       'ANIME_FEATURE YEAR_AIRED', 'ANIME_FEATURE IS_ADULT',\n       'ANIME_FEATURE ABOVE_FIVE_STAR_USERS',\n       'ANIME_FEATURE ABOVE_FIVE_STAR_RATINGS',\n       'ANIME_FEATURE ABOVE_FIVE_STAR_RATIO', 'ANIME_FEATURE COMEDY',\n       'ANIME_FEATURE ACTION', 'ANIME_FEATURE FANTASY',\n       'ANIME_FEATURE ADVENTURE', 'ANIME_FEATURE KIDS', 'ANIME_FEATURE DRAMA',\n       'ANIME_FEATURE SCI-FI', 'ANIME_FEATURE MUSIC', 'ANIME_FEATURE SHOUNEN',\n       'ANIME_FEATURE SLICE OF LIFE', 'USER_FEATURE REVIEW_COUNT',\n       'USER_FEATURE AVG_SCORE', 'USER_FEATURE SCORE_STDDEV',\n       'USER_FEATURE ABOVE_FIVE_STAR_COUNT',\n       'USER_FEATURE ABOVE_FIVE_STAR_RATIO']\ntarget = 'relavence_score'\n\ntest_size = int(1e5)\nX,y = train_processed[features],train_processed[target].apply(lambda x:int(x * 10))\ntest_idx_start = len(X)-test_size\n\nxtrain,xtest,ytrain,ytest = X.iloc[0:test_idx_start],X.iloc[test_idx_start:],y.iloc[0:test_idx_start],y.iloc[test_idx_start:]\n```\n\nIn the above code snippet, I have done the following steps,\n  1. Dropped all the columns which have more than 50% null values.\n  2. Sorted dataset based on _user _id._ Otherwise, a _group_ parameter will have inconsistent groups everywhere.\n  3. After sorting the dataset, I declared the last 100,000 rows as validation data and the rest as training data.\n  4. Since the LightGBM model expects integers as target values, I have scaled the target between 1–10 and converted it to an integer. ( If you want, try converting it to 0 or 1 based on the threshold).\n\n\nLet's define the group parameters and quickly fit the model as follows.\npython\n\n```\nget_group_size = lambda df: df.reset_index().groupby(\"user_id\")['user_id'].count()\n\ntrain_groups = get_group_size(xtrain)\ntest_groups = get_group_size(xtest)\n\nprint(sum(train_groups) , sum(test_groups))\n#(4764372, 100000)\n\nmodel = LGBMRanker(objective=\"lambdarank\")\nmodel.fit(xtrain,ytrain,group=train_groups,eval_set=[(xtest,ytest)],eval_group=[test_groups],eval_metric=['ndcg'])\n\n#....\n# [97] valid_0's ndcg@1: 0.900624 valid_0's ndcg@2: 0.900015 valid_0's ndcg@3: 0.892648 valid_0's ndcg@4: 0.891373 valid_0's ndcg@5: 0.886585\n# [98] valid_0's ndcg@1: 0.900624 valid_0's ndcg@2: 0.900015 valid_0's ndcg@3: 0.892648 valid_0's ndcg@4: 0.891895 valid_0's ndcg@5: 0.886632\n# [99] valid_0's ndcg@1: 0.900624 valid_0's ndcg@2: 0.901216 valid_0's ndcg@3: 0.892839 valid_0's ndcg@4: 0.892053 valid_0's ndcg@5: 0.88677\n# [100] valid_0's ndcg@1: 0.900624 valid_0's ndcg@2: 0.901216 valid_0's ndcg@3: 0.892839 valid_0's ndcg@4: 0.892053 valid_0's ndcg@5: 0.886363\n```\n\nAlright, now we finished the training. It's time to make some predictions about specific customers.\nThere is one more critical point to notice here. That is, how the model predictions are calculated. I was confused because when calling the `.predict` method, it does not expect additional parameters such as _group._ So I found below information from GitHub issues. According to the creator of LightGBM mentioned in [this issue](https://github.com/microsoft/LightGBM/issues/3326), LightGBM's lambdarank uses a pointwise approach to generate predictions. Meaning we do not want to provide additional parameters such as _group._ We can call the `.predict()` method with the correct feature vector.\nHowever, since we are developing the LTR model, it's essential to have some candidate products and rank those according to the predicted relevance score. To generate candidate animes, I will use a straightforward method here. That is, select the animes that are not exposed to a given user. Select an N random subset from unexposed animes. Generate features based on user and selected N anime subset. Finally, use generated feature vector to get the relevance score and sort animes based on the relevance score. But in real-world use cases, we should use some meaningful methodologies. As an example, you can generate candidates as follows,\n  * Select the user's favorite _N_ number of genres.\n  * For each genre in the above-selected genres, pick the highest-rated _m_ animes. Now you have _M* N_ animes to rank for that user. Just create the user base and anime-based features. And finally, call the `.predict()` method with the created feature vector.\n\n\npython\n\n```\nuser_2_anime_df = relavence_scores.groupby(\"user_id\").agg({\"anime_id\":lambda x:list(set(x))})\nuser_2_anime_map = dict(zip(user_2_anime_df.index,user_2_anime_df['anime_id']))\n\n#create candidate pool, this will be a all the animes in the database\ncandidate_pool = anime_info_df_final['anime_id'].unique().tolist()\n\n#anime_id to it's name mapping\nanime_id_2_name = relavence_scores.drop_duplicates(subset=[\"anime_id\",\"Name\"])[['anime_id',\"Name\"]]\nanime_id_2_name_map = dict(zip(anime_id_2_name['anime_id'],anime_id_2_name['Name']))\n\ndef candidate_generation(user_id:int,candidate_pool:list,user_2_anime_map:dict,N:int):\n    \"\"\"\n    Note: this a totally random generation, only for demo purpose\n    Generates a list of N anime candidates for a given user based on their previously liked animes.\n\n    Parameters:\n        user_id (int): The user's ID.\n        candidate_pool (list): A list of all possible anime candidates.\n        user_2_anime_map (dict): A dictionary that maps users to their liked animes.\n        N (int): The number of anime candidates to generate.\n\n    Returns:\n        already_interacted (list): List of animes which user already liked\n        candidates (list): A list of N anime candidates for the user.\n    \"\"\"\n\n    #get the already liked animes\n    already_interacted = user_2_anime_map[user_id]\n\n    #candidates will be rest of animes which are not exposed to user\n    candidates = list(set(candidate_pool) - set(already_interacted))\n\n    return already_interacted,np.random.choice(candidates,size=N)\n\ndef generate_predictions(user_id,user_2_anime_map,candidate_pool,feature_columns,anime_id_2_name_map,ranker,N=100):\n    \"\"\"\n    Generates predictions for anime recommendations for a given user.\n\n    Parameters:\n        user_id (int): The user's ID.\n        user_2_anime_map (dict): A dictionary that maps users to their liked animes.\n        candidate_pool (list): A list of all possible anime candidates.\n        feature_columns (list): A list of feature columns to use for generating predictions.\n        anime_id_2_name_map (dict): A dictionary that maps anime IDs to their names.\n        ranker (object): A trained model object that is used to generate predictions.\n        N (int): The number of anime predictions to generate.\n\n    Returns:\n        predictions (DataFrame): A dataframe containing the top N anime recommendations for the user.\n    \"\"\"\n    already_liked,candidates = candidate_generation(user_id,candidate_pool,user_2_anime_map,N=10000)\n\n    #Create dataframe for candidates\n    candidates_df = pd.DataFrame(data=pd.Series(candidates,name='anime_id'))\n\n    # Merge with feature dataframe\n    features = anime_info_df_final.merge(candidates_df)\n\n    #Add user id as a feature\n    features['user_id'] = user_id\n\n    # Merge with user information\n    features = features.merge(user_info)\n\n    # If number of already liked animes is less than number of candidates\n    # Extend the already liked list with -1\n    already_liked = list(already_liked)\n    if len(already_liked) < len(candidates):\n        append_list = np.full(fill_value=-1,shape=(len(candidates)-len(already_liked)))\n        already_liked.extend(list(append_list))\n\n    #Create dataframe for predictions\n    predictions = pd.DataFrame(index=candidates)\n    #Add anime names\n    predictions['name'] = np.array([anime_id_2_name_map.get(id_) for id_ in candidates])\n    #Generate predictions\n    predictions['score'] = ranker.predict(features[feature_columns])\n    predictions = predictions.sort_values(by='score',ascending=False).head(N)\n\n    predictions[f'already_liked - sample[{N}]'] = [anime_id_2_name_map.get(id_) for id_ in already_liked[0:len(predictions)]]\n    return predictions\n\n#let's generate the predictions \ngenerate_predictions(123,user_2_anime_map,candidate_pool,feature_columns=features,anime_id_2_name_map=anime_id_2_name_map,ranker=model,N=10)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1TX0vToKRqB3Vb8rk0tT_zA.png)\nAdditionally, we can use shap to explain the model's predictions.\npython\n\n```\nimport shap\n\ndef generate_shap_plots(ranker, X_train, feature_names, N=3):\n    \"\"\"\n    Generates SHAP plots for a pre-trained LightGBM model.\n\n    Parameters:\n        ranker (lightgbm.Booster): A trained LightGBM model\n        X_train (np.ndarray): The training data used to fit the model\n        feature_names (List): list of feature names\n        N (int): The number of plots to generate\n\n    Returns:\n        None\n    \"\"\"\n    explainer = shap.Explainer(ranker, X_train, feature_names=feature_names)\n    shap_values = explainer(X_train.iloc[:N])\n\n    # Create a figure with 2 subplots\n    # fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5))\n\n    # Plot the summary plot on the first subplot\n    plt.subplot(1, 2, 1)\n    shap.summary_plot(shap_values, feature_names=feature_names, plot_type='bar')\n\n    # Plot the feature importance plot on the second subplot\n    plt.subplot(1, 2, 2)\n    shap.summary_plot(shap_values, feature_names=feature_names, plot_type='dot')\n\n    plt.show()\n\ngenerate_shap_plots(model,xtrain,features,N=10000)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/15AqVey1E6Rd0fUyV5xz_Aw.png)\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1GuVEy2OBu-C8gG_Pp3EB1Q.png)\nImage by Author\n### Conclusion\nThis article aims to give a good starting point to address readers' specific use cases. Because when I started building an LTR model for my project, there wasn't a good guide for beginners. However, training the LTR model may not be necessary for some use cases. You can use straightforward methods like regression, multiclass/ label classification, or clustering. So don't over-engineer your solutions; pick the tool wisely ; )\nThank you for reading! The notebook for this article is available in my [GitHub repo](https://github.com/Ransaka/LTR-with-LIghtGBM).\nReferences :\n  * [LightGBM documentation](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRanker.html#lightgbm.LGBMRanker)\n  * [Microsoft Learning to Rank Datasets](https://www.microsoft.com/en-us/research/project/mslr/)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657265628_qm714e.jpeg)\nWritten By\n## [Ransaka Ravihara](https://towardsdatascience.com/author/ransakaravihara/)\n[See all from Ransaka Ravihara](https://towardsdatascience.com/author/ransakaravihara/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Learning To Rank](https://towardsdatascience.com/tag/learning-to-rank/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Recommendation System](https://towardsdatascience.com/tag/recommendation-system/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F&title=How%20to%20Implement%20Learning%20to%20Rank%20Model%20using%20Python)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F&title=How%20to%20Implement%20Learning%20to%20Rank%20Model%20using%20Python)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F&text=How%20to%20Implement%20Learning%20to%20Rank%20Model%20using%20Python)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1pzj4BoO1vZGOBvmEoqdI6g.png)](https://towardsdatascience.com/life-and-natures-influence-on-ai-237647e85823/)\n## [Life and Nature's Influence on AI](https://towardsdatascience.com/life-and-natures-influence-on-ai-237647e85823/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow AI algorithms are influenced by our life, nature, and the environment\n[Baijayanta Roy](https://towardsdatascience.com/author/baijayanta/)\nJune 22, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/1rR1JGJBVzkIpC4AotBZ_Hg.png)](https://towardsdatascience.com/two-tower-networks-and-negative-sampling-in-recommender-systems-fdc88411601b/)\n## [Two-Tower Networks and Negative Sampling in Recommender Systems](https://towardsdatascience.com/two-tower-networks-and-negative-sampling-in-recommender-systems-fdc88411601b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nUnderstand the key elements that power advanced recommendation engines\n[Michael Roizner](https://towardsdatascience.com/author/roizner/)\nNovember 24, 20237 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/07/0odOM0-32oqlbOxfu-scaled.jpg)](https://towardsdatascience.com/handling-missing-data-f998715fb73f/)\n## [Handling Missing Data](https://towardsdatascience.com/handling-missing-data-f998715fb73f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nPyTrix #7: Various Techniques to Handle Missing Data\n[Kurtis Pykes](https://towardsdatascience.com/author/kurtispykes/)\nJuly 28, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0bQ-ojy-xfzz7dQFF-scaled.jpg)](https://towardsdatascience.com/time-series-analysis-for-predictive-maintenance-of-turbofan-engines-1b3864991da4/)\n## [Time series analysis for predictive maintenance of turbofan engines](https://towardsdatascience.com/time-series-analysis-for-predictive-maintenance-of-turbofan-engines-1b3864991da4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nUsing distributed lag models to predict remaining useful life\n[Koen Peters](https://towardsdatascience.com/author/kpeters_/)\nOctober 4, 20200 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1yQueo5IA3H_o888eUETLEw.png)](https://towardsdatascience.com/probabilistic-forecasting-of-binary-events-using-regression-4f8a8022ec37/)\n## [Probabilistic Forecasting of Binary Events using Regression](https://towardsdatascience.com/probabilistic-forecasting-of-binary-events-using-regression-4f8a8022ec37/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nForecasting the probability of extreme values with the cumulative distribution function\n[Vitor Cerqueira](https://towardsdatascience.com/author/vcerq/)\nMarch 8, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2017/10/0WupYg4W9jP6np051.jpg)](https://towardsdatascience.com/artificial-intelligence-consequences-bd4dc4d537da/)\n## [Artificial Intelligence: Consequences](https://towardsdatascience.com/artificial-intelligence-consequences-bd4dc4d537da/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAI is going to change the world.\n[Daniel Shapiro, PhD](https://towardsdatascience.com/author/lemaysolutions/)\nOctober 23, 20175 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/08/karl-abuid-7ezVb0oTQ6M-unsplash-1-scaled-1.jpg)](https://towardsdatascience.com/data-mesh-diaries-realities-from-early-adopters/)\n## [Data Mesh Diaries: Realities from Early Adopters](https://towardsdatascience.com/data-mesh-diaries-realities-from-early-adopters/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nEarly-adopter realities gathered from real data mesh implementations\n[Corné Potgieter](https://towardsdatascience.com/author/corne-potgieter/)\nAugust 13, 20256 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/09/1Cl9QtquUeMkvO3o31jv9cg.png)](https://towardsdatascience.com/information-in-noise-08bc05bf6484/)\n## [Information in Noise](https://towardsdatascience.com/information-in-noise-08bc05bf6484/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nTwo Techniques for Visualizing Many Time-Series at Once\n[Lenix Carter](https://towardsdatascience.com/author/lenixc210/)\nSeptember 3, 20244 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/07/1p1JY38aTx_qfu4IApfDxSw-scaled.jpeg)](https://towardsdatascience.com/building-a-chess-ai-that-learns-from-experience-5cff953b6784/)\n## [Building a Chess AI that Learns from Experience](https://towardsdatascience.com/building-a-chess-ai-that-learns-from-experience-5cff953b6784/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nWIth only knowledge of the rules of the game.\n[Victor Sim](https://towardsdatascience.com/author/victorsim14/)\nJuly 11, 20216 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607631/image?etag=1781543525510&width=500&height=500) Critical Mistakes Companies Make When Integrating AI/ML into Their Processes ](https://towardsdatascience.com/critical-mistakes-companies-make-when-integrating-ai-ml-into-their-processes/ \"Critical Mistakes Companies Make When Integrating AI/ML into Their Processes\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n\n\n",
  "metadata": {
    "title": "How to Implement Learning to Rank Model using Python | Towards Data Science",
    "description": "The step-by-step guide on how to implement the lambdarank algorithm using Python and LightGBM",
    "keywords": null,
    "author": "Ransaka Ravihara",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "How to Implement Learning to Rank Model using Python",
    "og:description": "The step-by-step guide on how to implement the lambdarank algorithm using Python and LightGBM",
    "og:url": "https://towardsdatascience.com/how-to-implement-learning-to-rank-model-using-python-569cd9c49b08/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/19M80Da74bRerXVHYVEbFcQ.jpeg",
    "og:image:width": "479",
    "og:image:height": "352",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Ransaka Ravihara",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "9 min read",
    "article:published_time": "2023-01-18T17:15:34.000Z",
    "article:modified_time": "2023-01-18T17:15:34.000Z",
    "article:author": "https://towardsdatascience.com/author/ransakaravihara/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_000.txt",
      "chars": 740
    },
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_001.txt",
      "chars": 1355
    },
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_002.txt",
      "chars": 1212
    },
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_003.txt",
      "chars": 956
    },
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_004.txt",
      "chars": 3865
    },
    {
      "language": "txt",
      "file": "attachments/63f2e5618eb4/code/block_005.txt",
      "chars": 1038
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/0ZUVy9A0kAzs6xHSF-scaled.jpg",
      "alt": "Photo by Andrik Langfield on Unsplash",
      "local_path": "attachments/63f2e5618eb4/images/000.jpg",
      "bytes": 508105,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1VZ3UXU6jNhAqwrthI6DQ2g.jpeg",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/001.jpeg",
      "bytes": 32418,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1SU53hhQdMfT1nmLYPCTPKw.jpeg",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/002.jpeg",
      "bytes": 7735,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1Go-A9MnGc3r4mSWSiPq_Fg.png",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/003.png",
      "bytes": 10660,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1HEEXMuQMF0sjVo52_a_ybA.png",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/004.png",
      "bytes": 11145,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/19M80Da74bRerXVHYVEbFcQ.jpeg",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/005.jpeg",
      "bytes": 14772,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1GuVEy2OBu-C8gG_Pp3EB1Q.png",
      "alt": "Image by Author",
      "local_path": "attachments/63f2e5618eb4/images/006.png",
      "bytes": 42577,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1pzj4BoO1vZGOBvmEoqdI6g.png",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/007.png",
      "bytes": 2238360,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/1rR1JGJBVzkIpC4AotBZ_Hg.png",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/008.png",
      "bytes": 45071,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/07/0odOM0-32oqlbOxfu-scaled.jpg",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/009.jpg",
      "bytes": 548372,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0bQ-ojy-xfzz7dQFF-scaled.jpg",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/010.jpg",
      "bytes": 330706,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1yQueo5IA3H_o888eUETLEw.png",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/011.png",
      "bytes": 136732,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2017/10/0WupYg4W9jP6np051.jpg",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/012.jpg",
      "bytes": 28106,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/08/karl-abuid-7ezVb0oTQ6M-unsplash-1-scaled-1.jpg",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/013.jpg",
      "bytes": 427678,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/09/1Cl9QtquUeMkvO3o31jv9cg.png",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/014.png",
      "bytes": 23078,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/07/1p1JY38aTx_qfu4IApfDxSw-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/63f2e5618eb4/images/015.jpeg",
      "bytes": 574897,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [
    {
      "src": "https://www.youtube.com/c/TowardsDataScience",
      "quality": "unavailable",
      "local_path": "",
      "note": "无1080p且无720p，未交付更低清晰度"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ransakaravihara/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/what-is-learning-to-rank-a-beginners-guide-to-learning-to-rank-methods-23bbb99ef38c"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-evaluate-learning-to-rank-models-d12cadb99d47"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/learning-to-rank/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/recommendation-system/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/life-and-natures-influence-on-ai-237647e85823/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/baijayanta/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/two-tower-networks-and-negative-sampling-in-recommender-systems-fdc88411601b/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/roizner/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@andriklangfield"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://www.kaggle.com/datasets/ransakaravihara/anime-recommendation-ltr-dataset"
    },
    {
      "type": "external",
      "href": "https://github.com/microsoft/LightGBM/issues/3326"
    },
    {
      "type": "external",
      "href": "https://github.com/Ransaka/LTR-with-LIghtGBM"
    },
    {
      "type": "external",
      "href": "https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRanker.html"
    },
    {
      "type": "external",
      "href": "https://www.microsoft.com/en-us/research/project/mslr/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=How+to+Implement+Learning+to+Rank+Model+using+Python&u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=How+to+Implement+Learning+to+Rank+Model+using+Python&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=How+to+Implement+Learning+to+Rank+Model+using+Python&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-implement-learning-to-rank-model-using-python-569cd9c49b08%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:49Z",
  "source_url": "https://towardsdatascience.com/how-to-implement-learning-to-rank-model-using-python-569cd9c49b08/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}