Environment
Python 3.14.6, NumPy 2.4.6, Matplotlib 3.11.2, PyTorch 2.15.0.
Overview
Chapter 12, “Using Connections for Recommendations,” of Marketing Science in Theory and Practice represents purchases as a graph and uses graph neural networks (GNNs) to recommend products. This article follows the chapter through the business problem, graph theory, NGCF and LightGCN implementations, and evaluation results.
Setup code (imports and display settings)
from base64 import b64encode
from copy import deepcopy
from importlib.metadata import version
from io import BytesIO
from pathlib import Path
from pprint import pprint
import platform
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.ticker import FuncFormatter, ScalarFormatter, MaxNLocator
import torch
from torch import nn
from torch.nn import functional as F
from IPython.display import Latex, display
# ノートブックのフォルダー、またはリポジトリ直下から実行する。
BASE = Path.cwd()
if (BASE / "blog/12/12_nb.ipynb").exists():
BASE = BASE / "blog/12"
FIG_DIR = BASE / "12_nb_files"
FIG_DIR.mkdir(exist_ok=True)
def sig3(value):
"""末尾のゼロも残して有効数字3桁で表示する。"""
return format(float(value), "#.3g").removesuffix(".")
def show_math(tex):
# 重要式の原稿は \( ... \)。出力では二重の区切りを避ける。
tex = tex.strip()
if tex.startswith(r"\(") and tex.endswith(r"\)"):
tex = tex[2:-2].strip()
display(Latex("$$\n" + tex + "\n$$"))
def save_svg(fig, filename):
"""SVGを保存し、同じ図をノートブックにも埋め込む。"""
for ax in fig.axes:
for axis in (ax.xaxis, ax.yaxis):
if isinstance(axis.get_major_formatter(), ScalarFormatter):
axis.set_major_formatter(FuncFormatter(
lambda value, _: str(int(value))
if float(value).is_integer() else sig3(value)
))
path = FIG_DIR / filename
fig.savefig(path, format="svg", bbox_inches="tight")
# SVG非対応のビューアー向けに、出力欄だけPNGも埋め込む。
preview = BytesIO()
fig.savefig(preview, format="png", dpi=120, bbox_inches="tight")
plt.close(fig)
display({"image/svg+xml": path.read_text(encoding="utf-8"),
"image/png": b64encode(preview.getvalue()).decode("ascii")}, raw=True)
def heatmap(ax, matrix, rows, cols, title, vmax=None, integer=False):
"""小さな行列を、数値付きのヒートマップで確認する。"""
limit = float(np.max(matrix)) if vmax is None else vmax
ax.imshow(matrix, cmap="Blues", vmin=0, vmax=max(limit, 1.00e-12), aspect="auto")
ax.set(xticks=range(len(cols)), xticklabels=cols,
yticks=range(len(rows)), yticklabels=rows, title=title)
for (row, col), value in np.ndenumerate(matrix):
label = str(int(value)) if integer or value == 0 else sig3(value)
ax.text(col, row, label, ha="center", va="center", fontsize=9,
color="white" if value > limit * 0.550 else "black")
np.set_printoptions(formatter={"float_kind": sig3})
available_fonts = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ("Hiragino Sans", "Noto Sans CJK JP", "IPAexGothic", "Yu Gothic"):
if candidate in available_fonts:
plt.rcParams["font.family"] = candidate
break
plt.rcParams.update({"font.size": 11, "axes.unicode_minus": False,
"svg.fonttype": "path", "svg.hashsalt": "blog12"})
COLORS = ["#3274A1", "#D58B27", "#419578"]
torch.set_num_threads(1)
torch.manual_seed(123)
print("仮想環境:wa-src(3.14.6)")
print(f"Python:{platform.python_version()} / OS:{platform.system()}")
for package in ("numpy", "matplotlib", "torch"):
print(f"{package}:{version(package)}")
仮想環境:wa-src(3.14.6)
Python:3.14.6 / OS:Darwin
numpy:2.4.6
matplotlib:3.11.2
torch:2.15.0
1. What should we recommend to users with little history?
What should we suggest after someone buys a product? Even with little personal history, purchases by other users who bought the same item can provide clues. The chapter introduces connections through examples such as referrals and similar purchasing among friends.
Basic matrix factorization learns shared patterns from purchase histories. LightGBM can use connections through constructed features, such as the proportion of friends who bought an item. GNNs collect information from connected nodes and reach farther through repeated processing.
However, purchase links alone cannot carry information to a new user with no purchase history. Distinguish that case from having a small history. Check results by history size as well as overall accuracy. The implementation uses user–product purchase links, not friendship links.
2. Learn preferences from a graph
2.1 Represent purchases with matrices
In graph $G=(V,E)$, $V$ is the node set and $E$ the edge set. Keeping users and products in separate sets and connecting purchased pairs gives a bipartite graph. Purchasing is directional as an action, but we use an undirected graph to pass information both ways.
The purchase matrix $\mathbf{R}$ has users as rows and products as columns, with 1 for a purchase and 0 otherwise. The user–user and product–product blocks of adjacency matrix $\mathbf{A}$ are zero. The following example has three users and four products.
show_math(r"""\(
\mathbf{R}=\begin{pmatrix}1&1&0&0\\0&1&1&0\\0&0&1&1\end{pmatrix},
\qquad
\mathbf{A}=\begin{pmatrix}\mathbf{0}&\mathbf{R}\\
\mathbf{R}^{\top}&\mathbf{0}\end{pmatrix}.
\)""")
R = np.array([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1]])
A = np.block([[np.zeros((3, 3)), R], [R.T, np.zeros((4, 4))]])
users = ["u1", "u2", "u3"]
items = ["i1", "i2", "i3", "i4"]
nodes = users + items
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
user_y = np.linspace(1, 0, len(users))
item_y = np.linspace(1, 0, len(items))
for u, i in np.argwhere(R == 1):
axes[0].plot([0, 1], [user_y[u], item_y[i]], color="#A6AFB5", zorder=1)
for x, yy, names, color in ((0, user_y, users, COLORS[0]),
(1, item_y, items, COLORS[1])):
axes[0].scatter(np.full(len(yy), x), yy, s=600, color=color, zorder=2)
for y, label in zip(yy, names):
axes[0].text(x, y, label, ha="center", va="center", color="white")
axes[0].set(title="購入関係の二部グラフ", xlim=(-0.300, 1.30), ylim=(-0.150, 1.15))
axes[0].axis("off")
heatmap(axes[1], R, users, items, "購入行列 R", integer=True)
save_svg(fig, "01_purchase_graph.svg")
$$ \mathbf{R}=\begin{pmatrix}1&1&0&0\\0&1&1&0\\0&0&1&1\end{pmatrix}, \qquad \mathbf{A}=\begin{pmatrix}\mathbf{0}&\mathbf{R}\\ \mathbf{R}^{\top}&\mathbf{0}\end{pmatrix}. $$
2.2 Adjust weights by node degree
Let $d_v$ be node $v$’s degree, and place the degrees on the diagonal of $\mathbf{D}$. The graph Laplacian is $\mathbf{L}=\mathbf{D}-\mathbf{A}$. For positive degrees, multiply on both sides by $\mathbf{D}^{-1/2}$ to obtain the following expression.
show_math(r"""\(
\begin{aligned}
d_v&=\sum_w A_{vw},\qquad \mathbf{D}=\operatorname{diag}(d_1,\ldots,d_7),\\
\widetilde{\mathbf{L}}
&=\mathbf{D}^{-1/2}(\mathbf{D}-\mathbf{A})\mathbf{D}^{-1/2}\\
&=\mathbf{D}^{-1/2}\mathbf{D}\mathbf{D}^{-1/2}
-\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2}\\
&=\mathbf{I}-\widetilde{\mathbf{A}},\qquad
\widetilde{\mathbf{A}}=\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2},\\
\widetilde{A}_{vw}&=\frac{A_{vw}}{\sqrt{d_v}\sqrt{d_w}}.
\end{aligned}
\)""")
degree = A.sum(axis=1)
# 孤立ノードは逆数を0とし、ゼロ除算を避ける。
inverse_sqrt = np.divide(1, np.sqrt(degree), out=np.zeros_like(degree), where=degree > 0)
A_norm = inverse_sqrt[:, None] * A * inverse_sqrt[None, :]
pprint({"各ノードの次数": degree.astype(int).tolist()})
fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")
heatmap(axes[0], A, nodes, nodes, "隣接行列 A", integer=True)
heatmap(axes[1], np.diag(degree), nodes, nodes, "次数行列 D", integer=True)
heatmap(axes[2], A_norm, nodes, nodes, "対称正規化した隣接行列")
save_svg(fig, "02_graph_matrices.svg")
$$ \begin{aligned} d_v&=\sum_w A_{vw},\qquad \mathbf{D}=\operatorname{diag}(d_1,\ldots,d_7),\\ \widetilde{\mathbf{L}} &=\mathbf{D}^{-1/2}(\mathbf{D}-\mathbf{A})\mathbf{D}^{-1/2}\\ &=\mathbf{D}^{-1/2}\mathbf{D}\mathbf{D}^{-1/2} -\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2}\\ &=\mathbf{I}-\widetilde{\mathbf{A}},\qquad \widetilde{\mathbf{A}}=\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2},\\ \widetilde{A}_{vw}&=\frac{A_{vw}}{\sqrt{d_v}\sqrt{d_w}}. \end{aligned} $$
{'各ノードの次数': [2, 2, 2, 1, 2, 2, 1]}
In Figure 2, normalization changes edge weights but not edge locations. For example, $u_1$ and $i_1$ have degrees 2 and 1, giving weight $1/\sqrt{2\times1}\approx0.707$. This adjusts the influence of highly connected nodes.
2.3 GCN and message passing
An embedding is a numerical vector representing a node. A GCN adds self-loops, collects each node’s own and its neighbors’ embeddings, and transforms them using a weight matrix $\mathbf{W}$ and activation function $\phi$. The matrix $\mathbf{H}^{(l)}$ contains all node embeddings at layer $l$.
show_math(r"""\(
\begin{aligned}
\widehat{\mathbf{A}}&=\mathbf{A}+\mathbf{I},\qquad
\widehat{D}_{vv}=\sum_w\widehat{A}_{vw},\\
\overline{\mathbf{A}}&=\widehat{\mathbf{D}}^{-1/2}
\widehat{\mathbf{A}}\widehat{\mathbf{D}}^{-1/2},\\
\mathbf{H}^{(l+1)}&=\phi\!\left(\overline{\mathbf{A}}
\mathbf{H}^{(l)}\mathbf{W}^{(l)}\right).
\end{aligned}
\)""")
$$ \begin{aligned} \widehat{\mathbf{A}}&=\mathbf{A}+\mathbf{I},\qquad \widehat{D}_{vv}=\sum_w\widehat{A}_{vw},\\ \overline{\mathbf{A}}&=\widehat{\mathbf{D}}^{-1/2} \widehat{\mathbf{A}}\widehat{\mathbf{D}}^{-1/2},\\ \mathbf{H}^{(l+1)}&=\phi\!\left(\overline{\mathbf{A}} \mathbf{H}^{(l)}\mathbf{W}^{(l)}\right). \end{aligned} $$
This information exchange is called message passing. Aggregation can use a sum, mean, maximum, or other operation. One layer reaches neighbors; two reach nodes up to two edges away. More layers can make embeddings too similar, a problem called oversmoothing, so deeper is not always better.
2.4 NGCF uses aggregation and elementwise products
The chapter’s NGCF uses $\mathbf{S}$, obtained by row-normalizing the adjacency matrix and then adding self-loops. It also takes the elementwise product $\odot$ of the aggregate $\mathbf{M}$ and the current embeddings $\mathbf{E}$. We learn weight matrices $\mathbf{W}_1,\mathbf{W}_2$ and biases $\mathbf{b}_1,\mathbf{b}_2$.
show_math(r"""\(
\begin{aligned}
\mathbf{S}&=\mathbf{D}^{-1}\mathbf{A}+\mathbf{I},\qquad
\mathbf{M}=\mathbf{S}\mathbf{E}^{(l)},\\
\mathbf{Z}&=\mathbf{M}\mathbf{W}_1+\mathbf{b}_1
+(\mathbf{M}\odot\mathbf{E}^{(l)})\mathbf{W}_2+\mathbf{b}_2,\\
\mathbf{E}^{(l+1)}&=\operatorname{LeakyReLU}(\mathbf{Z}).
\end{aligned}
\)""")
$$ \begin{aligned} \mathbf{S}&=\mathbf{D}^{-1}\mathbf{A}+\mathbf{I},\qquad \mathbf{M}=\mathbf{S}\mathbf{E}^{(l)},\\ \mathbf{Z}&=\mathbf{M}\mathbf{W}_1+\mathbf{b}_1 +(\mathbf{M}\odot\mathbf{E}^{(l)})\mathbf{W}_2+\mathbf{b}_2,\\ \mathbf{E}^{(l+1)}&=\operatorname{LeakyReLU}(\mathbf{Z}). \end{aligned} $$
The equation omits dropout and vector-length normalization. Finally, the initial and intermediate layer embeddings are concatenated across columns. This chapter’s NGCF differs from the original paper in its normalization and includes self-loops in the elementwise-product term.
2.5 LightGCN uses propagation and averaging
LightGCN removes weight transformations, activation functions, and self-loops from propagation. Averaging across layers, including the initial layer, retains a node’s own information. Below, $L$ is the layer count and $\hat y_{ui}$ a recommendation score, not a purchase probability.
show_math(r"""\(
\begin{aligned}
\mathbf{E}^{(l+1)}&=\widetilde{\mathbf{A}}\mathbf{E}^{(l)},\\
\mathbf{E}^{(2)}&=\widetilde{\mathbf{A}}
(\widetilde{\mathbf{A}}\mathbf{E}^{(0)})
=\widetilde{\mathbf{A}}^2\mathbf{E}^{(0)},\\
\mathbf{E}_{\mathrm{final}}&=\frac{1}{L+1}\sum_{l=0}^{L}\mathbf{E}^{(l)},
\qquad \hat y_{ui}=\mathbf{e}_u^\top\mathbf{e}_i.
\end{aligned}
\)""")
$$ \begin{aligned} \mathbf{E}^{(l+1)}&=\widetilde{\mathbf{A}}\mathbf{E}^{(l)},\\ \mathbf{E}^{(2)}&=\widetilde{\mathbf{A}} (\widetilde{\mathbf{A}}\mathbf{E}^{(0)}) =\widetilde{\mathbf{A}}^2\mathbf{E}^{(0)},\\ \mathbf{E}_{\mathrm{final}}&=\frac{1}{L+1}\sum_{l=0}^{L}\mathbf{E}^{(l)}, \qquad \hat y_{ui}=\mathbf{e}_u^\top\mathbf{e}_i. \end{aligned} $$
In the example graph, set $\mathbf{e}_{u_1}^{(0)}=\mathbf{e}_{i_1}^{(0)}=(1,0)$ and $\mathbf{e}_{u_2}^{(0)}=\mathbf{e}_{i_2}^{(0)}=(0,1)$. The first layer brings in product information; the second brings in information from users who bought the same products. This illustrates propagation only, not a trained result.
show_math(r"""\(
\begin{aligned}
\mathbf{e}_{u_1}^{(1)}
&=\frac{(1,0)}{\sqrt{2\times1}}+\frac{(0,1)}{\sqrt{2\times2}}
=\left(\frac{1}{\sqrt2},\frac12\right),\\
\mathbf{e}_{i_1}^{(1)}&=\frac{(1,0)}{\sqrt2},\qquad
\mathbf{e}_{i_2}^{(1)}=\frac{(1,0)}2+\frac{(0,1)}2,\\
\mathbf{e}_{u_1}^{(2)}
&=\frac{\mathbf{e}_{i_1}^{(1)}}{\sqrt2}
+\frac{\mathbf{e}_{i_2}^{(1)}}2
=\left(\frac12+\frac14,\frac14\right)
=\left(\frac34,\frac14\right),\\
\mathbf{e}_{u_1}&=\frac{(1,0)+(1/\sqrt2,1/2)+(3/4,1/4)}3
\approx(0.819,0.250).
\end{aligned}
\)""")
E0 = np.array([[1, 0], [0, 1], [1, 1], [1, 0], [0, 1], [1, 1], [2, 0]], dtype=float)
E1 = A_norm @ E0
E2 = A_norm @ E1
E_final = (E0 + E1 + E2) / 3
pprint({"u1の最終埋め込み": E_final[0]})
fig, axes = plt.subplots(1, 4, figsize=(12, 4), layout="constrained")
for ax, embeddings, title in zip(axes, (E0, E1, E2, E_final),
("初期層", "1層目", "2層目", "初期+2層の平均")):
heatmap(ax, embeddings, nodes, ["次元1", "次元2"], title, vmax=2)
save_svg(fig, "03_embedding_propagation.svg")
$$ \begin{aligned} \mathbf{e}_{u_1}^{(1)} &=\frac{(1,0)}{\sqrt{2\times1}}+\frac{(0,1)}{\sqrt{2\times2}} =\left(\frac{1}{\sqrt2},\frac12\right),\\ \mathbf{e}_{i_1}^{(1)}&=\frac{(1,0)}{\sqrt2},\qquad \mathbf{e}_{i_2}^{(1)}=\frac{(1,0)}2+\frac{(0,1)}2,\\ \mathbf{e}_{u_1}^{(2)} &=\frac{\mathbf{e}_{i_1}^{(1)}}{\sqrt2} +\frac{\mathbf{e}_{i_2}^{(1)}}2 =\left(\frac12+\frac14,\frac14\right) =\left(\frac34,\frac14\right),\\ \mathbf{e}_{u_1}&=\frac{(1,0)+(1/\sqrt2,1/2)+(3/4,1/4)}3 \approx(0.819,0.250). \end{aligned} $$
{'u1の最終埋め込み': array([0.819, 0.250])}
2.6 BPR loss ranks purchased products above unobserved ones
Let $\Delta$ be the score difference between purchased item $i$ and unobserved item $j$. Using sigmoid function $\sigma$, the ranking loss can be rewritten as follows. Unobserved does not mean disliked; such items may be purchased in the future.
show_math(r"""\(
\begin{aligned}
\Delta&=\hat y_{ui}-\hat y_{uj},\qquad
\sigma(\Delta)=\frac{1}{1+e^{-\Delta}},\\
\ell(\Delta)&=-\log\sigma(\Delta)
=-\log\frac{1}{1+e^{-\Delta}}
=\log(1+e^{-\Delta}),\\
\ell(0)&=\log(1+1)=\log2\approx0.693,\\
\mathcal{J}&=\frac{1}{|\mathcal{B}|}\sum_{(u,i,j)\in\mathcal{B}}
\left[\ell(\Delta)+\lambda
\left(\|\mathbf{e}^{(0)}_u\|^2+\|\mathbf{e}^{(0)}_i\|^2
+\|\mathbf{e}^{(0)}_j\|^2\right)\right].
\end{aligned}
\)""")
delta = np.linspace(-4, 4, 201)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.50), layout="constrained")
axes[0].plot(delta, 1 / (1 + np.exp(-delta)), color=COLORS[0])
axes[0].set(ylabel="シグモイドの値", ylim=(0, 1))
axes[1].plot(delta, np.logaddexp(0, -delta), color=COLORS[1])
axes[1].set(ylabel="順位損失")
for ax in axes:
ax.set(xlabel="購入済み − 未観測のスコア差")
ax.axvline(0, color="gray", linestyle="--", linewidth=1)
ax.grid(alpha=0.250)
save_svg(fig, "04_bpr_loss.svg")
$$ \begin{aligned} \Delta&=\hat y_{ui}-\hat y_{uj},\qquad \sigma(\Delta)=\frac{1}{1+e^{-\Delta}},\\ \ell(\Delta)&=-\log\sigma(\Delta) =-\log\frac{1}{1+e^{-\Delta}} =\log(1+e^{-\Delta}),\\ \ell(0)&=\log(1+1)=\log2\approx0.693,\\ \mathcal{J}&=\frac{1}{|\mathcal{B}|}\sum_{(u,i,j)\in\mathcal{B}} \left[\ell(\Delta)+\lambda \left(\|\mathbf{e}^{(0)}_u\|^2+\|\mathbf{e}^{(0)}_i\|^2 +\|\mathbf{e}^{(0)}_j\|^2\right)\right]. \end{aligned} $$
Figure 4 shows smaller ranking loss when the purchased item scores higher. Here $\mathcal{B}$ is the set of triples used for an update and $\lambda$ controls embedding-size regularization. LightGCN regularizes initial embeddings, while the book’s NGCF regularizes the concatenated layer embeddings.
3. Train and evaluate recommendations in Python
The book separates data processing into Dataset, models into models, and training and evaluation into Trainer and Evaluator. Here we use a shorter implementation to make the calculations easier to follow. The small example uses dense matrices and omits NGCF dropout. The book’s implementation includes sparse-matrix processing and persistence for real data.
3.1 Implement NGCF
First define matrix factorization as a BPR baseline, then implement NGCF aggregation, elementwise products, normalization, and concatenation.
class BPR(nn.Module):
"""ユーザーと商品のIDに対応する埋め込みを学ぶ行列分解。"""
def __init__(self, purchase, dim=8):
super().__init__()
self.n_users, self.n_items = purchase.shape
self.embedding = nn.Parameter(
torch.randn(self.n_users + self.n_items, dim) * 0.100
)
R_tensor = torch.as_tensor(purchase, dtype=torch.float32)
adjacency = torch.zeros(self.n_users + self.n_items,
self.n_users + self.n_items)
adjacency[:self.n_users, self.n_users:] = R_tensor
adjacency[self.n_users:, :self.n_users] = R_tensor.T
self.register_buffer("adjacency", adjacency)
def forward(self):
# 推薦スコア用と正則化用の埋め込みを返す。
return self.embedding, self.embedding
class NGCF(BPR):
def __init__(self, purchase, dim=8, n_layers=2):
super().__init__(purchase, dim)
degree = self.adjacency.sum(dim=1)
# 行正規化してから、自己ループを加える。
propagation = self.adjacency / degree.clamp_min(1)[:, None]
propagation = propagation + torch.eye(len(degree))
self.register_buffer("propagation", propagation)
self.linear = nn.ModuleList([nn.Linear(dim, dim) for _ in range(n_layers)])
self.interaction = nn.ModuleList([nn.Linear(dim, dim) for _ in range(n_layers)])
def forward(self):
current = self.embedding
outputs = [current]
for linear, interaction in zip(self.linear, self.interaction):
neighbors = self.propagation @ current
current = linear(neighbors) + interaction(neighbors * current)
current = F.leaky_relu(current, negative_slope=0.200)
current = F.normalize(current, p=2, dim=1)
outputs.append(current)
combined = torch.cat(outputs, dim=1)
return combined, combined
3.2 Implement LightGCN
Build a symmetrically normalized adjacency matrix from the same purchase matrix. Use averaged propagated embeddings for scores and the initial embeddings for regularization.
class LightGCN(BPR):
def __init__(self, purchase, dim=8, n_layers=2):
super().__init__(purchase, dim)
self.n_layers = n_layers
degree = self.adjacency.sum(dim=1)
inverse = degree.clamp_min(1).rsqrt() * (degree > 0)
normalized = inverse[:, None] * self.adjacency * inverse[None, :]
self.register_buffer("propagation", normalized)
def forward(self):
current = self.embedding
total = current
for _ in range(self.n_layers):
current = self.propagation @ current
total = total + current
return total / (self.n_layers + 1), self.embedding
3.3 Separate training and evaluation data
Generate simulated histories for 12 users and ten products. Each user buys five products from one of two groups in sequence. Use the first three for training, the fourth for validation, and the fifth for testing. Only training links enter the graph.
Draw negative examples from products unobserved at training time. In validation, exclude training purchases from candidates; in testing, exclude training and validation purchases. Recall@K measures the share of relevant items in the top $K$, while nDCG@K also considers their ranks.
show_math(r"""\(
\begin{aligned}
\operatorname{Recall}@K&=\frac{\sum_{r=1}^{K}h_r}{|T_u|},\qquad
\operatorname{Precision}@K=\frac{\sum_{r=1}^{K}h_r}{K},\\
\operatorname{DCG}@K&=\sum_{r=1}^{K}\frac{h_r}{\log_2(r+1)},\\
\operatorname{IDCG}@K&=\sum_{r=1}^{\min(K,|T_u|)}\frac{1}{\log_2(r+1)},\qquad
\operatorname{nDCG}@K=\frac{\operatorname{DCG}@K}{\operatorname{IDCG}@K}.
\end{aligned}
\)""")
# 正解が1商品で、それが2位にある場合の計算。
show_math(r"""\(
\begin{aligned}
(h_1,h_2)&=(0,1),\qquad |T_u|=1,\\
\operatorname{Recall}@2&=(0+1)/1=1,\qquad
\operatorname{Precision}@2=(0+1)/2=0.500,\\
\operatorname{DCG}@2&=0/\log_2 2+1/\log_2 3\approx0.631,\\
\operatorname{IDCG}@2&=1/\log_2 2=1,\qquad
\operatorname{nDCG}@2\approx0.631/1=0.631.
\end{aligned}
\)""")
rng = np.random.default_rng(123)
n_users, n_items = 12, 10
train = np.zeros((n_users, n_items), dtype=bool)
valid = np.zeros_like(train)
test = np.zeros_like(train)
for u in range(n_users):
group = 0 if u < n_users // 2 else 5
ordered = rng.permutation(np.arange(group, group + 5))
train[u, ordered[:3]] = True
valid[u, ordered[3]] = True
test[u, ordered[4]] = True
# 本文と同様、評価対象のユーザー・商品が学習側にあることを確認する。
assert train.any(axis=0).all() and train.any(axis=1).all()
assert not ((train & valid) | (train & test) | (valid & test)).any()
pprint({"学習の組数": int(train.sum()), "検証の組数": int(valid.sum()),
"テストの組数": int(test.sum())})
@torch.no_grad()
def evaluate(model, seen, truth, k=2):
"""ユーザーごとに計算して、同じ重みで平均する。"""
model.eval()
embeddings, _ = model()
scores = embeddings[:n_users] @ embeddings[n_users:].T
scores = scores.masked_fill(torch.as_tensor(seen), -torch.inf)
ranking = scores.topk(k, dim=1).indices.numpy()
hits = np.take_along_axis(truth, ranking, axis=1)
discount = 1 / np.log2(np.arange(2, k + 2))
relevant = truth.sum(axis=1)
ideal = np.array([discount[:min(k, count)].sum() for count in relevant])
metrics = {
f"Recall@{k}": float(np.mean(hits.sum(axis=1) / relevant)),
f"Precision@{k}": float(hits.mean()),
f"nDCG@{k}": float(np.mean((hits * discount).sum(axis=1) / ideal)),
}
return metrics, scores.numpy(), ranking
def fit(model_class):
"""同じ初期乱数・負例系列・学習条件で、小規模な計算を確認する。"""
torch.manual_seed(123)
sampler = np.random.default_rng(123)
model = model_class(train)
optimizer = torch.optim.Adam(model.parameters(), lr=0.0300)
user_np, positive_np = np.nonzero(train)
user = torch.as_tensor(user_np)
positive = torch.as_tensor(positive_np + n_users)
negative_pools = [np.flatnonzero(~row) for row in train]
history = {"loss": [], "recall": []}
best_recall, stale, best_epoch = -1, 0, 0
for epoch in range(1, 101):
model.train()
# 学習時点の未観測商品から等確率で負例を抽出する。
negative_np = np.array([sampler.choice(negative_pools[u]) for u in user_np])
negative = torch.as_tensor(negative_np + n_users)
embeddings, penalty = model()
difference = (embeddings[user] *
(embeddings[positive] - embeddings[negative])).sum(dim=1)
regularization = (penalty[user].square().sum(dim=1)
+ penalty[positive].square().sum(dim=1)
+ penalty[negative].square().sum(dim=1)).mean()
# softplus(-差)で、-log(sigmoid(差))を安定して計算する。
loss = F.softplus(-difference).mean() + 0.00100 * regularization
optimizer.zero_grad()
loss.backward()
optimizer.step()
validation, _, _ = evaluate(model, train, valid)
history["loss"].append(loss.item())
history["recall"].append(validation["Recall@2"])
if validation["Recall@2"] > best_recall:
best_recall = validation["Recall@2"]
best_state = deepcopy(model.state_dict())
best_epoch, stale = epoch, 0
else:
stale += 1
if stale >= 10:
break
# テストはモデル選択に使わず、検証で選んだ状態を復元して評価する。
model.load_state_dict(best_state)
metrics, scores, ranking = evaluate(model, train | valid, test)
return model, history, best_epoch, metrics, scores, ranking
$$ \begin{aligned} \operatorname{Recall}@K&=\frac{\sum_{r=1}^{K}h_r}{|T_u|},\qquad \operatorname{Precision}@K=\frac{\sum_{r=1}^{K}h_r}{K},\\ \operatorname{DCG}@K&=\sum_{r=1}^{K}\frac{h_r}{\log_2(r+1)},\\ \operatorname{IDCG}@K&=\sum_{r=1}^{\min(K,|T_u|)}\frac{1}{\log_2(r+1)},\qquad \operatorname{nDCG}@K=\frac{\operatorname{DCG}@K}{\operatorname{IDCG}@K}. \end{aligned} $$
$$ \begin{aligned} (h_1,h_2)&=(0,1),\qquad |T_u|=1,\\ \operatorname{Recall}@2&=(0+1)/1=1,\qquad \operatorname{Precision}@2=(0+1)/2=0.500,\\ \operatorname{DCG}@2&=0/\log_2 2+1/\log_2 3\approx0.631,\\ \operatorname{IDCG}@2&=1/\log_2 2=1,\qquad \operatorname{nDCG}@2\approx0.631/1=0.631. \end{aligned} $$
{'テストの組数': 12, '学習の組数': 36, '検証の組数': 12}
In the equations, $T_u$ is the relevant-item set and $h_r$ is 1 when the item at rank $r$ is relevant. Stop training after ten consecutive epochs without an improvement in validation Recall@2, then restore the best epoch. This small example checks the procedure; it is not an experiment for establishing which model is best.
results = {}
for model_class in (BPR, NGCF, LightGCN):
results[model_class.__name__] = fit(model_class)
_, history, best_epoch, metrics, _, _ = results[model_class.__name__]
pprint({"モデル": model_class.__name__, "採用エポック": best_epoch,
"終了エポック": len(history["loss"]),
"模擬データのテスト": {key: sig3(value) for key, value in metrics.items()}})
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
for (name, result), color in zip(results.items(), COLORS):
_, history, best_epoch, _, _, _ = result
epochs = np.arange(1, len(history["loss"]) + 1)
axes[0].plot(epochs, history["loss"], color=color, label=name)
axes[1].plot(epochs, history["recall"], color=color, label=name)
axes[1].scatter(best_epoch, history["recall"][best_epoch - 1], color=color, s=50)
axes[0].set(ylabel="学習時の損失", title="模擬データ:損失の推移")
axes[1].set(ylabel="検証 Recall@2", ylim=(0, 1.08), title="点は採用した時点")
for ax in axes:
ax.set_xlabel("エポック")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.grid(alpha=0.250)
ax.legend()
save_svg(fig, "05_training_curves.svg")
# ユーザー1人の推薦を、正解とともに読む。
_, _, _, _, scores, ranking = results["LightGCN"]
target_user = 0
candidates = np.flatnonzero(~(train | valid)[target_user])
candidate_scores = scores[target_user, candidates]
candidate_order = np.argsort(-candidate_scores, kind="stable")
candidates = candidates[candidate_order]
candidate_scores = candidate_scores[candidate_order]
pprint({"u1への推薦上位2件": (ranking[target_user] + 1).tolist(),
"テストの正解商品": (np.flatnonzero(test[target_user]) + 1).tolist()})
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
stage = train.astype(int) + 2 * valid + 3 * test
axes[0].imshow(stage, cmap=plt.matplotlib.colors.ListedColormap(
["#F4F6F8", COLORS[0], COLORS[1], COLORS[2]]), vmin=0, vmax=3, aspect="auto")
axes[0].set(xticks=range(n_items), xticklabels=range(1, n_items + 1),
yticks=range(n_users), yticklabels=range(1, n_users + 1),
xlabel="商品番号", ylabel="ユーザー番号", title="青:学習/橙:検証/緑:テスト")
bar_colors = [COLORS[2] if test[target_user, i] else "#A6AFB5" for i in candidates]
axes[1].barh(range(len(candidates)), candidate_scores, color=bar_colors)
axes[1].set(yticks=range(len(candidates)), yticklabels=[f"i{i + 1}" for i in candidates],
xlabel="推薦スコア(確率ではない)", title="u1の候補:緑はテストの正解")
axes[1].invert_yaxis()
axes[1].xaxis.set_major_locator(MaxNLocator(4))
axes[1].axhline(1.50, color="black", linestyle="--", linewidth=1)
axes[1].grid(axis="x", alpha=0.250)
save_svg(fig, "06_recommendations.svg")
{'モデル': 'BPR',
'採用エポック': 16,
'模擬データのテスト': {'Precision@2': '0.500', 'Recall@2': '1.00', 'nDCG@2': '0.846'},
'終了エポック': 26}
{'モデル': 'NGCF',
'採用エポック': 2,
'模擬データのテスト': {'Precision@2': '0.250', 'Recall@2': '0.500', 'nDCG@2': '0.377'},
'終了エポック': 12}
{'モデル': 'LightGCN',
'採用エポック': 4,
'模擬データのテスト': {'Precision@2': '0.500', 'Recall@2': '1.00', 'nDCG@2': '1.00'},
'終了エポック': 14}
{'u1への推薦上位2件': [2, 8], 'テストの正解商品': [2]}
In Figure 5, losses fluctuate with negative sampling and include regularization, so their values alone do not compare model performance. Figure 6 excludes training and validation purchases from recommendation candidates. The two items above the dotted line are recommended.
4. Read the comparison reported in the book
The chapter removes returns and other excluded records from Online Retail, retains the first purchase for each customer–product pair, and removes customers and products with fewer than five connections. Customers with at least three remaining invoices are split chronologically by invoice. Preprocessing leaves 1,884 customers, 2,985 products, and 197,104 pairs.
The next figure plots values reported in the book, not results from the simulated example above. Total runtime is measured on an Apple M2 Pro CPU and includes loading, preprocessing, training, and evaluation.
# 出典:doc/12/12_main.tex「BPR・NGCF・LightGCNの比較」の掲載値。
names = ["BPR", "NGCF", "LightGCN"]
book_results = {
"テスト Recall@10": np.array([0.0344, 0.0391, 0.0403]),
"テスト nDCG@10": np.array([0.0458, 0.0493, 0.0526]),
"総時間(分)": np.array([0.790, 9.00, 6.87]),
}
pprint({metric: {name: sig3(value) for name, value in zip(names, values)}
for metric, values in book_results.items()})
fig, axes = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
for ax, (metric, values) in zip(axes, book_results.items()):
bars = ax.bar(names, values, color=COLORS)
ax.bar_label(bars, labels=[sig3(value) for value in values], padding=4)
ax.set(title=metric, ylim=(0, float(values.max()) * 1.20))
ax.grid(axis="y", alpha=0.250)
fig.suptitle("第12章の掲載値:Online Retail、seed=123の1回の結果")
save_svg(fig, "07_book_comparison.svg")
{'テスト Recall@10': {'BPR': '0.0344', 'LightGCN': '0.0403', 'NGCF': '0.0391'},
'テスト nDCG@10': {'BPR': '0.0458', 'LightGCN': '0.0526', 'NGCF': '0.0493'},
'総時間(分)': {'BPR': '0.790', 'LightGCN': '6.87', 'NGCF': '9.00'}}
Under these conditions, LightGCN has the highest scores but takes longer than BPR. This is one run with a fixed random seed; the same differences are not guaranteed every time. Filtering uses the full observation period, and evaluation excludes users and products absent from training, so it does not measure new-user performance.
In practice, check accuracy by history size, bias toward popular products, and response time. Then run a limited A/B test and compare click-through or purchase rates. Higher offline recommendation scores do not establish higher sales.
Conclusion
This article introduced a workflow that represents purchases as a graph, learns embeddings with NGCF and LightGCN, and recommends unobserved products.
NGCF uses aggregation and elementwise products, while LightGCN uses propagation and averages across layers. Data splitting and candidate filtering affect results as well as model architecture.
Chapter 12 of Marketing Science in Theory and Practice explains real-data preprocessing, sparse graph construction, training control, and interpretation. The full code is on the support page .
References: Wang et al., Neural Graph Collaborative Filtering , 2019; He et al., LightGCN , 2020. The book’s comparison uses D. Chen, Online Retail , UCI, 2015.