A04 · Sponsored-search matching and quality ranking
Prerequisites: foundations 31–34; A03.
Evidence: explicitly constructed mechanism experiments, not real ad logs. This chapter does not claim industrial-system reproduction or online gains.
Learning order: predict → change one variable → run → explain.
English companion. All instructional Markdown is translated. Experiment code, Chinese language examples, execution counts, and saved outputs remain as in the source edition; historical output text may therefore be Chinese. The initial setup cell anchors the working directory and Python import path for this companion's deeper folder; it does not change the experiment. Saved outputs are historical evidence, not a new run. Run from the top after preparing the required data and models.
# English companions live one directory deeper; keep the original experiment code unchanged.
from pathlib import Path as _TranslationPath
import os as _translation_os
import sys as _translation_sys
_translation_root = next((p for p in [_TranslationPath.cwd(), *_TranslationPath.cwd().parents]
if (p / "reclab").is_dir()), None)
if _translation_root is None:
raise RuntimeError("Open this notebook from inside the Search Recommendation Ads Lab checkout.")
_translation_os.chdir(_translation_root)
if str(_translation_root) not in _translation_sys.path:
_translation_sys.path.insert(0, str(_translation_root))
Problem and input/output contract
Organic retrieval answers information needs. Ad candidates must additionally satisfy campaign status, geography, creative, and budget eligibility. Here keywords trigger by OR, geography/status filter by AND, and quality×CPC bid determines rank. Quality is constructed, not a landing-page score derived from anonymous Criteo fields. Real systems also need review and landing-page consistency.
Before running, predict which result the changed variable will affect and which invariants must hold.
from pathlib import Path
import sys
root=Path.cwd()
if not (root/'reclab').exists(): root=root.parent
if str(root) not in sys.path: sys.path.insert(0,str(root))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from reclab import ads_curriculum as acRun the one-variable comparison
Inputs are small constructed examples visible in source. Output units and constraints are defined above. Run assertions to verify mathematics and accounting.
pool=ac.candidates();display(pd.DataFrame([{k:a[k] for k in ('id','quality','bid')} for a in pool]))
assert [a['id'] for a in pool]==['a','b']
print('北京', [a['id'] for a in ac.candidates(region='北京')])
print('未匹配查询',ac.candidates(query='药品'))
organic=['跑鞋选购知识','运动损伤预防'];print('自然结果',organic,'商业候选',[a['id'] for a in pool])Saved notebook output · not executed on this page
| id | quality | bid | |
|---|---|---|---|
| 0 | a | 0.8 | 2.0 |
| 1 | b | 0.5 | 2.5 |
北京 ['b'] 未匹配查询 [] 自然结果 ['跑鞋选购知识', '运动损伤预防'] 商业候选 ['a', 'b']
Interpretation and limits
The largest raw bid does not rank first. Disabled candidate c cannot display even with high quality and bid. Organic results remain separate; document IDs are not ad campaigns. Changing only geography changes eligibility.
Inspect source, then try an exercise
Implement phrase matching and negative keywords. Compare “便宜跑鞋” (cheap running shoes) with “二手跑鞋” (second-hand running shoes), checking that hard constraints apply before ranking.
import inspect
print(inspect.getsource(ac.candidates))Saved notebook output · not executed on this page
def candidates(query='跑鞋', region='上海', topk=3):
ads=inventory(); index={}
for a in ads:
for key in a['keywords']: index.setdefault(key,set()).add(a['id'])
tokens=set(query.split()); recalled=set().union(*(index.get(t,set()) for t in tokens))
eligible=[a for a in ads if a['id'] in recalled and region in a['regions'] and a['active'] and a['budget']>0]
oracle=[a for a in ads if tokens & a['keywords'] and region in a['regions'] and a['active'] and a['budget']>0]
assert {a['id'] for a in eligible}=={a['id'] for a in oracle}
return sorted(eligible,key=lambda a:(-a['quality']*a['bid'],a['id']))[:topk]
Sources and next step
A-CCR pp. 18–20 and 39; search-market topics in A-NJU. This is an original Lab exercise, not a copy of the complete lecture text.
Chinese GitHub chapter · Authors’ RTB slides. The Chinese deck is not a complete modern advertising-engineering course. Historical descriptions of platforms are not presented as current market facts.
After the exercise, return to the ads learning path and continue to the next semantic unit.