Python 案例:如何分配不同场景的权重
权重分配是数据分析和业务决策中的常见需求,下面我用一个完整的电商推荐场景案例来讲解几种实用的权重分配方法。

场景设定
假设我们要给用户推荐商品,需要考虑 4 个维度:
| 维度 | 说明 |
|---|---|
| 用户偏好匹配度 | 用户历史兴趣 |
| 商品热度 | 销量、点击量 |
| 商品利润 | 佣金高低 |
| 时效性 | 上新时间 |
不同业务场景下,这些维度的重要性不同,需要分配不同权重。
手动配置权重(适合业务规则明确)
import pandas as pd
import numpy as np
# 不同场景的权重配置
SCENE_WEIGHTS = {
"新用户首页": {"preference": 0.1, "hotness": 0.6, "profit": 0.2, "freshness": 0.1},
"老用户推荐": {"preference": 0.5, "hotness": 0.2, "profit": 0.2, "freshness": 0.1},
"促销活动页": {"preference": 0.1, "hotness": 0.2, "profit": 0.5, "freshness": 0.2},
"新品专区": {"preference": 0.2, "hotness": 0.1, "profit": 0.1, "freshness": 0.6},
}
# 校验权重之和为 1
for scene, w in SCENE_WEIGHTS.items():
assert abs(sum(w.values()) - 1.0) < 1e-6, f"{scene} 权重和不为1"
def score_items(df, scene):
"""按场景权重计算商品综合得分"""
weights = SCENE_WEIGHTS[scene]
df = df.copy()
df["score"] = sum(df[col] * w for col, w in weights.items())
return df.sort_values("score", ascending=False)
# 示例数据(各维度已归一化到 0~1)
items = pd.DataFrame({
"item": ["A", "B", "C", "D"],
"preference": [0.9, 0.3, 0.6, 0.2],
"hotness": [0.2, 0.9, 0.5, 0.4],
"profit": [0.3, 0.2, 0.8, 0.5],
"freshness": [0.1, 0.2, 0.3, 0.9],
})
print("=== 老用户推荐场景 ===")
print(score_items(items, "老用户推荐"))
print("\n=== 新品专区场景 ===")
print(score_items(items, "新品专区"))
适用:业务经验丰富、规则稳定的场景。
AHP 层次分析法(专家打分定量化)
适合多专家协商权重,把主观判断转化为数值。
import numpy as np
def ahp_weights(matrix):
"""AHP 权重计算 + 一致性检验"""
matrix = np.array(matrix, dtype=float)
n = matrix.shape[0]
# 特征值法求权重
eigvals, eigvecs = np.linalg.eig(matrix)
max_idx = np.argmax(eigvals.real)
weights = eigvecs[:, max_idx].real
weights = weights / weights.sum()
# 一致性检验
CI = (eigvals[max_idx].real - n) / (n - 1)
RI_dict = {1:0, 2:0, 3:0.58, 4:0.90, 5:1.12, 6:1.24, 7:1.32}
CR = CI / RI_dict[n] if RI_dict[n] else 0
print(f"一致性比率 CR = {CR:.4f} {'✓ 通过' if CR < 0.1 else '✗ 需调整'}")
return weights
# 专家判断矩阵:行为"相对重要",1~9 标度
# 顺序:偏好 / 热度 / 利润 / 时效
judgment = [
[1, 1, 1, 3 ], # 偏好
[1, 1, 1, 3 ], # 热度
[1, 1, 1, 3 ], # 利润
[1/3, 1/3, 1/3, 1 ], # 时效
]
w = ahp_weights(judgment)
print("AHP 权重:", dict(zip(["preference","hotness","profit","freshness"], w.round(3))))
输出示例权重:preference≈0.30, hotness≈0.30, profit≈0.30, freshness≈0.10
适用:需要多方专家达成共识的场景(医疗、金融风控等)。
熵权法(数据驱动,客观赋权)
权重由数据离散程度自动决定——差异越大的指标越重要。
def entropy_weight(df):
"""熵权法:从数据自动计算权重"""
data = df.values.astype(float)
# 归一化(指标需同向:越大越好)
p = data / data.sum(axis=0)
# 避免 log(0)
p = np.where(p == 0, 1e-12, p)
# 计算信息熵
n = data.shape[0]
e = -np.sum(p * np.log(p), axis=0) / np.log(n)
# 差异系数
d = 1 - e
# 归一化权重
return d / d.sum()
weights = entropy_weight(items[["preference","hotness","profit","freshness"]])
print("熵权法权重:", dict(zip(
["preference","hotness","profit","freshness"], weights.round(3)
)))
优点:完全客观,不受人为因素影响。
缺点:可能忽略业务真实重要性(如利润很低的指标差异大反而权重高)。
组合赋权(主客观结合,推荐做法)
实际项目中最常用:AHP 主观权重 × 熵权法客观权重 做乘法归一化。
def combine_weights(subjective, objective):
"""乘法组合赋权"""
combined = subjective * objective
return combined / combined.sum()
w_subj = np.array([0.30, 0.30, 0.30, 0.10]) # AHP 结果
w_obj = entropy_weight(items[["preference","hotness","profit","freshness"]])
w_final = combine_weights(w_subj, w_obj)
print("组合权重:", dict(zip(
["preference","hotness","profit","freshness"], w_final.round(3)
)))
场景自适应权重(动态调整)
根据用户行为实时调整权重,比如新用户自动提高热度权重。
def dynamic_weights(user):
"""根据用户状态动态生成权重"""
base = np.array([0.3, 0.3, 0.3, 0.1])
if user["is_new"]:
base += np.array([-0.2, +0.3, 0.0, +0.0]) # 新用户偏热度
if user["is_promo_triggered"]:
base += np.array([-0.1, -0.1, +0.2, +0.0]) # 促销偏利润
if user["last_active_days"] > 30:
base += np.array([-0.1, +0.0, +0.0, +0.2]) # 流失风险偏时效
base = np.clip(base, 0.05, None) # 防止出现负权重
return base / base.sum()
user = {"is_new": True, "is_promo_triggered": False, "last_active_days": 2}
print("动态权重:", dynamic_weights(user).round(3))
| 方法 | 数据依赖 | 主观性 | 适用场景 |
|---|---|---|---|
| 手动配置 | 无 | 高 | 规则清晰、快速上线 |
| AHP | 弱 | 中(专家) | 多方协商、指标体系复杂 |
| 熵权法 | 强 | 低(客观) | 有充分数据、追求公平 |
| 组合赋权 | 强 | 平衡 | 生产环境首选 |
| 动态权重 | 中 | 中 | 用户分层、实时个性化 |
实践建议
- 业务初期用方法一,快速验证;
- 数据积累后上方法五(动态权重),按用户场景细分;
- 关键决策(如风控额度)用方法二/四,保留决策解释性;
- 务必做归一化,各指标量纲一致;
- 权重需可配置化(放配置中心 / 数据库),避免硬编码。
如果你告诉我具体是哪种场景(推荐系统 / 风控评分 / 供应商评估 / 绩效打分),我可以给出更贴合的量表和代码模板。