AI Wiki中文/EN

Sequential recommendation: the same items in another order

序列推荐

Learn next-item transitions, back off unseen contexts and keep future events out of the prefix.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A history is more than a bag of items

Two readers have visited articles 0 and 1. One visited 0 then 1; the other visited 1 then 0. A bag of item counts sees the same input, while a next-item model can treat the last action as a different context. Order matters when a short-term task changes what should come next.

Sequential recommendation predicts from an ordered history. A session is a bounded sequence of actions; a basket is a set of items within one action. Their order assumptions differ. Rendle and colleagues study next-basket recommendation, explain finite-order Markov chains, and show why fully parameterized personalized transitions become sparse. FPMC, PDF 3–4 Kang and McAuley’s SASRec instead learns a representation of a user’s preceding item sequence with causal self-attention. SASRec, PDF 3–4

Our worked algorithm is a trained finite-order next-item count model with smoothing and suffix backoff. It provides a small inspectable baseline; the later attention discussion does not claim that this program implements SASRec or factorized personalized Markov chains.

A second previous item separates two prefixes that share the same last item in this synthetic fixture.
A second previous item separates two prefixes that share the same last item in this synthetic fixture.

How much of the past becomes the state?

Let s_1 through s_t be observed item IDs. An order-m approximation keeps only the most recent m items:

P(st+1=j∣s1,…,st)≈P(j∣smax⁡(1,t−m+1),…,st).P(s_{t+1}=j\mid s_1,\ldots,s_t)\approx P(j\mid s_{\max(1,t-m+1)},\ldots,s_t).

Order zero ignores history. Order one uses the last item. Order two can distinguish histories ending (0,1) and (2,1), even though both end in 1. The approximation assumes the chosen context is sufficient; it does not assert that distant preferences are irrelevant in real behavior.

For context c, count how often next item j followed it in training sessions. With V possible items and a positive smoothing parameter alpha, use:

P^(j∣c)=N(c,j)+α∑v=1VN(c,v)+αV.\widehat P(j\mid c)=\frac{N(c,j)+\alpha}{\sum_{v=1}^{V}N(c,v)+\alpha V}.

This is a symmetric add-alpha estimate for a single next item. It sums to one and gives unseen continuations positive probability. FPMC’s basket formulation uses inclusion probabilities for multiple items, whose sum need not be one; copying its basket matrix into this single-item interpretation would change the problem. FPMC, PDF 3, equations 1–6

We store counts for every observed suffix length up to m. At prediction time choose the longest suffix that was observed:

ℓ∗=max⁡{0≤ℓ≤min⁡(m,t):N(st−ℓ+1:t)>0},N(c)=∑jN(c,j).\ell^*=\max\{0\le\ell\le\min(m,t):N(s_{t-\ell+1:t})>0\},\qquad N(c)=\sum_jN(c,j).

The length-zero context is the empty tuple and pools all training next-item targets. If there were no training transitions at all, return a uniform distribution. This is a hard backoff choice, not an interpolation between all context lengths. Smoothing and backoff are separate: smoothing supplies unseen next items within a chosen context; backoff chooses a shorter context when the longer one has no observations.

For held-out prefix–target pairs, average the negative log probability of each target:

NLL⁡=−1T∑a=1Tlog⁡P^(ya∣ca).\operatorname{NLL}=-\frac1T\sum_{a=1}^{T}\log\widehat P(y_a\mid c_a).

Also report hit@1, the fraction whose highest-scored item matches the target. Ties in this implementation choose the smallest ID. NLL tests probabilities; hit@1 checks only the top decision. Neither should be calculated using targets already inserted into the fitted counts.

A causal attention model can use longer contexts without assigning a separate count row to every suffix. With item-plus-position embeddings H and learned projections, one attention layer has the form:

