Neural Collaborative Filtering

Embedding lookups, a learned interaction, and rating prediction

Ben Dai

CUHK · Department of Statistics and Data Science

The NCF roadmap

The training workflow is already in the NN deck. Today we change two things: how IDs become vectors, and how the vectors interact.

1 · IDs
user \(u\)
item \(i\)
→
2 · Lookup
\(p_u\)
\(q_i\)
→
3 · Interaction
dot product
or learned MLP
→
4 · Rating
\(\widehat r_{ui}\)
MFfixed dot product

The interaction is chosen before fitting.

NCFlearned MLP

Concatenate the two vectors and learn the interaction.

ANCFboth paths

Keep the dot product and add a neural correction.

Every model in this deck uses the same first two steps; only step 3 changes.

Today’s notebook

SECTIONS 1–2 · DATANetflix split

User and item IDs, 1–5 star ratings, and one shared encoding.

SECTIONS 3–8 · MODELSMF → NCF → more merges

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.

From matrix factorization to a learned interaction

\[\widehat r_{ui}=\mu+a_u+b_i+p_u^\top q_i\]
user ID u
→
lookup p_u
↘
dot product
→
rating
item ID i
→
lookup q_i

↗

MF already has the two ingredients we need: an ID-to-vector lookup and a way to combine the vectors.

Can a neural network reproduce MF?

\[\widehat r_{ui}=\mu+a_u+b_i+p_u^\top q_i\]
user ID
→
Embedding p_u
↘
inner product
→
rating
item ID
→
Embedding q_i

↗

The first challenge is a reusable layer that turns an ID into its learned factor vector.

An embedding layer is a learned lookup table

A user-ID by factor table; user ID 2 selects the third row, which is the learned vector p2.

\[u\longmapsto P[u]=p_u,\qquad i\longmapsto Q[i]=q_i\]

“Embedding” and “latent factor” describe the same kind of learned dense vector here.

One ID or a batch of IDs

A batch of three IDs selects three rows from the embedding table and returns them in the input order.

A batch of IDs is a batch of lookups: the output is a matrix (B,K).

Lookup equals a one-hot matrix product

A one-hot row times the embedding table selects one row.

The one-hot row explains the math; the embedding layer performs the lookup without building the zeros.

Embedding size is a choice; values are learned

The embedding table has n_users rows and K columns. K is chosen before fitting; the entries are learned.

ID numbers are lookup positions, not ordered measurements; K is chosen, and the table entries are learned.

Reading the nn.Embedding docs

emb = 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.

MF is a tiny two-branch network

MF as a two-branch network: user and item IDs are looked up in embedding tables, then combined by an inner product.

\[u\to p_u,\quad i\to q_i,\quad (p_u,q_i)\to p_u^\top q_i\]

Turning MF into layers does not change its model: the interaction is still an inner product.

What changes in NCF?

MF learns good vectors, but it fixes how they combine. NCF keeps the vectors and learns the combination rule.

MATRIX FACTORIZATIONFixed bilinear rule
\[p_u^\top q_i=\sum_{k=1}^K p_{uk}q_{ik}\]

The score is a sum of coordinate-wise products; the rule is chosen before fitting.

WHY IT CAN FAILthe score only sees a weighted sum

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.

NEURAL COLLABORATIVE FILTERINGLearn the combination
\[\widehat r_{ui}=g_\theta([p_u,q_i])\]

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.

Follow one prediction through the NCF graph

User and item IDs are looked up, concatenated, passed through hidden layers, and scored.

Every observed rating sends an error signal through the hidden layers and back into the two embedding tables.

The shape contract for NCF

NCF shape contract: user and item IDs map to embeddings of width K, concatenate to width 2K, pass through a hidden layer, and produce one score.

Before training, check every brick: (B,) → (B,K) → (B,2K) → (B,H) → (B,1).

NCF: four questions before code

1 · DATAobserved (u,i,r) rows

A missing pair is not a zero rating.

2 · MODEL\(g_\theta([p_u,q_i])\)

Lookup, concatenate, then an MLP.

3 · LOSSMSE on observed ratings

Only training pairs enter the loss.

4 · OPTIMIZATIONSGD on all parameters

One optimizer updates tables and network.

The rating-regression criterion

\[\min_{P,Q,\theta}\;\frac{1}{\lvert\Omega_{\rm train}\rvert}\sum_{(u,i)\in\Omega_{\rm train}}\bigl(r_{ui}-g_\theta([p_u,q_i])\bigr)^2\]
FITTraining pairs only

Gradient updates use observed training ratings.

SELECTValidation RMSE

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.

A PyTorch implementation sketch

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.

Keep the familiar bias terms

\[\widehat r_{ui}=\mu+a_u+b_i+g_\theta([p_u,q_i])\]
BRANCH 1user ID

Look up \(a_u\) and \(p_u\).

BRANCH 2item ID

Look up \(b_i\) and \(q_i\).

COMBINEadd + network

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.

Biased NCF in PyTorch

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.

