Algorithmresearch
GRU4Rec
Also called recurrent session-based recommendation.
Feeds the items of a session to a gated recurrent network and trains it with ranking losses to score the next item.
- Time
- O(E N (H^2 + B H)) worst
- Space
- O(n H + H^2) extra
- Where
- B = the number of sessions per mini-batch; E = the number of epochs; H = the number of hidden units; N = the number of events in the training sessions; n = the number of items
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas, Domonkos Tikk, 2016
GRU4Rec is the session-based recommender of Hidasi, Karatzoglou, Baltrunas and Tikk (2016). It reads the items of a session one at a time with a gated recurrent unit (GRU) network, a kind of recurrent network, and after each item it scores every item as the next one. It trains with ranking losses on the items of the same mini-batch as negatives, and it builds mini-batches from many sessions in parallel, so that sessions of very different lengths can share one batch. It needs no user profile: the hidden state of the network is the state of the session. The paper reported large gains over item-to-item nearest neighbors on two data sets. That is a measurement, and later comparisons measured simple methods doing as well on other data.
In plain words
A user clicks a few items in a row, with no login and no history. The model keeps a short memory, a vector, and updates it after each click. From the memory it gives each item a score for "this comes next".
The memory update has two gates. One decides how much of the old memory to keep, the other how much of it to use when making a new proposal. Training shows the model real sessions and moves the weights so that the true next item scores higher than the other items in the batch.
The problem
The input is a set of sessions, each a sequence of items from items. The task of session-based recommendation is, after each prefix , to rank the items so that is near the top. The quality is measured by recall@20 and MRR@20 on held-out sessions.
The model has input weights (one column per item, since the input is one-hot), recurrent weights of size , and output vectors and biases . After step the score of item is . With target and negatives , the two losses of Section 3.1.3 are
BPR is the loss of Bayesian personalized ranking averaged over the negatives. TOP1 is a smooth form of the relative rank of the target, plus a term that pushes the scores of negatives toward 0.
The algorithm
GRU4REC-TRAIN(sessions, H, B, E, η)- 1
draw all weights at random - 2
repeat E times - 3
for each session-parallel mini-batch of B lanes do - 4
for each lane: h ← 0 if its session starts here, else the state the lane carried - 5
read the input item with GRU-STEP; score the target and the other targets of the batch; get the loss gradient by backpropagation - 6
add the gradients of all lanes - 7
step all weights against the summed gradient with rate η - 8
return the weights GRU-STEP(x, h)- 9
z ← σ(W_z[x] + U_z h); r ← σ(W_r[x] + U_r h) ▷ update gate and reset gate - 10
ĥ ← tanh(W_h[x] + U_h (r ⊙ h)) ▷ candidate state - 11
return (1 - z) ⊙ h + z ⊙ ĥ
Lines L9 to L11 are Equations 2 to 5 of the paper. Session-parallel mini-batches (Section 3.1.1, Figure 2) work as follows. Put the sessions in an order. The first batch holds the first event of each of the first sessions, with the second events as targets. The next batch holds the second events, and so on. When a session runs out, the next unused session takes its lane and the hidden state of that lane is reset to 0. The negatives of each event are the targets of the other events in the batch (Section 3.1.2). An item is in a batch about as often as it is clicked, so this is sampling in proportion to popularity, and it costs no separate draws.
The code writes the backpropagation through time by hand. The training loop carries each lane's hidden state into the next batch but treats it as a constant, so the gradient of a batch stops at the step boundary. That cut is a choice of this code; the paper does not say how far its gradient runs back. The paper trains with Adagrad and puts tanh on the output scores (Section 4.2); the code uses plain stochastic gradient steps and linear scores.
Example
Take and an item with , , all recurrent weights 0, and .
- Line L9: .
- Line L10: .
- Line L11: .
Let the target have and one negative have , both with bias 0. The scores are and .
- BPR: . Its derivative in is , so a step raises the target score.
- TOP1: . The second term is large even though the negative ranks below the target; it pushes toward 0.
For the mini-batches, take sessions , , , , , and . Session has no target and is skipped. The first batch is the events , , . Session is then done, so in the second batch its lane starts with a reset: , , . The test file checks these values.
Correctness
The proof in proofs/correctness.md shows that the hand-written backward pass is the exact gradient of the summed loss over a sequence: the loss derivatives in the scores, the output layer, and one GRU step backward, then an induction from the last step to the first. It also shows that the session-parallel batches visit each event of each session of length at least 2 exactly once, in order, with a reset at the first event. The tests check every gradient entry against finite differences for both losses. Whether the trained model ranks well is a question of measurement, not of proof.
Proof: The hand-written backward pass of GRU4Rec is the gradient of the ranking loss, and the session-parallel batches visit every event oncefull
The notation is that of the page. A sequence has inputs , targets , negative lists and a fixed start state . For ,
the scores are for , and the loss is with the BPR or the TOP1 loss of the page. Every function in the chain (, , products, sums, ) is smooth, so is a smooth function of all the parameters and the chain rule applies everywhere.
Lemma 1 (the losses). With the target, and :
- BPR, : and .
- TOP1, : and .
Proof. , so and the derivative in is the negative of that. For TOP1, has derivative in and in , and has derivative in . The code computes these. A negative list that contains twice is a sum, which the code also handles, since it adds.
Lemma 2 (the output layer). Let . Then , , and .
Proof. is bilinear in and and linear in .
Lemma 3 (one GRU step backward). Let , the total derivative through all later steps and the output of step . Then, entry by entry,
the gradient contributions of step are to , to , to , and to the rows , and
Proof. depends on directly (through ), and through , and . The direct path gives . The product rule on gives and , so and are as stated. and give , , . The argument enters through , so , and passes to and to . The pre-activations and pass and to . Each pre-activation has and , and no other row of appears, because the input is one-hot.
Theorem 4 (the backward pass is the gradient). sequence_loss_and_grad returns and its exact gradient in every parameter.
Proof. The loop runs and keeps dh_next, which on entry to step holds through the steps after (zero for , since no later step exists). It adds (Lemma 2, with from Lemma 1), so dh is , the full derivative: affects only through and through step . It then adds the contributions of Lemma 3 and sets dh_next to through step , which is everything after except the output at ; that output is added at the next iteration. By induction from downward the invariant holds at every step. Each parameter is shared across steps, and its gradient is the sum of the contributions of all steps, which is what the code adds. is a constant and gets no gradient.
The tests compare every entry of this gradient with a central finite difference for both losses on a sequence of four steps with a nonzero .
Proposition 5 (session-parallel batches). session_parallel_batches(sessions, X) returns batches in which (a) each session of length contributes exactly the events , , in order, (b) the reset flag is true exactly at , (c) no batch has more than events or two events of one session, and (d) sessions shorter than 2 contribute nothing.
Proof. Each lane holds at most one session and a position in it. A lane at position emits with the flag , then moves to if exists, and otherwise takes the next session from the queue at position 1 or goes idle. So a lane emits the events of one session in order, from the first to the last, and then moves on, which gives (a) and (b) for each session it takes. The queue holds each session of length at least 2 once and is read in order, so each such session is taken by exactly one lane, and the loop runs until all lanes are idle, so every taken session is finished. Each batch takes at most one event per lane, which gives (c). Sessions shorter than 2 are not in the queue, which gives (d).
A training step. In train, a lane carries its hidden state from one batch to the next and resets it to 0 at the start of a session, as in Section 3.1.1 of the paper. The gradient of a batch is the exact gradient of the sum of the one-step losses with each carried state treated as a constant (Theorem 4 with ). That is the gradient of the full loss with backpropagation cut at the step boundary, not the full gradient through the session. The page states this choice. This page does not prove that the steps converge, or that the model ranks well; ranking quality is measured.
Complexity
- One step. The GRU step costs for the three recurrent products, and the scores and their gradients cost per scored item. With in-batch negatives each event scores items, so one event costs .
- One epoch. events, so . The batching itself is .
- Training. for epochs.
- Space. for the input and output weights and for the recurrent weights, plus the hidden states of the active lanes.
- Prediction. Reading a session of length costs and scoring all items costs .
Properties
- No user model. The state is built from the session alone, so a new or anonymous user can get recommendations after one click.
- Order aware. The state after depends on the order of the items, unlike a sum of item vectors.
- Smooth loss. Both losses are smooth in all weights, so the gradient exists everywhere.
- Not convex. The products in the GRU make the loss non-convex, and training finds a local solution.
- Popularity bias in the negatives. In-batch negatives are popular items more often, which changes what the loss pushes down.
Variants and improvements
- Loss functions. The paper found pointwise cross-entropy often unstable and used BPR and TOP1 (Section 4.2). Hidasi and Karatzoglou (2018) added the BPR-max and TOP1-max losses and extra sampled negatives, and reported gains of up to 35% in MRR and recall@20 over the earlier RNN.
- Larger layers. The paper reported better results with 1000 hidden units than with 100 for the pairwise losses (Table 3).
- Deeper networks. The paper tried more GRU layers and found one layer best on its data.
- Self-attention. SASRec replaces the recurrent state by causal self-attention over the past items. An attention or transformer page does not yet exist on the site.
- Other units. The paper reported that a plain recurrent unit and an LSTM did worse than the GRU in its experiments.
When to use it
Hidasi et al. evaluated on RSC15, the RecSys Challenge 2015 clicks (7,966,257 training sessions with 31,637,239 clicks on 37,483 items), and VIDEO, a video service (about 3 million sessions). Their best baseline was session-based item-to-item nearest neighbors. In Table 3, a GRU with 1000 units and the TOP1 loss reached recall@20 of 0.6206 and MRR@20 of 0.2693 on RSC15, which they reported as 22.53% and 31.49% above item-KNN, and the BPR loss reached recall@20 of 0.6322. On VIDEO, TOP1 with 1000 units reported recall@20 of 0.6624 and MRR@20 of 0.3891.
These are measurements on two data sets with one protocol. Ludewig and Jannach (2018) compared session-based methods on more data sets and found that simple nearest neighbor methods often did as well as or better than GRU4Rec. Use GRU4Rec when sessions are anonymous and the order of the items matters, and compare it with a well-tuned session nearest neighbor baseline.
Pitfalls
- Weak baselines. As with other neural recommenders, a poorly tuned nearest neighbor baseline makes the network look better than it is.
- Unstable pointwise loss. The paper reports that cross-entropy gave only 10 and 6 numerically stable networks out of 100 random runs on RSC15 and VIDEO.
- The hidden state at session ends. Forgetting to reset the state when a lane switches sessions leaks one session into the next.
- Truncated gradients. Stopping the gradient at the batch boundary, as this code does, means the weights never get a signal from more than one step back. It is cheap but it is not the full gradient.
- Target in the negatives. If two lanes have the same target, that item is a positive for one lane and a negative for the other. The code drops a lane's own target from its negatives.
- Gradient checks. Check the backward pass with finite differences on a nonzero start state, or the gradients of the first step are zero and the check proves less.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gru4rec/. The authors are listed in prov/6CBA3Q.jsonl.
"""GRU4Rec (Hidasi, Karatzoglou, Baltrunas and Tikk, ICLR 2016), by hand.
The input of step t is the item x_t as a one-hot vector, so W x_t is the
column of W for item x_t; here the input weights are stored by item, as rows
Wz[x], Wr[x], Wh[x] of length H. The GRU of Equations 2 to 5 of the paper:
z_t = sigma(Wz[x_t] + Uz h_(t-1))
r_t = sigma(Wr[x_t] + Ur h_(t-1))
hh_t = tanh(Wh[x_t] + Uh (r_t * h_(t-1)))
h_t = (1 - z_t) * h_(t-1) + z_t * hh_t
The score of item j after step t is O[j] . h_t + c[j]. The loss of step t
compares the target item i with a list of negative items j (N_S of them):
BPR: -(1/N_S) sum_j ln sigma(r_i - r_j)
TOP1: (1/N_S) sum_j sigma(r_j - r_i) + sigma(r_j^2)
`sequence_loss_and_grad` runs the forward pass over a sequence and the
backward pass through time, written by hand. Training uses session-parallel
mini-batches with the targets of the other lanes as negatives, and stops the
gradient at the step boundary (the hidden state is carried, not
differentiated through). That cut is a choice of this module, not of the
paper. The gradient check covers full sequences. The paper also uses tanh on
the output scores and Adagrad; this module uses linear scores and plain SGD.
Parameters are a dict of 2-D lists.
"""
import math
import random
Matrix = list[list[float]]
Params = dict[str, Matrix]
def sigmoid(z: float) -> float:
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
e = math.exp(z)
return e / (1.0 + e)
def log_sigmoid(z: float) -> float:
if z >= 0:
return -math.log1p(math.exp(-z))
return z - math.log1p(math.exp(z))
def matvec(a: Matrix, v: list[float]) -> list[float]:
return [sum(x * y for x, y in zip(row, v)) for row in a]
def tmatvec(a: Matrix, v: list[float]) -> list[float]:
"""a^T v."""
out = [0.0] * len(a[0])
for row, s in zip(a, v):
if s != 0.0:
for c, x in enumerate(row):
out[c] += x * s
return out
def init(n_items: int, hidden: int, seed: int = 1, scale: float = 0.3) -> Params:
"""Gaussian start. Cost O(n_items H + H^2)."""
rng = random.Random(seed)
def mat(r: int, c: int) -> Matrix:
return [[rng.gauss(0.0, scale) for _ in range(c)] for _ in range(r)]
return {
"Wz": mat(n_items, hidden), "Wr": mat(n_items, hidden), "Wh": mat(n_items, hidden),
"Uz": mat(hidden, hidden), "Ur": mat(hidden, hidden), "Uh": mat(hidden, hidden),
"O": mat(n_items, hidden), "c": [[0.0] * n_items],
}
def gru_step(p: Params, x: int, h: list[float]) -> dict:
"""One GRU step from state h with input item x. Cost O(H^2)."""
az = [a + b for a, b in zip(p["Wz"][x], matvec(p["Uz"], h))]
ar = [a + b for a, b in zip(p["Wr"][x], matvec(p["Ur"], h))]
z = [sigmoid(v) for v in az] # @line L9
r = [sigmoid(v) for v in ar]
rh = [a * b for a, b in zip(r, h)]
hh = [math.tanh(a + b) for a, b in zip(p["Wh"][x], matvec(p["Uh"], rh))] # @line L10
new = [(1.0 - zz) * hp + zz * hc for zz, hp, hc in zip(z, h, hh)] # @line L11
return {"x": x, "h_prev": h, "z": z, "r": r, "rh": rh, "hh": hh, "h": new}
def scores(p: Params, h: list[float], items: list[int]) -> list[float]:
"""O[j] . h + c[j] for the listed items. Cost O(len(items) H)."""
return [sum(a * b for a, b in zip(p["O"][j], h)) + p["c"][0][j] for j in items]
def step_loss(kind: str, rs: list[float]) -> tuple[float, list[float]]:
"""Loss and its derivative in the scores. rs[0] is the target, rs[1:] the negatives."""
ri, neg = rs[0], rs[1:]
ns = len(neg)
if ns == 0:
return 0.0, [0.0] * len(rs)
d = [0.0] * len(rs)
total = 0.0
if kind == "bpr":
for k, rj in enumerate(neg, start=1):
total -= log_sigmoid(ri - rj) / ns
g = sigmoid(rj - ri) / ns
d[0] -= g
d[k] += g
elif kind == "top1":
for k, rj in enumerate(neg, start=1):
a, b = sigmoid(rj - ri), sigmoid(rj * rj)
total += (a + b) / ns
d[0] -= a * (1.0 - a) / ns
d[k] += (a * (1.0 - a) + b * (1.0 - b) * 2.0 * rj) / ns
else:
raise ValueError("kind must be 'bpr' or 'top1'")
return total, d
def zeros_like(p: Params) -> Params:
return {name: [[0.0] * len(row) for row in mat] for name, mat in p.items()}
def sequence_loss_and_grad(
p: Params, xs: list[int], ys: list[int], negs: list[list[int]], h0: list[float], kind: str
) -> tuple[float, Params, list[float]]:
"""Loss summed over the steps, its gradient by backpropagation through time, and the last state.
Step t reads xs[t] and is scored on target ys[t] against the items negs[t].
h0 is a constant. Cost O(T (H^2 + N_S H)) for T steps.
"""
caches, total, dscores = [], 0.0, []
h = h0
for x, y, neg in zip(xs, ys, negs):
c = gru_step(p, x, h)
items = [y] + neg
loss, d = step_loss(kind, scores(p, c["h"], items))
total += loss
caches.append(c)
dscores.append((items, d))
h = c["h"]
g = zeros_like(p)
dh_next = [0.0] * len(h0)
for c, (items, d) in zip(reversed(caches), reversed(dscores)):
dh = dh_next[:]
for j, dj in zip(items, d):
g["c"][0][j] += dj
for k in range(len(dh)):
g["O"][j][k] += dj * c["h"][k]
dh[k] += dj * p["O"][j][k]
x, hp, z, r, rh, hh = c["x"], c["h_prev"], c["z"], c["r"], c["rh"], c["hh"]
dhh = [a * b for a, b in zip(dh, z)]
dz = [a * (b - e) for a, b, e in zip(dh, hh, hp)]
dhp = [a * (1.0 - b) for a, b in zip(dh, z)]
dah = [a * (1.0 - b * b) for a, b in zip(dhh, hh)]
drh = tmatvec(p["Uh"], dah)
dr = [a * b for a, b in zip(drh, hp)]
dhp = [a + b * e for a, b, e in zip(dhp, drh, r)]
daz = [a * b * (1.0 - b) for a, b in zip(dz, z)]
dar = [a * b * (1.0 - b) for a, b in zip(dr, r)]
for name, da, inp in (("h", dah, rh), ("z", daz, hp), ("r", dar, hp)):
gw, gu = g["W" + name][x], g["U" + name]
for k in range(len(da)):
gw[k] += da[k]
for q in range(len(inp)):
gu[k][q] += da[k] * inp[q]
dhp = [a + b + e for a, b, e in zip(dhp, tmatvec(p["Uz"], daz), tmatvec(p["Ur"], dar))]
dh_next = dhp
return total, g, h
def session_parallel_batches(sessions: list[list[int]], lanes: int) -> list[list[tuple[int, int, int, bool]]]:
"""The session-parallel mini-batches of Section 3.1.1 of the paper.
Each batch is a list of (session index, input item, target item, reset),
one per active lane. A lane works through its session event by event;
when the session ends, the lane takes the next unused session and the
hidden state is reset. Sessions shorter than 2 are skipped. Cost
O(total events).
"""
queue = [s for s in range(len(sessions)) if len(sessions[s]) >= 2]
nxt = 0
state: list[list[int] | None] = []
for _ in range(lanes):
if nxt < len(queue):
state.append([queue[nxt], 0])
nxt += 1
else:
state.append(None)
batches = []
while any(st is not None for st in state):
batch = []
for b in range(lanes):
st = state[b]
if st is None:
continue
s, pos = st
seq = sessions[s]
batch.append((s, seq[pos], seq[pos + 1], pos == 0))
if pos + 2 < len(seq):
state[b] = [s, pos + 1]
elif nxt < len(queue):
state[b] = [queue[nxt], 0]
nxt += 1
else:
state[b] = None
batches.append(batch)
return batches
def train(
sessions: list[list[int]], n_items: int, hidden: int, lanes: int, epochs: int, rate: float,
kind: str = "bpr", seed: int = 1,
) -> Params:
"""SGD over session-parallel mini-batches with in-batch negatives. Cost O(E events (H^2 + lanes H))."""
p = init(n_items, hidden, seed) # @line L1
for _ in range(epochs): # @line L2
hs: dict[int, list[float]] = {}
for batch in session_parallel_batches(sessions, lanes): # @line L3
targets = [y for _, _, y, _ in batch]
g_total = zeros_like(p)
for s, x, y, reset in batch:
h = [0.0] * hidden if reset else hs[s] # @line L4
neg = sorted({t for t in targets if t != y})
_, g, h_new = sequence_loss_and_grad(p, [x], [y], [neg], h, kind) # @line L5
hs[s] = h_new
for name, mat in g.items(): # @line L6
tot = g_total[name]
for r, row in enumerate(mat):
for c, v in enumerate(row):
tot[r][c] += v
for name, mat in p.items(): # @line L7
for r, row in enumerate(mat):
gr = g_total[name][r]
for c in range(len(row)):
row[c] -= rate * gr[c]
return p # @line L8
def next_items(p: Params, session: list[int], n_items: int, k: int) -> list[int]:
"""The k items with the highest score after reading the session. Cost O(T H^2 + n H)."""
h = [0.0] * len(p["Uz"])
for x in session:
h = gru_step(p, x, h)["h"]
s = scores(p, h, list(range(n_items)))
return sorted(range(n_items), key=lambda j: (-s[j], j))[:k]
test_gru4rec.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gru4rec/. The authors are listed in prov/6CBA3Q.jsonl.
import math
import random
import pytest
import gru4rec as g
FD_STEP = 1e-6
FD_TOL = 1e-6
def cyclic_sessions(seed: int, n: int, count: int) -> list[list[int]]:
"""Sessions in which the item after x is always (x + 1) mod n."""
rng = random.Random(seed)
out = []
for _ in range(count):
s, length = rng.randrange(n), rng.randint(3, 6)
out.append([(s + k) % n for k in range(length)])
return out
@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_every_gradient_matches_finite_differences(kind):
p = g.init(5, 3, seed=7, scale=0.6)
for row in p["c"]:
for c in range(len(row)):
row[c] = 0.1 * (c - 2)
xs, ys = [0, 3, 1, 4], [3, 1, 4, 2]
negs = [[1, 2], [0, 4], [2], [0, 1, 3]]
h0 = [0.2, -0.3, 0.1]
_, grads, _ = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)
for name, mat in p.items():
for r in range(len(mat)):
for c in range(len(mat[r])):
old = mat[r][c]
mat[r][c] = old + FD_STEP
up = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)[0]
mat[r][c] = old - FD_STEP
down = g.sequence_loss_and_grad(p, xs, ys, negs, h0, kind)[0]
mat[r][c] = old
fd = (up - down) / (2 * FD_STEP)
assert abs(fd - grads[name][r][c]) <= FD_TOL * max(1.0, abs(fd)), (name, r, c)
@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_loss_derivative_in_the_scores(kind):
rs = [0.3, -0.2, 0.5, 1.1]
_, d = g.step_loss(kind, rs)
for k in range(len(rs)):
up, down = rs[:], rs[:]
up[k] += FD_STEP
down[k] -= FD_STEP
fd = (g.step_loss(kind, up)[0] - g.step_loss(kind, down)[0]) / (2 * FD_STEP)
assert abs(fd - d[k]) <= FD_TOL
def test_session_parallel_batches_cover_every_event_once():
sessions = [[0, 1, 2, 3], [4, 5], [6], [7, 8, 9], [1, 3, 5, 7, 9], [2, 4]]
batches = g.session_parallel_batches(sessions, 3)
seen = []
for batch in batches:
assert len(batch) <= 3
assert len({s for s, _, _, _ in batch}) == len(batch)
seen.extend(batch)
expected = []
for s, seq in enumerate(sessions):
expected.extend((s, seq[t], seq[t + 1], t == 0) for t in range(len(seq) - 1))
assert sorted(seen) == sorted(expected)
for s, seq in enumerate(sessions):
order = [(x, y) for b in batches for s2, x, y, _ in b if s2 == s]
assert order == [(seq[t], seq[t + 1]) for t in range(len(seq) - 1)]
assert batches[0] == [(0, 0, 1, True), (1, 4, 5, True), (3, 7, 8, True)]
assert batches[1] == [(0, 1, 2, False), (4, 1, 3, True), (3, 8, 9, False)]
def test_page_example():
p = {
"Wz": [[0.0]], "Wr": [[0.0]], "Wh": [[math.log(3.0)]],
"Uz": [[0.0]], "Ur": [[0.0]], "Uh": [[0.0]],
"O": [[1.0], [-1.0]], "c": [[0.0, 0.0]],
}
c = g.gru_step(p, 0, [0.0])
assert c["z"] == [0.5] and c["r"] == [0.5]
assert abs(c["hh"][0] - 0.8) <= 1e-12
assert abs(c["h"][0] - 0.4) <= 1e-12
rs = g.scores(p, c["h"], [0, 1])
bpr, d_bpr = g.step_loss("bpr", rs)
top1, _ = g.step_loss("top1", rs)
assert abs(bpr - math.log1p(math.exp(-0.8))) <= 1e-12
assert abs(bpr - 0.3711006659477777) <= 1e-12
assert abs(d_bpr[0] + 1 / (1 + math.exp(0.8))) <= 1e-12
assert abs(top1 - (1 / (1 + math.exp(0.8)) + 1 / (1 + math.exp(-0.16)))) <= 1e-12
@pytest.mark.parametrize("kind", ["bpr", "top1"])
def test_training_learns_a_cyclic_pattern(kind):
n = 6
sessions = cyclic_sessions(4, n, 30)
before = g.init(n, 6, seed=2)
p = g.train(sessions, n, 6, 5, 10, 0.1, kind, seed=2)
hits_before = sum(g.next_items(before, [(x - 1) % n, x], n, 1) == [(x + 1) % n] for x in range(n))
hits = sum(g.next_items(p, [(x - 1) % n, x], n, 1) == [(x + 1) % n] for x in range(n))
assert hits_before <= 2
assert hits == n
def test_unknown_loss_is_rejected():
with pytest.raises(ValueError):
g.step_loss("hinge", [0.0, 1.0])
History
Hidasi, Karatzoglou, Baltrunas and Tikk presented GRU4Rec at ICLR 2016. It was one of the first applications of a recurrent network to session-based recommendation, and it became a standard baseline. Hidasi and Karatzoglou improved the losses and the sampling at CIKM 2018. Ludewig and Jannach published a comparison in 2018 that found simple nearest neighbor methods competitive. Self-attention models such as SASRec (2018) followed.
References
- Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas and Domonkos Tikk, Session-based recommendations with recurrent neural networks, ICLR 2016, Section 3 (the GRU, Equations 2 to 5), Section 3.1 (1-of-N input and the network), Section 3.1.1 (session-parallel mini-batches, Figure 2), Section 3.1.2 (in-batch negatives as popularity-based sampling), Section 3.1.3 (the BPR and TOP1 losses), Section 4 (RSC15 and VIDEO, recall@20 and MRR@20, Tables 1 and 3)
- Balázs Hidasi and Alexandros Karatzoglou, Recurrent neural networks with top-k gains for session-based recommendations, CIKM 2018, Abstract (new ranking losses and extra negative samples, with reported gains in MRR and recall@20)
- Malte Ludewig and Dietmar Jannach, Evaluation of session-based recommendation algorithms, Abstract (simple nearest neighbor methods often did as well as or better than GRU4Rec in their comparison)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6CBA3Q Edit this page History Report an error Markdown