Scoring Song Impressions: A Click Model for a Music Feed
Machine LearningModel answerLast updated
Design a model that estimates the chance a user clicks a recommended track, covering song representation, sparse feature handling, algorithm choice, calibration, and offline and online evaluation.
A music streaming app shows users recommended songs. You need to build a model that, for a given user, candidate song, and display context (time, device, surface, position), outputs the probability that this impression leads to a click.
Assumptions
- Candidate retrieval is out of scope. Another component supplies the songs, and your model only scores them.
- Training data is a log of impressions. Each one has a binary label: whether a click occurred within a fixed attribution window.
- The attribution window, the serving latency budget, and the available song metadata are not given. Ask about them.
Your answer should cover
- Clarifying questions you would ask and how the answers change your design.
- How you build labels and features without leaking information that would not exist at display time.
- How you represent songs, including new songs and songs with little history.
- How you handle extremely sparse features (high-cardinality IDs, rare categories, mostly missing values).
- Which algorithm(s) you would try, with a simple baseline and a stronger model, and the trade-offs.
- How you evaluate the predictions offline (probability quality and ranking) and online, including guardrails so that optimizing clicks does not hurt listening quality.
Hints
Hint 1
Start from the label and the prediction moment: every feature must be computable using only data available when the impression was shown, and validation splits should respect time.
Hint 2
For songs, combine a learned ID embedding with content-based vectors (metadata, audio, text), and think about what to fall back on when a song has almost no impressions.
Hint 3
For sparse features, think hashing or frequency thresholds, embeddings with regularization, and explicit missing indicators. Then decide how a model captures user-song interactions (logistic regression with crosses vs. factorization or deep models vs. gradient-boosted trees).
Hint 4
Separate two goals: ranking quality (AUC, NDCG) and probability quality (log loss, calibration curves). Mention position bias and what you would monitor online beyond CTR.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the problem
Questions I would ask first:
- Click definition and window. Is a click a tap on the card, or a play lasting more than N seconds? A 30-minute window versus same-session changes label noise and how long I must wait before a training row is final.
- Features at serving time. Which user history, song metadata, and audio-derived signals are available in the online path, and how fresh are they?
- Sparsity type. Are we dealing with huge ID spaces (user, song, artist), rare categories (niche genres), or mostly-missing numeric values? Each needs a different treatment.
- Calibration need. If scores are only used to rank, ranking metrics suffice. If they feed blending, budgeting, or thresholds with other models, calibrated probabilities matter.
- Latency. A typical budget is a few tens of milliseconds for scoring a few hundred candidates, which rules out very heavy models unless they are precomputed or distilled.
2. Labels and features
- One row per impression. Label = click within the window. Rows younger than the window are excluded or marked pending to avoid false negatives.
- Deduplicate repeated impressions of the same song, or keep them and add a "times shown before" feature, since repeated exposure often lowers CTR.
- Leakage control: compute history features (user's recent clicks, song's historical CTR) as of the impression timestamp, using a point-in-time feature store. A common mistake is using a song's overall CTR that includes the very click being predicted.
- Feature groups: user (tenure, genre affinity, recent skips), song (artist, genre, age, popularity, audio embedding), context (hour, device, surface, position), and cross features (user-genre match, user-artist affinity).
3. Representing songs
- Learned ID embedding (for example 32 to 64 dimensions) trained inside the CTR model or from co-listening data (item2vec style). It captures behavior but is weak for rare songs.
- Content embedding from audio (spectrogram encoder), lyrics or text, and metadata (artist, genre, tags, release date). It works from day one.
- Combination: concatenate or gate ID and content embeddings. For songs below an impression threshold, the ID embedding is replaced by a shared "unknown" vector or an embedding predicted from content, so cold-start songs lean on content.
- Add the artist embedding as a shared parent, so a new song inherits signal from its artist.
- Refresh embeddings on a schedule, and version them so that training and serving use the same one.
4. Handling extreme sparsity
- Rare categories: bucket anything below a frequency threshold (say, fewer than 50 impressions) into an "other" bin.
- Hashing trick for very large ID spaces, with a table sized to tolerate some collisions (for example 2^22 buckets per field). It bounds memory and handles unseen values.
- Embeddings with regularization (L2 or dropout on embeddings, smaller dimension for rare fields) instead of one-hot vectors.
- Missing values: add an explicit missing indicator and impute with a neutral value. In tree models, native missing handling works well. Do not impute with the mean silently, because missingness is often informative.
- Smoothed target statistics: for example CTR_smoothed = (clicks + m·prior) / (impressions + m). This shrinks noisy rates for low-volume entities toward the global or parent rate.
- Sparse-friendly training: use optimizers such as Adagrad or FTRL, which update only the active features.
5. Model choice
| Model | Strengths | Weaknesses |
|---|---|---|
| Logistic regression with hashed features and a few crosses | Fast, well calibrated, easy to debug, strong baseline | Needs hand-built crosses, limited interactions |
| Gradient-boosted trees | Strong on dense and aggregated features, handles missing values | Poor with huge ID spaces, slower to update |
| Factorization machine or two-tower with interaction | Learns user-song interactions from sparse IDs | Needs care for cold start |
| Deep model (Wide and Deep, DeepFM, DCN) | Memorization (wide) plus generalization (deep), shared embeddings | More cost, harder to calibrate and debug |
My plan: ship the logistic regression baseline first to set a floor and validate the pipeline, then move to a Wide and Deep or DeepFM style model with embeddings. Keep the wide part for memorizing frequent user-song pairs and the deep part for generalizing to rare ones. Handle position bias by including position as a training feature and fixing it to a default value at serving, or by using a separate position tower.
Class imbalance (CTR is often 1 to 5 percent) is usually fine with log loss. If negatives are downsampled to save compute, correct the output: p = q / (q + (1 − q)/w), where w is the negative keep rate inverse.
6. Evaluation
Offline
- Time-based split: train on the past, validate on the following days. Random splits leak future behavior and inflate results.
- Probability quality: log loss, calibration curve and expected calibration error, and per-segment calibration (new users, new songs). Fix miscalibration with Platt scaling or isotonic regression on a held-out recent slice.
- Ranking quality: AUC overall and per-user or per-session (GAUC), plus NDCG or recall at k on grouped impressions.
- Slices: cold-start songs, light users, each surface and device.
Online
- A/B test against the current ranker. Primary metric is CTR or clicks per session, but click optimization can promote clickbait-like covers or popular tracks.
- Guardrails: play-through or listening time per click, skip rate within 30 seconds, saves and follows, catalog diversity, new-song exposure, and long-term retention.
- Monitor feature drift, calibration drift, and the share of fallback embeddings, with alerting and retraining on a regular cadence (daily or weekly).
- Consider a small exploration slice so cold songs gather unbiased data, and use it for counterfactual evaluation because the logs are biased by the old ranker.
Common mistakes
- Leaking post-impression data into features or using random splits.
- Treating rare IDs as reliable, so the model overfits to a few clicks.
- Reporting only AUC when calibrated probabilities are required.
- Ignoring position bias and learning that "top slot" means "good song".
- Judging success by CTR alone without listening-quality guardrails.