Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ The table below lists the recommendation models/algorithms featured in Cornac. E
| 2013 | [Hidden Factors and Hidden Topics (HFT)](cornac/models/hft), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#module-cornac.models.hft.recom_hft), [paper](https://cs.stanford.edu/people/jure/pubs/reviews-recsys13.pdf) | Content-Based / Text | CPU | [quick-start](examples/hft_example.py)
| 2012 | [Weighted Bayesian Personalized Ranking (WBPR)](cornac/models/bpr), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#weighted-bayesian-personalized-ranking-wbpr), [paper](http://proceedings.mlr.press/v18/gantner12a/gantner12a.pdf) | Collaborative Filtering | CPU | [quick-start](examples/bpr_netflix.py)
| 2011 | [Collaborative Topic Regression (CTR)](cornac/models/ctr), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#module-cornac.models.ctr.recom_ctr), [paper](http://www.cs.columbia.edu/~blei/papers/WangBlei2011.pdf) | Content-Based / Text | CPU | [quick-start](examples/ctr_example_citeulike.py), [deep-dive](https://github.com/PreferredAI/tutorials/blob/master/recommender-systems/05_multimodality.ipynb)
| 2010 | [Factorizing Personalized Markov Chains (FPMC)](cornac/models/fpmc), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#module-cornac.models.fpmc.recom_fpmc), [paper](https://www.ismll.uni-hildesheim.de/pub/pdfs/RendleFreudenthaler2010-FPMC.pdf) | Next-Item | [requirements](cornac/models/fpmc/requirements.txt), CPU / GPU | [quick-start](examples/fpmc_diginetica.py)
| Earlier | [Baseline Only](cornac/models/baseline_only), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#baseline-only), [paper](http://courses.ischool.berkeley.edu/i290-dm/s11/SECURE/a1-koren.pdf) | Baseline | CPU | [quick-start](examples/svd_example.py)
| | [Bayesian Personalized Ranking (BPR)](cornac/models/bpr), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#bayesian-personalized-ranking-bpr) [paper](https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf) | Collaborative Filtering | CPU | [quick-start](examples/bpr_netflix.py), [deep-dive](https://github.com/recommenders-team/recommenders/blob/main/examples/02_model_collaborative_filtering/cornac_bpr_deep_dive.ipynb)
| | [Factorization Machines (FM)](cornac/models/fm), [docs](https://cornac.readthedocs.io/en/stable/api_ref/models.html#factorization-machines-fm), [paper](https://www.csie.ntu.edu.tw/~b97053/paper/Factorization%20Machines%20with%20libFM.pdf) | Collaborative Filtering / Content-Based | Linux, CPU | [quick-start](examples/fm_example.py), [deep-dive](https://github.com/PreferredAI/tutorials/blob/master/recommender-systems/06_contextual_awareness.ipynb)
Expand Down
2 changes: 2 additions & 0 deletions cornac/datasets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,3 +279,5 @@ Session-aware recommendation extends next-item (session-based) recommendation by
| [Diginetica](./diginetica.py) | 571 | 6,008 | 2,670 | 12,146 | 4.68 | 2.02 | 4.55 | 0.354% |
| [RetailRocket](./retailrocket.py) | 4,249 | 36,658 | 24,732 | 230,817 | 5.82 | 6.30 | 9.33 | 0.148% |
| [Cosmetics](./cosmetics.py) | 17,268 | 42,367 | 172,242 | 2,533,262 | 9.97 | 59.79 | 14.71 | 0.346% |

For session-based (next-item) evaluation, [Diginetica](./diginetica.py)'s `load_val()` and `load_test()` default to `mode="session-based"`, returning each user's single held-out session (`val_sbr`/`test_sbr`) with no training transitions repeated — the clean evaluation set used by session-based models such as [FPMC](../models/fpmc/) and [GRU4Rec](../models/gru4rec/). Pass `mode="session-aware"` to load the cumulative files (`val`/`test`) instead, where each user's prior sessions precede their held-out one for cross-session models.
34 changes: 28 additions & 6 deletions cornac/datasets/diginetica.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,45 +44,67 @@ def load_train(fmt="USIT", reader: Reader = None) -> List:
return reader.read(fpath, fmt=fmt, sep=",")


def load_val(fmt="USIT", reader: Reader = None) -> List:
def load_val(fmt="USIT", reader: Reader = None, mode="session-based") -> List:
"""Load validation data

Parameters
----------
reader: `obj:cornac.data.Reader`, default: None
Reader object used to read the data.

mode: str, default: 'session-based'
- ``'session-based'`` (default): each user's single held-out session
only (``val_sbr``) — the clean evaluation set for session-based
models, with no training transitions repeated.
- ``'session-aware'``: the full cumulative file (``val``), where each
user's prior sessions precede their held-out session, so a
session-aware model can use cross-session history at eval time.

Returns
-------
data: array-like
Data in the form of a list of tuples (user, session, item, timestamp).
"""
if mode not in ("session-based", "session-aware"):
raise ValueError(f"mode='{mode}' not supported; choose 'session-based' or 'session-aware'")
name = "val_sbr" if mode == "session-based" else "val"
fpath = cache(
url="https://static.preferred.ai/cornac/datasets/diginetica/val.zip",
url=f"https://static.preferred.ai/cornac/datasets/diginetica/{name}.zip",
unzip=True,
relative_path="diginetica/val.csv",
relative_path=f"diginetica/{name}.csv",
)
reader = Reader() if reader is None else reader
return reader.read(fpath, fmt=fmt, sep=",")


def load_test(fmt="USIT", reader: Reader = None) -> List:
def load_test(fmt="USIT", reader: Reader = None, mode="session-based") -> List:
"""Load test data

Parameters
----------
reader: `obj:cornac.data.Reader`, default: None
Reader object used to read the data.

mode: str, default: 'session-based'
- ``'session-based'`` (default): each user's single held-out session
only (``test_sbr``) — the clean evaluation set for session-based
models, with no training transitions repeated.
- ``'session-aware'``: the full cumulative file (``test``), where each
user's prior sessions precede their held-out session, so a
session-aware model can use cross-session history at eval time.

Returns
-------
data: array-like
Data in the form of a list of tuples (user, session, item, timestamp).
"""
if mode not in ("session-based", "session-aware"):
raise ValueError(f"mode='{mode}' not supported; choose 'session-based' or 'session-aware'")
name = "test_sbr" if mode == "session-based" else "test"
fpath = cache(
url="https://static.preferred.ai/cornac/datasets/diginetica/test.zip",
url=f"https://static.preferred.ai/cornac/datasets/diginetica/{name}.zip",
unzip=True,
relative_path="diginetica/test.csv",
relative_path=f"diginetica/{name}.csv",
)
reader = Reader() if reader is None else reader
return reader.read(fpath, fmt=fmt, sep=",")
1 change: 1 addition & 0 deletions cornac/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from .ease import EASE
from .efm import EFM
from .fm import FM
from .fpmc import FPMC
from .gcmc import GCMC
from .global_avg import GlobalAvg
from .gp_top import GPTop
Expand Down
16 changes: 16 additions & 0 deletions cornac/models/fpmc/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 2026 The Cornac Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

from .recom_fpmc import FPMC
84 changes: 84 additions & 0 deletions cornac/models/fpmc/fpmc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Copyright 2026 The Cornac Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

import torch
import torch.nn as nn


class FPMC_Model(nn.Module):
"""Factorizing Personalized Markov Chains (Rendle et al., 2010).

Score for user ``u``, last item ``i``, candidate ``j``:

s(u, i, j) = <UI_u, IU_j> + <IL_j, LI_i>

Implemented to return ``(B, B+N)`` matrices when out_iids contains the
in-batch positives followed by ``N`` shared negatives.
"""

def __init__(self, user_num, item_num, factor_num, pad_idx=None, device="cpu"):
super().__init__()
self.user_num = user_num
self.item_num = item_num
self.factor_num = factor_num
self.device = device
self.pad_idx = pad_idx if pad_idx is not None else item_num

# User-Item (target) embeddings
self.UI_emb = nn.Embedding(user_num + 1, factor_num, padding_idx=user_num)
# Item-User factor: scoring with UI
self.IU_emb = nn.Embedding(item_num + 1, factor_num, padding_idx=self.pad_idx)
# Last-Item factor (input)
self.LI_emb = nn.Embedding(item_num + 1, factor_num, padding_idx=self.pad_idx)
# Item-Last factor: scoring with LI
self.IL_emb = nn.Embedding(item_num + 1, factor_num, padding_idx=self.pad_idx)
self.item_biases = nn.Embedding(item_num + 1, 1, padding_idx=self.pad_idx)

nn.init.normal_(self.UI_emb.weight, std=0.01)
nn.init.normal_(self.IU_emb.weight, std=0.01)
nn.init.normal_(self.LI_emb.weight, std=0.01)
nn.init.normal_(self.IL_emb.weight, std=0.01)
nn.init.constant_(self.item_biases.weight, 0)
for emb in (
self.UI_emb,
self.IU_emb,
self.LI_emb,
self.IL_emb,
self.item_biases,
):
if emb.padding_idx is not None:
emb.weight.data[emb.padding_idx].zero_()

def forward(self, in_uids, in_iids, out_iids):
last_item_emb = self.LI_emb(in_iids) # (B, D)
user_emb = self.UI_emb(in_uids) # (B, D)
iu_emb = self.IU_emb(out_iids) # (B+N, D)
il_emb = self.IL_emb(out_iids) # (B+N, D)
bias = self.item_biases(out_iids) # (B+N, 1)

mf = torch.einsum("be,ne->bn", user_emb, iu_emb)
fmc = torch.einsum("ne,be->bn", il_emb, last_item_emb)
return mf + fmc + bias.T

@torch.no_grad()
def predict(self, user_idx, last_iid, item_indices=None):
if item_indices is None:
item_indices = torch.arange(self.item_num, device=self.device)
else:
item_indices = torch.as_tensor(
item_indices, dtype=torch.long, device=self.device
)
scores = self.forward(user_idx, last_iid, item_indices).squeeze()
return scores.detach().cpu().numpy()
Loading
Loading