Encoding and fusing continuous, categorical, text, and image signals
CUHK · Department of Statistics and Data Science
The ID-only graph has two inputs: a user ID and an item ID. Side information adds more inputs to the same graph.
Numeric signals from profiles, content, or context.
Discrete labels that can become embeddings.
Product or item text, encoded by an LLM or a smaller model.
Product or item images, encoded by a CNN or ViT.
The modelling question is not “do we have IDs?” but “how do we encode and fuse all the information we have?”
A classroom subset of the Video Games category, built from the 5-core rating-only split. One row is one rating; product metadata joins on item_id.
Continuous target; evaluate with RMSE.
Price, store, category path, title, description, features.
Each rating is assigned to train or test at random; all users and items can appear in both.
Amazon Reviews 2023 (Hou et al., 2024). Rating-derived fields such as average_rating and rating_number are excluded; they would leak the target.
Each block has a different encoder, but the head sees vectors. That is the whole “load side information into the network” pattern.
| user | product | price | store | image | rating |
|---|---|---|---|---|---|
| AHNZ… | Pro Evolution Soccer 2013 | 20.25 | Konami | yes | 5 |
| AH5A… | Demon Slayer: Hinokami Chronicles | 34.98 | SEGA | yes | 4 |
| AFXA… | Sim Theme Park | 35.00 | Electronic Arts | no | 2 |
| AHJW… | Xbox One 1TB Console | 349.99 | Microsoft | no | 1 |
User ID and activity count from training interactions.
Title/description, price, store/category, product photo.
A continuous star rating, evaluated with RMSE.
All four modalities are available before the rating. Exclude average_rating and rating_number: they leak the target.
Already a vector. Preprocess, then fuse.
Encode, then learn an embedding table.
LLM encoder produces a dense vector.
CNN or ViT produces a dense vector.
The encoder changes with the modality. The fusion and evaluation questions do not.
Already vectors — preprocess, then fuse.
| feature | raw | notebook transform | unseen / missing |
|---|---|---|---|
price
|
20.25 |
log1p → train z-score
|
train median |
user_count
|
12 | training count → z-score | 0 |
Section 2 prepares the columns; MFNetCont adds this block to MFNet. Scalers and counts use training rows only.
X["cont"] has exactly these two columns. Other product metadata belongs to the categorical, text, or image block.
Early concat lets one MLP learn all interactions; additive MF keeps the ID score and adds a feature correction; two towers encode each side separately before the dot product.
A category is an ID. An embedding is a learned lookup table.
User ID, store, category — the same nn.Embedding lookup; only the table size changes.
The recommender only sees vectors. Swapping an encoder should not change the fusion block.
Same encoders, different interaction.
Handles new IDs, but may miss individual preferences.
Keeps personalized ID factors and adds a feature contribution.
Builds each factor from ID and features together.
Use features-only when IDs are weak; additive MF when IDs are strong; side-aware factors when both sides have rich features.
The third approach makes the interaction depend on the features on both sides.
Feature-only works for a new ID but has no individual preference. Additive MF keeps the ID score and adds a feature correction — the safest first model.
Features and category embeddings build each factor; the ID term is a learned residual. A new ID sets the residual to zero, but the feature path still produces a vector.
Each tower learns nonlinear interactions within its side; the final layer learns the interaction across sides.
The model is only as good as the split.
Start with MFNet; add only the blocks the data supports.
Choose before fitting; tune on validation.
MSE on the observed 1–5 ratings.
ID/category embeddings, biases, and the additive blocks.
One MSE trains the ID tables and every side-information block. Select hyperparameters on validation.
X["ids"]forward(ids, …)MFNetA new block adds a key; it does not move column positions.
X["cont"] is passed to forward(…, cont).
MFNet uses ids; MFNetText also uses text.
A new modality is a new dictionary key and a new named argument — not a new column index.
class MFNetCont(MFNet):
def __init__(self, n_users, n_items, K=16, mu=0.0, d_cont=2):
super().__init__(n_users, n_items, K, mu)
self.cont = nn.Sequential(
nn.Linear(d_cont, 16), nn.ReLU(), nn.Linear(16, 1)
)
def forward(self, ids, cont):
return super().forward(ids) + self.cont(cont)
For this model, X only needs ids and cont; later models receive larger dicts.
One subclass, one new block. The dict keys select the named arguments; skorch handles the training loop and prediction.
31,836 train rows · 7,960 test rows. No user or item is deliberately removed.
IDs are not held out; most test rows reuse users and items seen in training.
A random split does not test a genuinely new product or a new user.
Scalers and rating summaries use training rows only; ID vocabularies can use the catalogue.
Rating mean, rating count, or quantile computed from the target leaks even in a random split.
The notebook uses a random 80/20 split, so report test RMSE and describe it as in-distribution interpolation.
Random 80/20 row split: 31,836 train rows · 7,960 test rows. Select on validation; report test once. Lower RMSE is better.
| model | added input | validation RMSE | test RMSE |
|---|---|---|---|
| MFNet | IDs only | 1.1644 | 1.1587 |
| + continuous | price + user_count | 1.1656 | 1.1589 |
| + categorical | store + category path | 1.1635 | 1.1598 |
| + text | MiniLM title + description | 1.1589 | 1.1535 |
Image subset (300 products): text only 1.1437 → + image 1.1438. Not comparable with the full table.
0.0052 lower test RMSE than MFNet.
Changes are tiny and do not hold on test.
+0.0001 on the image subset.
More side information is not automatically better. On this split, text is the only clear gain; the image block is neutral.
Intuition: with a random split the item ID is already seen in training, so price and category add little beyond the ID; text still adds product semantics.
Optional Product text → embedding → a small additive block.
| field | example | why |
|---|---|---|
title
|
Pro Evolution Soccer 2013 | short, high signal |
description
|
long product copy | use cases and context |
features
|
bullet list | structured attributes |
One string per item_id: 2,000 products, one embedding each.
Title, description, and feature bullets are available before the rating.
Review title/text is written together with the star rating; it leaks the target.
One string per product, built from product metadata only. Review text is not a feature.
# Colab: !pip -q install transformers
import numpy as np
from transformers import pipeline
embed = pipeline("feature-extraction", model="sentence-transformers/all-MiniLM-L6-v2")
texts = (items.title.fillna("") + " " +
items.description.fillna("") + " " +
items.features.fillna("")).tolist()
out = embed(texts, batch_size=64,
truncation=True, max_length=256)
# out[i][0].shape -> (n_tokens, 384)
text_vectors = np.array([np.mean(o[0], axis=0) for o in out]) # (n_items, 384)
feature-extraction returns one vector per token, not one vector per product. Mean pooling turns it into a single 384-d embedding.
New input: X["text"] = e_text, shape (N, 384). MFNetText.forward(ids, cont, cat, text).
Trainable parameters: 12,320 + 528 + 17 ≈ 12.9k; MiniLM stays frozen at ~22M.
This is MFNetText: one projection, one small block, added to the existing score. The MiniLM encoder stays frozen.
Precompute 2,000 × 384; train only the projection and block. Cheap and reproducible.
Update MiniLM only when the domain is specialized and frozen features clearly underperform.
Project 384 → 32, then add or concat. L2-normalize if using cosine-style retrieval.
Embed in batches; cache the matrix.
Truncate long descriptions.
One embedding per product; map to rating rows.
No encoder call at serving time.
Freeze first, cache the 2,000 embeddings, and measure on the same random split. Fine-tune only with evidence.
Optional Product photo → 512-d vector → a small additive block.
One of the 300 product photos in the subset.
Prefix with the local dataset folder; in Colab, prefix with the GitHub BASE URL.
One embedding per product; the image ablation uses only rating rows for these products.
The product photo is metadata, not review content. Do not use review images or rating-derived fields.
Only a subset has an image, so image results are not directly comparable with the full-table numbers.
from transformers import pipeline
embed_image = pipeline(
"image-feature-extraction",
model="microsoft/resnet-18",
)
image_items = items[items.image_path.notna()]
paths = [f"{LOCAL or BASE}/{p}" for p in image_items.image_path]
image_vectors = np.array(
embed_image(paths, batch_size=32, pool=True)
).reshape(len(paths), -1)
image_vectors /= np.linalg.norm(image_vectors, axis=1, keepdims=True)
image_emb = pd.DataFrame(image_vectors, index=image_items.item_id)
d_image = image_emb.shape[1] # 512
pool=True averages the 7×7 feature map; each vector is then L2-normalized.
image-feature-extraction returns a spatial tensor; flatten it to one 512-d vector per product.
New input: X["image"] = v_i, shape (N, 512). MFNetImage.forward(ids, cont, cat, text, image).
Trainable: 16,416 + 528 + 17 ≈ 17k; ResNet18 stays frozen. Evaluate on the 300-image subset.
MFNetImage inherits MFNetText and adds one projection plus one block.
Precompute 300 × 512; train only the projection and image block.
Fine-tune the last block only when you have enough images and compute.
Concat for ranking; image tower for retrieval; CLIP-style alignment for zero-shot items.
Paths or URLs; batch 32.
Flatten the pooled ResNet map; L2-normalize.
then 16 → 1; small additive head.
Cache embeddings; no CNN at serving time.
Image subset: text only 1.1437 → + image 1.1438. No gain; freeze first and measure.
Optional Same pattern at scale.
Average embeddings, then ReLU layers produce the user vector u.
Softmax trains the item side; nearest-neighbour search serves candidates.
Watch/search sequences and demographics enter before the final interaction.
The two-tower pattern is a retrieval architecture first; the same encoders can feed a ranking model later.
Clicks and purchases become a user embedding.
Title and aspect CBOW embeddings plus a leaf-category embedding.
Affinity between the user and candidate item embedding.
Same two-tower pattern: a sequence encoder on the user side, a text/category encoder on the item side.
Other features and the user behavior sequence enter the embedding layer.
Multi-head self-attention models the order of past items.
Concatenate target item with sequence output; MLP + sigmoid.
Alibaba uses a sequence Transformer plus feature crossing; Wide & Deep and DeepFM are earlier early-fusion variants.
| retrieval | ranking | |
|---|---|---|
| goal | millions → hundreds | hundreds → top few |
| model | two-tower, dot product | richer MLP, crosses, context |
| latency | milliseconds | tens of milliseconds |
| features | available for every candidate | rich user/item/context features |
The same feature definition must be available at training and serving time.
A rating mean computed yesterday is not the same feature today.
A side-information model is also a data-engineering contract. Training-serving skew is a modelling bug.
Scale, embed, or pretrain; the recommender sees vectors.
Additive maps for interpretability; two towers for new entities and retrieval.
Random split: report test RMSE. Add new-entity splits only for generalization claims.
Side information is a representation strategy, a fusion choice, and an evaluation protocol — and on this dataset, only text improved test RMSE.
nn.Embedding; scikit-learn OneHotEncoder, StandardScaler; Hugging Face pipeline(“feature-extraction”) and pipeline(“image-feature-extraction”); Sentence Transformers all-MiniLM-L6-v2; microsoft/resnet-18; CLIP.
CUHK · STAT3009 · Side Information