Embedding lookups, a learned interaction, and rating prediction
CUHK · Department of Statistics and Data Science
The training workflow is already in the NN deck. Today we change two things: how IDs become vectors, and how the vectors interact.
The interaction is chosen before fitting.
Concatenate the two vectors and learn the interaction.
Keep the dot product and add a neural correction.
Every model in this deck uses the same first two steps; only step 3 changes.
User and item IDs, 1–5 star ratings, and one shared encoding.
Embedding lookups, training, comparison, practice, and GMF / two-tower / NeuMF extensions.
Open nb/STAT3009_NCF.ipynb. The Neural Networks warm-up lives in STAT3009_NN.ipynb.
↗
MF already has the two ingredients we need: an ID-to-vector lookup and a way to combine the vectors.
↗
The first challenge is a reusable layer that turns an ID into its learned factor vector.
“Embedding” and “latent factor” describe the same kind of learned dense vector here.
A batch of IDs is a batch of lookups: the output is a matrix (B,K).
The one-hot row explains the math; the embedding layer performs the lookup without building the zeros.
ID numbers are lookup positions, not ordered measurements; K is chosen, and the table entries are learned.
nn.Embedding docsemb = nn.Embedding(num_embeddings=10, embedding_dim=4)
ids = torch.tensor([[1, 2], [3, 0]]) # (B,T), integer dtype
vectors = emb(ids) # (B,T,4)
print(emb.weight.shape) # (10,4)| argument | what it controls | NCF | NLP / LLM |
|---|---|---|---|
num_embeddings
|
number of rows |
n_users, n_items
|
vocab_size
|
embedding_dim
|
vector width |
K
|
d_model
|
padding_idx
|
row fixed to zero | not used | padding token |
sparse
|
sparse gradients | not used | huge vocabularies |
weight is a learned (num_embeddings, embedding_dim) matrix; forward only selects rows.
Turning MF into layers does not change its model: the interaction is still an inner product.
MF learns good vectors, but it fixes how they combine. NCF keeps the vectors and learns the combination rule.
The score is a sum of coordinate-wise products; the rule is chosen before fitting.
Take \(p_u=(1,1)\). Items \((1,1)\) and \((2,0)\) both score \(2\); a user may still prefer the balanced item—or the extreme one.
The MLP can approximate a dot product, or learn a nonlinear rule that separates those items.
The embeddings are still learned; only the combination rule becomes a model. More flexibility is useful only if validation improves.
Every observed rating sends an error signal through the hidden layers and back into the two embedding tables.
Before training, check every brick: (B,) → (B,K) → (B,2K) → (B,H) → (B,1).
A missing pair is not a zero rating.
Lookup, concatenate, then an MLP.
Only training pairs enter the loss.
One optimizer updates tables and network.
Gradient updates use observed training ratings.
Choose settings and the epoch budget without touching the final test labels.
This is the explicit-rating version used in STAT3009; the original NCF research also considers implicit feedback.
class NCF(nn.Module):
def __init__(self, n_users, n_items, K=16):
super().__init__()
torch.manual_seed(0)
self.user_emb = nn.Embedding(n_users, K)
self.item_emb = nn.Embedding(n_items, K)
self.net = nn.Sequential(
nn.Linear(2 * K, 32), nn.ReLU(),
nn.Linear(32, 1),
)
def forward(self, x):
u = x[:, 0].long()
i = x[:, 1].long()
z = torch.cat([self.user_emb(u),
self.item_emb(i)], dim=1)
return self.net(z)Both embedding tables and the MLP are trained by the same loss.
Look up \(a_u\) and \(p_u\).
Look up \(b_i\) and \(q_i\).
Start from the bias baseline, then let the network learn the interaction.
Adding the familiar bias terms gives the network a sensible starting point and isolates the interaction.
class BiasedNCF(nn.Module):
def __init__(self, n_users, n_items, K=16, mu=0.0):
super().__init__()
torch.manual_seed(0)
self.user_emb = nn.Embedding(n_users, K)
self.item_emb = nn.Embedding(n_items, K)
self.user_bias = nn.Embedding(n_users, 1)
self.item_bias = nn.Embedding(n_items, 1)
self.mu = nn.Parameter(torch.tensor([mu]))
self.net = nn.Sequential(
nn.Linear(2 * K, 32), nn.ReLU(),
nn.Linear(32, 16), nn.ReLU(),
nn.Linear(16, 1),
)
def forward(self, x):
u = x[:, 0].long()
i = x[:, 1].long()
z = torch.cat([self.user_emb(u),
self.item_emb(i)], dim=1)
return (self.mu + self.user_bias(u)
+ self.item_bias(i) + self.net(z))
The four embedding tables and the MLP are registered in one Module; one optimizer updates all of them.
\(p_u^\top q_i\) retains the simple, interpretable matching mechanism.
Separate embeddings \(s_u,t_i\) feed a nonlinear correction.
This additive extension is useful when a dot product captures part of the pattern but leaves structured residuals.
class ANCF(nn.Module):
def __init__(self, n_users, n_items, K=16, R=8, mu=0.0):
super().__init__()
torch.manual_seed(0)
self.user_emb = nn.Embedding(n_users, K)
self.item_emb = nn.Embedding(n_items, K)
self.user_neural = nn.Embedding(n_users, R)
self.item_neural = nn.Embedding(n_items, R)
self.user_bias = nn.Embedding(n_users, 1)
self.item_bias = nn.Embedding(n_items, 1)
self.mu = nn.Parameter(torch.tensor([mu]))
self.net = nn.Sequential(
nn.Linear(2 * R, 32), nn.ReLU(),
nn.Linear(32, 1),
)
def forward(self, x):
u = x[:, 0].long()
i = x[:, 1].long()
mf = (self.user_emb(u) * self.item_emb(i)).sum(
dim=1, keepdim=True)
z = torch.cat([self.user_neural(u),
self.item_neural(i)], dim=1)
return (self.mu + self.user_bias(u)
+ self.item_bias(i) + mf + self.net(z))ncf = NeuralNetRegressor(
module=BiasedNCF,
module__n_users=n_users,
module__n_items=n_items,
module__mu=mu,
criterion=nn.MSELoss,
optimizer=torch.optim.SGD,
optimizer__lr=0.05,
max_epochs=50,
batch_size=256,
iterator_train__shuffle=True,
train_split=ValidSplit(0.1, random_state=0),
)
ncf.fit(X_train, y_train)
The module__ prefix passes constructor arguments; the rest is the same skorch wrapper used in the previous deck.
Keep explicit factor interactions as inputs.
Let the network combine those interactions with another representation.
This extension has more parameters and more design choices; it needs the same careful validation as the simpler models.
Look up its learned vector and predict.
The ID-only NCF model cannot infer a personalized vector from an unseen ID.
Side information—user or item features—offers a way to construct a representation for a new entity. That is the next lecture.
nb/STAT3009_NCF.ipynb
Run the notebook in order. Come back when the comparison table is on screen.
Load the Netflix split, encode IDs, and print the shapes.
Run MFNet, BiasedNCF, and ANCF; check every output shape.
Fit all three for 50 epochs and display the comparison table.
When you return, we will read the validation curves and the test RMSE together.
| model | interaction | flexibility | example test RMSE |
|---|---|---|---|
| Biased MF | \(p_u^\top q_i\) | fixed | 0.971 |
| NCF | \(g_\theta([p_u,q_i])\) | learned | 0.974 |
| Additive NCF | \(p_u^\top q_i+h_\phi([s_u,t_i])\) | both paths | 0.961 |
The example is one fixed 50-epoch budget on the course split. More flexibility is not automatically better; validation decides.
NCF has more parameters; it can memorize observed pairs.
Keep the test set closed until the final comparison.
The learned interaction helps only when validation improves; otherwise the simpler dot product is the better model.
For each new model, ask again: data, model, loss, optimization—and then ask how you will validate it.
Open nb/STAT3009_NCF.ipynb, Section 7. Work in pairs for 20 minutes. The grid uses 30 epochs to stay fast; the comparison above uses 50.
BiasedNCF for 50 epochs; plot training and validation RMSE.
Compare candidate models on validation; open the test labels only once, at the end.
Bigger models can fit training noise and lose on validation.
Too small underfits; too large overfits the sparse table.
Pick the epoch budget and architecture on validation; report test once.
NCF is still a regression model: the same data, loss, and optimization questions apply.
Lowest mean CV RMSE; refit=True refits the winner.
The search uses 30 epochs; the fixed comparison uses 50.
CV ranks candidates; it is not a test score. The search budget also matters.
Keep the two embedding branches; change only how they meet. Section 8 of the notebook has skeletons and solutions.
\(p_u\odot q_i\) → a linear head. MF fixes the head weights to 1; GMF learns them.
User and item embeddings go through separate towers, then a dot product.
Concatenate the GMF vector and the MLP vector, then a final linear layer.
Optional / take-home. All three reuse the same training and validation recipe; only the merge changes.
| question | MF | NCF |
|---|---|---|
| Data | observed (u,i,r) rows | same rows |
| Model | dot product | embeddings + concat + MLP |
| Loss | MSE on observed ratings | same loss |
| Optimization | SGD + backprop | same optimizer |
| Evaluation | validation curve + CV | same evaluation |
Only the interaction changes; the data, loss, optimizer, and evaluation stay the same.
Turn integer user and item IDs into learned dense vectors.
Use torch.cat and an MLP to learn the interaction.
Decide whether the learned interaction improves validation RMSE.
Compare training and validation curves before opening the test set.
torch.cat do in NCF, and what is the resulting shape?
If you can answer these six questions, you can reproduce the notebook from scratch.
NCF: one ID → one vector. NLP: a sequence of token IDs → a sequence of vectors, shape (B,T,d).
Nearest vectors in one shared space.
Use the same vectors for unsupervised grouping.
The NCF idea, now with text or side features.
RAG is one application; the same embeddings support search, clustering, and recommendation.
An ID-only model cannot represent an unseen user or item; side features can build the vector instead.
CUHK · STAT3009 · Neural Collaborative Filtering