Open
fix(user-ops): RFM combo 的 R 位改为二值化,修复中间分值用户落兜底档 #2
fix(user-ops): RFM combo 的 R 位改为二值化,修复中间分值用户落兜底档 #2
Open
待遇安然风Add on 18 days ago
Total: 2 files changed+92-1
@@ -0,0 +1,87 @@
1+#!/usr/bin/env python3
2+# -*- coding: utf-8 -*-
3+"""rfm_segmentation.py 回归测试:combo 三位都必须落在 SEGMENT_MAP 的 {1,5}^3 键内。
4+ 
5+用法:
6+ python tests/test_rfm_segmentation.py
7+ 
8+覆盖:
9+ [M] 映射命中 构造 R 分散在 1-5 各档的用户,segments.csv 里每个 rfm_combo 都必须是
10+ SEGMENT_MAP 的 key(修复前 R∈{2,3,4} 会拼出 254、315 这类无效 key)
11+ [F] 分层覆盖 8 档人群里至少能出现 4 种不同标签,避免退化成两极
12+"""
13+import csv
14+import os
15+import subprocess
16+import sys
17+import tempfile
18+from datetime import datetime, timedelta
19+ 
20+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21+SCRIPT = os.path.join(ROOT, "user-operations", "scripts", "rfm_segmentation.py")
22+sys.path.insert(0, os.path.join(ROOT, "user-operations", "scripts"))
23+ 
24+from rfm_segmentation import SEGMENT_MAP # noqa: E402
25+ 
26+FAILS = []
27+ 
28+ 
29+def check(ok, msg):
30+ print((" [OK] " if ok else " [FAIL] ") + msg)
31+ if not ok:
32+ FAILS.append(msg)
33+ 
34+ 
35+def build_csv(path):
36+ today = datetime.now()
37+ with open(path, "w", encoding="utf-8", newline="") as f:
38+ w = csv.writer(f)
39+ w.writerow(["user_id", "last_active_date", "order_count", "total_amount"])
40+ # 60 个用户:recency 1~120 天、order_count 1~20、amount 100~2000,尽量铺满各档
41+ for i in range(60):
42+ days = 1 + i * 2
43+ d = (today - timedelta(days=days)).strftime("%Y-%m-%d")
44+ w.writerow([f"u{i:03d}", d, 1 + i % 20, 100 + i * 30])
45+ 
46+ 
47+def run_case():
48+ tmp = tempfile.mkdtemp(prefix="rfm_test_")
49+ csv_path = os.path.join(tmp, "rfm_users.csv")
50+ out_dir = os.path.join(tmp, "out")
51+ build_csv(csv_path)
52+ proc = subprocess.run(
53+ [sys.executable, SCRIPT, csv_path, "--output", out_dir],
54+ capture_output=True, text=True, encoding="utf-8",
55+ )
56+ check(proc.returncode == 0, f"脚本退出码为 0(实际 {proc.returncode}): {proc.stderr.strip()[:200]}")
57+ out_csv = os.path.join(out_dir, "segments.csv")
58+ check(os.path.isfile(out_csv), "segments.csv 已生成")
59+ if not os.path.isfile(out_csv):
60+ return
61+ 
62+ with open(out_csv, encoding="utf-8") as f:
63+ rows = list(csv.DictReader(f))
64+ 
65+ combos = [r["rfm_combo"] for r in rows]
66+ check(len(rows) == 60, f"输出 60 行(实际 {len(rows)})")
67+ invalid = sorted(set(combos) - set(SEGMENT_MAP))
68+ check(not invalid, "所有 rfm_combo 都在 SEGMENT_MAP 内(无效值: %s)" % invalid[:5])
69+ check(all(set(c) <= {"1", "5"} and len(c) == 3 for c in combos),
70+ "combo 每位只能是 1 或 5(实际: %s)" % sorted(set(combos))[:6])
71+ 
72+ segments = {r["segment"] for r in rows}
73+ check(len(segments) >= 4, f"至少覆盖 4 种人群标签(实际 {len(segments)} 种: {sorted(segments)})")
74+ 
75+ 
76+def main():
77+ print("== rfm_segmentation 回归测试")
78+ run_case()
79+ print()
80+ if FAILS:
81+ print(f"FAILED: {len(FAILS)} 项未通过")
82+ sys.exit(1)
83+ print("全部通过")
84+ 
85+ 
86+if __name__ == "__main__":
87+ main()
@@ -151,7 +151,11 @@ def main():
151 f_s = f_map.get(rec["freq"], 1)151 f_s = f_map.get(rec["freq"], 1)
152 m_s = m_map.get(rec["amount"], 1) if has_amount else 1152 m_s = m_map.get(rec["amount"], 1) if has_amount else 1
153 153 
154- combo = f"{r_s}{'5' if f_s > max_f / 2 else '1'}{'5' if m_s > max_m / 2 else '1'}"154+ combo = (
155+ f"{'5' if r_s > args.r_score / 2 else '1'}"
156+ f"{'5' if f_s > max_f / 2 else '1'}"
157+ f"{'5' if m_s > max_m / 2 else '1'}"
158+ )
155 seg = SEGMENT_MAP.get(combo)159 seg = SEGMENT_MAP.get(combo)
156 if seg is None:160 if seg is None:
157 seg = "重要价值用户" if (r_s > args.r_score / 2 and f_s > max_f / 2 and m_s > max_m / 2) else "一般挽留用户"161 seg = "重要价值用户" if (r_s > args.r_score / 2 and f_s > max_f / 2 and m_s > max_m / 2) else "一般挽留用户"