Corin1998 commited on
Commit
8f61797
·
verified ·
1 Parent(s): 167c1df

Create linucb.py

Browse files
Files changed (1) hide show
  1. app/linucb.py +85 -0
app/linucb.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, math, hashlib
3
+ from typing import Dict, Any, Tuple
4
+ import numpy as np
5
+ from . import storage
6
+
7
+ def _seg_bucket(segment: str, buckets: int = 8) -> int:
8
+ if not segment:
9
+ return 0
10
+ h = hashlib.sha1(segment.encode("utf-8")).hexdigest()
11
+ return int(h[:8], 16) % buckets
12
+
13
+ def feature_vec(context: Dict[str, Any], d_seg: int = 8) -> np.ndarray:
14
+ hour = int(context.get("hour", 12))
15
+ seg = str(context.get("segment") or "")
16
+ x = np.zeros(1 + 24 + d_seg, dtype=float)
17
+ x[0] = 1.0 # bias
18
+ x[1 + max(0, min(23, hour))] = 1.0 # hour one-hot
19
+ x[1 + 24 + _seg_bucket(seg, d_seg)] = 1.0
20
+ return x
21
+
22
+ class LinUCB:
23
+ """
24
+ クリック率のLinUCB。p_click ≈ theta^T x + α * sqrt(x^T A^{-1} x)
25
+ CVRはベータ平均で補完し、EV=pc_ucb*E[CVR]*V を最大化。
26
+ """
27
+ def __init__(self, campaign_id: str, alpha: float = 0.3, d_seg: int = 8):
28
+ self.campaign_id = campaign_id
29
+ self.alpha = float(alpha)
30
+ self.d_seg = d_seg
31
+ self.d = 1 + 24 + d_seg
32
+
33
+ def _load_state(self, variant_id: str) -> Tuple[np.ndarray, np.ndarray, int]:
34
+ row = storage.get_linucb_state(self.campaign_id, variant_id)
35
+ if row:
36
+ A = np.array(json.loads(row["A_json"]), dtype=float).reshape(self.d, self.d)
37
+ b = np.array(json.loads(row["b_json"]), dtype=float).reshape(self.d, 1)
38
+ return A, b, int(row["n_updates"])
39
+ A = np.eye(self.d)
40
+ b = np.zeros((self.d, 1))
41
+ return A, b, 0
42
+
43
+ def _save_state(self, variant_id: str, A: np.ndarray, b: np.ndarray, n_updates: int):
44
+ storage.upsert_linucb_state(
45
+ self.campaign_id, variant_id, self.d,
46
+ json.dumps(A.reshape(-1).tolist()),
47
+ json.dumps(b.reshape(-1).tolist()),
48
+ int(n_updates),
49
+ )
50
+
51
+ def choose(self, context: Dict[str, Any]) -> Tuple[str | None, float]:
52
+ mets = storage.get_metrics(self.campaign_id)
53
+ if not mets:
54
+ return None, -1.0
55
+ vpc = storage.get_campaign_value_per_conversion(self.campaign_id)
56
+ x = feature_vec(context, self.d_seg).reshape(self.d, 1)
57
+
58
+ best_score, best_vid = -1.0, None
59
+ for r in mets:
60
+ vid = r["variant_id"]
61
+ A, b, _ = self._load_state(vid)
62
+ try:
63
+ A_inv = np.linalg.inv(A)
64
+ except np.linalg.LinAlgError:
65
+ A_inv = np.linalg.pinv(A)
66
+ theta = A_inv @ b
67
+ mean = float((theta.T @ x)[0, 0])
68
+ ucb = self.alpha * float(math.sqrt((x.T @ A_inv @ x)[0, 0]))
69
+ pc = max(0.0, min(1.0, mean + ucb))
70
+
71
+ # CVRはベータ平均で補完
72
+ av, bv = float(r["alpha_conv"]), float(r["beta_conv"])
73
+ pv_mean = av / max(1e-6, (av + bv))
74
+ score = pc * pv_mean * vpc
75
+ if score > best_score:
76
+ best_score, best_vid = score, vid
77
+ return best_vid, best_score
78
+
79
+ def update_click(self, variant_id: str, context: Dict[str, Any], reward: float):
80
+ # クリック有無で更新(reward=1/0)
81
+ x = feature_vec(context, self.d_seg).reshape(self.d, 1)
82
+ A, b, n = self._load_state(variant_id)
83
+ A = A + x @ x.T
84
+ b = b + reward * x
85
+ self._save_state(variant_id, A, b, n + 1)