Recommend related items by co-occurrence lift

Why it matters Related-item rails in e-commerce and media apps often start from co-occurrence statistics like lift.

"People who bought this also bought" lists come from items that appear together in sessions. Raw co-occurrence favours popular items; lift corrects for popularity.

Write cooccur_recs(sessions, item, k, min_count=1). sessions is a list of item lists. Treat each session as a SET (repeats inside one session count once). With N sessions, c_x = number of sessions containing x and c_xy = number containing both. For every other item y with c_(item, y) >= min_count, lift = c_xy * N / (c_item * c_y). Return a list of (y, lift) for the top k by lift, ties by larger c_xy, then smaller id. Return [] if item never appears.

Signaturedef cooccur_recs(sessions, item, k, min_count=1)

Example

cooccur_recs([[1, 2], [1, 3], [2, 3], [1, 2, 2]], 1, 2) gives [(2, 0.8889), (3, 0.6667)].

Understand the idea

If two items often appear in the same basket, they are probably related. But raw counts mislead: milk appears with everything because everyone buys milk. Lift asks a sharper question: do these two appear together more often than chance would predict?

Example: 4 sessions. Item 1 is in 3, item 2 in 3, both together in 2. If they were independent, we would expect 3 * 3 / 4 = 2.25 sessions with both. We saw 2, so lift = 2 / 2.25 = 0.89. A lift above 1 means a real association; below 1 means they appear together less than chance.

Rule: lift(x, y) = c_xy * N / (c_x * c_y), with counts taken over sessions treated as sets.

A minimum co-occurrence count is usually added, because two rare items seen together once can get a huge but meaningless lift.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecooccur_recs([[1, 2], [1, 3], [2, 3], [1, 2, 2]], 1, 2)
  • Sample 2: popular item penalisedcooccur_recs([[1, 9], [2, 9], [3, 9], [4, 9], [1, 5], [1, 9, 5], [6]], 1, 3)