A=softmax⁡row((HWQ)(HWK)⊤d+M),Mij={0,j≤i,−∞,j>i.A=\operatorname{softmax}_{\rm row}\left(\frac{(HW_Q)(HW_K)^\top}{\sqrt d}+M\right),\qquad M_{ij}=\begin{cases}0,&j\le i,\\-\infty,&j>i.\end{cases}

Padding also needs masking. The causal mask prevents position i from attending to later actions; it does not by itself repair a training split that leaked future information into item features. SASRec adds learned positions, pointwise feed-forward layers, residuals and normalization, then scores next items using the prefix representation:

s(j∣s1:t)=ht⊤ej.s(j\mid s_{1:t})=h_t^\top e_j.

The source discusses shared input/output item embeddings. Its nonlinear prefix transformation still permits asymmetric transitions: a followed by b need not imply b followed by a. SASRec, PDF 3–4

Two histories with the same final item

Use Python 3.12 and NumPy 1.26.4. The complete original program trains on 30 synthetic sessions: twelve [0,1,3], twelve [2,1,4], and six [0,2,1,4]. These contain 66 within-session next-item transitions. Eight separate evaluation cases repeat prefixes [0,1]→3 and [2,1]→4. Their labels are not added to training, but their patterns deliberately match the generating rules; this is not a real-world benchmark.

"""Original sparse finite-order next-item model with explicit suffix backoff."""
import json
from collections import Counter
import numpy as np


def sequence(values, vocabulary):
    s=list(values)
    if any(not isinstance(i,(int,np.integer)) or isinstance(i,(bool,np.bool_)) or not 0<=i<vocabulary for i in s):
        raise ValueError('integer item IDs within the vocabulary required')
    return s


def fit(sessions, vocabulary=5, order=2, alpha=.5):
    if not isinstance(vocabulary,int) or vocabulary<1 or not isinstance(order,int) or order<0 or not np.isfinite(alpha) or alpha<=0:
        raise ValueError('positive vocabulary/smoothing and nonnegative order required')
    counts={};transitions=0
    for raw in sessions:
        s=sequence(raw,vocabulary)
        for t in range(1,len(s)):
            for depth in range(min(order,t)+1):
                context=tuple(s[t-depth:t]) if depth else ()
                if context not in counts:counts[context]=np.zeros(vocabulary)
                counts[context][s[t]]+=1
            transitions+=1
    return dict(counts=counts,vocabulary=vocabulary,order=order,alpha=float(alpha),transitions=transitions)


def predict(model,prefix):
    s=sequence(prefix,model['vocabulary']);counts=model['counts'];chosen=()
    for depth in range(min(len(s),model['order']),-1,-1):
        key=tuple(s[-depth:]) if depth else ()
        if key in counts:chosen=key;break
    row=counts.get(chosen,np.zeros(model['vocabulary']));alpha=model['alpha']
    return (row+alpha)/(row.sum()+alpha*len(row)),chosen


def evaluate(model,cases):
    if not cases:raise ValueError('nonempty held-out cases required')
    hits=[];nll=[]
    for prefix,target in cases:
        sequence([target],model['vocabulary']);p,_=predict(model,prefix)
        hits.append(int(np.argmax(p)==target));nll.append(-float(np.log(p[target])))
    return dict(hit_at_1=float(np.mean(hits)),nll=float(np.mean(nll)),cases=len(cases))


def before(events, cutoff):
    if any(len(row)!=2 or not isinstance(row[0],int) for row in events):raise ValueError('integer time/item pairs required')
    if any(events[i][0]>=events[i+1][0] for i in range(len(events)-1)):raise ValueError('strict time order required')
    return [item for time,item in events if time<=cutoff]


def demo():
    train=[[0,1,3]]*12+[[2,1,4]]*12+[[0,2,1,4]]*6
    heldout=[([0,1],3),([2,1],4)]*4
    rows=[]
    for order in [0,1,2]:
        m=fit(train,order=order);row=dict(order=order,**evaluate(m,heldout))
        row['probabilities']=[predict(m,p)[0].tolist() for p in [[0,1],[2,1]]];rows.append(row)
    model=fit(train);p,context=predict(model,[4,4,1])
    events=[(1,0),(2,1),(3,3),(4,4)]
    return dict(rows=rows,training_sessions=len(train),training_transitions=model['transitions'],
                prefix_at_2=before(events,2),backoff_context=list(context),backoff_probabilities=p.tolist(),
                same_bag=[dict(prefix=s,bag=dict(Counter(s)),probabilities=predict(model,s)[0].tolist()) for s in [[0,1],[1,0]]])


if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

With alpha=0.5, orders zero, one and two give hit@1 values 0, 0.5 and 1, and NLL values about 1.505084, 0.759490 and 0.125537. The order-one model assigns the same probabilities to both prefixes and favors item 4. Order two assigns target probabilities 0.862069 and 0.902439, separating the contexts.

An unseen prefix [4,4,1] backs off to [1], not an invented order-two row. An empty model returns uniform probabilities. The time helper turns events at times 1,2,3,4 into prefix [0,1] at cutoff 2; appending later events leaves that prefix unchanged. Tests also ensure that the end of one session is never linked to the beginning of another.

With T transitions, maximum order m, V items and C distinct stored contexts, count arrays require O(C V) space, plus the context keys. Tuple construction and hashing make training approximately O(T (m+1)² + C V) in this implementation. Prediction searches suffixes in O((m+1)²), then normalizes a V-entry row in O(V). For fixed m=2 this is small; raising m can make the number of possible contexts grow as V to the power m. The sparse dictionary avoids allocating every possible context but cannot manufacture missing evidence. Dense attention over length L instead carries O(L²) attention entries per layer, alongside its projection and value computations.

A later action is a label, not a feature

Split sequences before forming targets or constructing features that use future actions. Keep equal-time event ordering and session boundaries explicit. A user’s future clicks, edited item metadata or a post-event summary can leak even when the attention mask is triangular.

The count model pools transitions across users. It captures contextual order but has no persistent user vector, no elapsed-time model and no learned item semantics. Rare long contexts can overfit; a shorter order can work better with little data. Next-item prediction may also legitimately recommend an item already consumed, so the no-repeat policy from a reading-app example is not universal. Compare with order zero or popularity, state the candidate set, and choose smoothing/order on a separate validation split.

What belongs in the prefix?

  1. Why can [0,1] and [1,0] receive different predictions despite identical bags? Answer: Their ordered suffixes differ. An order-aware model uses that difference; a bag of counts loses it.
  2. Context [0] was followed by item 1 twice and item 2 once. With V=3 and alpha=0.5, what is P(1)? Answer: 2.5/4.5. The denominator adds a total prior count of 1.5 to the three observations.
  3. Why does [4,4,1] use context [1] in this example? Answer: Its two-item suffix [4,1] was never observed, but the one-item suffix [1] was. Hard backoff selects the longest observed suffix.
  4. Does causal attention make it safe to construct item features from the user’s entire future history? Answer: No. The mask blocks later sequence positions, not information already leaked into an input feature. Features and splits must respect the same decision-time boundary.

From explicit contexts to learned ones

The FPMC reading supports the order definition, basket distinction and sparsity problem; the SASRec method pages support causal attention and prefix representations. Our smoothing, hard backoff and authored sessions are disclosed teaching choices. No basket tensor factorization, self-attention training or published result is reproduced. To extend the exercise, change the generating process so that old preferences matter beyond the last two items, then test whether the chosen context length discards that signal.

Make a prediction, then check

Two histories end in the same item. Must a second-order model predict the same distribution?

Choose one answer

Learning objectives

  • Compare finite-order transitions with causal attention and distinguish a sequence from an unordered basket.
  • Run the original computation and explain a counterexample without claiming a public benchmark result.

Prerequisites & connections

Explore related knowledge →

References

  1. Factorizing Personalized Markov Chains for Next-Basket Recommendation
    Steffen Rendle; Christoph Freudenthaler; Lars Schmidt-Thieme · 2010
  2. Self-Attentive Sequential Recommendation
    Wang-Cheng Kang; Julian McAuley · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF 1 identity and 3–4 text: Markov order, basket marginals, transition estimation and sparsity. Teaching code is a smoothed single-next-item suffix model, not FPMC factor training. Read PDF 1 identity and 3–4 methods text: shifted targets, positions, causal mask, FFN, residuals and shared item embeddings. No full-model reproduction or visual figure review. 6 paired equations and four explained exercises. Checked smoothed suffix counts, order0/1/2, hard backoff, session boundaries, time cutoff and unseen context.30 synthetic sessions/66 transitions; not SASRec or FPMC training.

  • Checked smoothed suffix counts, order0/1/2, hard backoff, session boundaries, time cutoff and unseen context.30 synthetic sessions/66 transitions; not SASRec or FPMC training.
  • Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.