Add a nonlinear correction, keep MF

\[\widehat r_{ui}=\mu+a_u+b_i+p_u^\top q_i+h_\phi([s_u,t_i])\]
MF PATHfirst-order interaction

\(p_u^\top q_i\) retains the simple, interpretable matching mechanism.

NEURAL PATHadditional interaction

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.

Additive NCF in PyTorch

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))

The same skorch wrapper trains NCF

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.

A more flexible path is optional

\[\widehat r_{ui}=\phi\!\left([\,p_u\circ q_i,\;\psi([s_u,t_i])\,]\right)\]
\(p_u\circ q_i\)coordinate-wise products

Keep explicit factor interactions as inputs.

\(\psi,\phi\)learned nonlinear functions

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.

When the ID is new

KNOWN IDEmbedding row exists

Look up its learned vector and predict.

NEW IDNo learned row yet

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.

Coding break: run the NCF pipeline

PAUSE · CODING BREAK · 8–10 MIN Switch to nb/STAT3009_NCF.ipynb

Run the notebook in order. Come back when the comparison table is on screen.

1 · DATASection 2

Load the Netflix split, encode IDs, and print the shapes.

2 · MODELSSections 3–5

Run MFNet, BiasedNCF, and ANCF; check every output shape.

3 · TRAINSection 6

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.

What to expect: MF vs NCF

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.

More flexibility can overfit

Training loss keeps falling; validation loss reaches a minimum and then rises.
WHAT THE CURVES SHOWtraining falls faster

NCF has more parameters; it can memorize observed pairs.

WHAT TO DOchoose on validation

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.

The thread from MF to NCF

MF
dot product
→
embedding layers
same factors
→
NCF
learned interaction
→
side information
new IDs

For each new model, ask again: data, model, loss, optimization—and then ask how you will validate it.

In-class practice: build an NCF

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.

  1. Train the provided BiasedNCF for 50 epochs; plot training and validation RMSE.
  2. Change \(K\) from 16 to 8 and re-fit; compare validation RMSE.
  3. Add one hidden layer or change its width; does validation improve?
  4. Report the test RMSE of your best model and one sentence explaining the choice.

Compare candidate models on validation; open the test labels only once, at the end.

Practice debrief

CAPACITYmore units ≠ better

Bigger models can fit training noise and lose on validation.

EMBEDDINGS\(K\) is a hyperparameter

Too small underfits; too large overfits the sparse table.

SELECTIONvalidation, then test

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.

CV snapshot: NCF over \(K\) and hidden

Cross-validation RMSE for four NCF settings; K=16 and hidden=16 is best.

SELECTED\(K=16,\ \mathrm{hidden}=16\)

Lowest mean CV RMSE; refit=True refits the winner.

TEST RMSE0.9569

The search uses 30 epochs; the fixed comparison uses 50.

CV ranks candidates; it is not a test score. The search budget also matters.

Extra practice: change the merge

Keep the two embedding branches; change only how they meet. Section 8 of the notebook has skeletons and solutions.

GMFelementwise product

\(p_u\odot q_i\) → a linear head. MF fixes the head weights to 1; GMF learns them.

TWO-TOWERseparate MLPs

User and item embeddings go through separate towers, then a dot product.

NEUMFtwo parallel paths

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.

Carry the template forward

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.

What you should be able to do now

BUILDan embedding layer

Turn integer user and item IDs into learned dense vectors.

COMBINEMF and a network

Use torch.cat and an MLP to learn the interaction.

COMPAREMF vs NCF

Decide whether the learned interaction improves validation RMSE.

DIAGNOSEoverfitting

Compare training and validation curves before opening the test set.

Exit ticket

  1. Why can an embedding layer be viewed as a one-hot matrix product?
  2. What does torch.cat do in NCF, and what is the resulting shape?
  3. What changes from MF to NCF, and what stays the same?
  4. Why must the validation set stay out of the gradient updates?
  5. What happens when a user or item ID was never seen during training?
  6. Why might MF beat NCF on a sparse dataset?

If you can answer these six questions, you can reproduce the notebook from scratch.

Embedding is a core NLP module

Text is tokenized, token IDs select embedding rows, and the resulting sequence goes through a Transformer.

NCF: one ID → one vector. NLP: a sequence of token IDs → a sequence of vectors, shape (B,T,d).

Where LLMs use embeddings

RAG pipeline: query and documents are embedded, compared by cosine similarity, top-k passages go into a prompt, and an LLM answers.

SEMANTIC SEARCHquery → documents

Nearest vectors in one shared space.

CLUSTERINGgroup similar items

Use the same vectors for unsupervised grouping.

RECOMMENDATIONuser + item vectors

The NCF idea, now with text or side features.

RAG is one application; the same embeddings support search, clustering, and recommendation.

Next: side information

Known IDs use a learned embedding row; a new ID has no row, so side features go through an MLP to build a vector.

An ID-only model cannot represent an unseen user or item; side features can build the vector instead.