J1Hard★ Core Essential · Industrial BedrockPart J · RecSys & Search Metrics
Factorization Machine (FM) O(kd) Implementation
Factorize pairwise feature interactions cleanly from O(k*d^2) down to linear O(k*d) complexity.
⏱️ Time:
O(B * D * K) 严格线性时间复杂度💾 Space:
O(D * K) 隐向量存储🎯 Interactive Self-Practice Loop (Attempt Before Peeking)
Practice in 4 steps: recall mechanism, complete core lines, check edge cases, and log mastery locally.
Step 1 · Mechanism Recall & Stability Self-Check
Step 2 · Complete Key Implementation Lines
import numpy as np
class FactorizationMachine:
def __init__(self, num_features: int, k_factors: int = 8):
self.w0 = 0.0 # 全局偏置
self.w1 = np.zeros(num_features) # 一阶线性权重 (D,)
self.V =
def forward(self, x: np.ndarray) -> np.ndarray:
"""
x: (B, D) 样本特征矩阵
返回: (B,) 预测打分
"""
# 1. 零阶与一阶线性部分: w0 + x @ w1
linear_part = self.w0 + x @ self.w1 # (B,)
# 2. 二阶交叉部分
# term1: (sum(V_if * x_i))^2 -> (x @ V)^2 -> (B, K)
sum_vx = x @ self.V # (B, K)
term1 = sum_vx ** 2 # (B, K)
# term2: sum(V_if^2 * x_i^2) -> (x^2 @ V^2) -> (B, K)
term2 = (x ** 2) @ (self.V ** 2) # (B, K)
# 沿 K 轴求和并乘 0.5
interaction_part = 0.5 * np.sum(term1 - term2, axis=-1) # (B,)
return
Step 3 · Verify Boundary Cases & Assertions
Step 4 · Follow-Up Drill & Review Outcome
Q1: How does DeepFM combine Factorization Machines with deep neural networks?
💡
Core Mental Anchor / Mnemonic
Compute 0.5 * ((sum vx)^2 - sum(v^2 x^2)) to evaluate all pairwise interactions in O(kd).
📐 Mathematical Derivation & Core Formula
### Factorization of Pairwise Interactions
Pairwise polynomial regression costs parameters and struggles on sparse inputs. Factorization Machines (Rendle, 2010) factorize interaction weights with latent factors :
This collapses pairwise computation from down to linear .
Pairwise polynomial regression costs parameters and struggles on sparse inputs. Factorization Machines (Rendle, 2010) factorize interaction weights with latent factors :
This collapses pairwise computation from down to linear .
🔄 Tensor Dimensions & Shape Flow
x: (B, D) -> linear (B,) + 0.5 * sum_k((x @ V)^2 - (x^2 @ V^2)) -> out (B,)
🛡️ Numerical Stability & Pitfalls Checklist
- Initialize latent factors V with small variance (e.g., 0.01) to prevent initial gradient blow-up.
- Pass raw FM logits through Sigmoid for binary CTR click prediction.
💻 Reference Code Implementation
import numpy as np
class FactorizationMachine:
def __init__(self, num_features: int, k_factors: int = 8):
self.w0 = 0.0 # 全局偏置
self.w1 = np.zeros(num_features) # 一阶线性权重 (D,)
self.V = np.random.randn(num_features, k_factors) * 0.01 # 二阶隐向量 (D, K)
def forward(self, x: np.ndarray) -> np.ndarray:
"""
x: (B, D) 样本特征矩阵
返回: (B,) 预测打分
"""
# 1. 零阶与一阶线性部分: w0 + x @ w1
linear_part = self.w0 + x @ self.w1 # (B,)
# 2. 二阶交叉部分
# term1: (sum(V_if * x_i))^2 -> (x @ V)^2 -> (B, K)
sum_vx = x @ self.V # (B, K)
term1 = sum_vx ** 2 # (B, K)
# term2: sum(V_if^2 * x_i^2) -> (x^2 @ V^2) -> (B, K)
term2 = (x ** 2) @ (self.V ** 2) # (B, K)
# 沿 K 轴求和并乘 0.5
interaction_part = 0.5 * np.sum(term1 - term2, axis=-1) # (B,)
return linear_part + interaction_part
🧪 Runnable Assertions & Validation
Copy and run directly in Python / Jupyter:
import numpy as np
fm = FactorizationMachine(num_features=5, k_factors=4)
x = np.random.randn(2, 5)
out = fm.forward(x)
assert out.shape == (2,)
assert not np.isnan(out).any()
print("✓ FM 因子分解机自测通过")🎯 Core Follow-up Inquiries & Reference Answers
Q1:How does DeepFM combine Factorization Machines with deep neural networks?
DeepFM shares a common embedding table across an explicit FM branch (linear + 2nd-order pairwise terms) and a parallel MLP branch (capturing higher-order non-linear interactions), jointly summing both outputs.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
中文速览与面试要点
FM 因子分解机(二阶特征交叉 O(kd) 手撕)
推荐系统经典里程碑,通过代数平方差化简将 O(k*d^2) 的全特征交叉降至 O(k*d) 线性复杂度。
核心要点
- ### 二阶交叉项的代数化简神技 Steffen Rendle 在 2010 年提出因子分解机(FM)。 在稀疏推荐场景中,高维特征(如 d=10^6)两两交叉 _i<j w_ij x_i x_j 参数量达 O(d^2),不仅极易过拟合且计算不可行。 FM 为每个特征学习一个 k 维隐向量 v_i R^k,令交叉权重 w_ij = v_i, v_j 。 关键化简步骤: _i=1^d _j=i+1^d v_i, v_j x_i x_j = 12 ( _i=1^d _j=1^d v_i, v_j x_i x_j - _i=1^d v_i, v_i x_i^2 ) 展开内积并在各维度上独立提取公因子: = 12 _f=1^k [ ( _i=1^d v_i, f x_i )^2 - _i=1^d v_i, f^2 x_i^2 ] 成功将计算量从 O(k d^2) 压缩到 O(k d) 线性耗时!
- x: (B, D) -> linear: (B,) -> sum_vx: (B, K) -> term1, term2 -> 0.5*sum(term1-term2) -> (B,)
- V 必须使用小方差(如 0.01)初始化,防止二阶交叉在初期产生巨大数值导致发散
- 在实际 CTR 点击率预估中,最后通常通过 Sigmoid 输出预估点击率概率
- DeepFM 是如何在 FM 基础上进行深度学习升级的?:DeepFM 共享相同的 Embedding 输入层,并列并行构建两个分支:FM 分支负责通过上述代数公式手撕显式的二阶低阶特征交叉;Deep 分支通过多层感知机(MLP)拟合高阶非线性特征交互,最后将两部分加权输出,实现了端到端端兼顾记忆性与泛化性。
参考实现
import numpy as np
class FactorizationMachine:
def __init__(self, num_features: int, k_factors: int = 8):
self.w0 = 0.0 # 全局偏置
self.w1 = np.zeros(num_features) # 一阶线性权重 (D,)
self.V = np.random.randn(num_features, k_factors) * 0.01 # 二阶隐向量 (D, K)
def forward(self, x: np.ndarray) -> np.ndarray:
"""
x: (B, D) 样本特征矩阵
返回: (B,) 预测打分
"""
# 1. 零阶与一阶线性部分: w0 + x @ w1
linear_part = self.w0 + x @ self.w1 # (B,)
# 2. 二阶交叉部分
# term1: (sum(V_if * x_i))^2 -> (x @ V)^2 -> (B, K)
sum_vx = x @ self.V # (B, K)
term1 = sum_vx ** 2 # (B, K)
# term2: sum(V_if^2 * x_i^2) -> (x^2 @ V^2) -> (B, K)
term2 = (x ** 2) @ (self.V ** 2) # (B, K)
# 沿 K 轴求和并乘 0.5
interaction_part = 0.5 * np.sum(term1 - term2, axis=-1) # (B,)
return linear_part + interaction_part