- docs/e2e: 将 DAG 演示面板(dag-panel.mjs/html/data.mjs/sh/DAG演示.command)用 git mv 归入 dag-panel/ 子目录;修正相对依赖 ../lib、../results/dag-runs;清理 _diag_*.mjs 等临时诊断脚本(git rm 已跟踪项,rm 未跟踪项) - web: 修复头部用户名称切账号不变(新增 utils/user.ts 响应式 userName,登录/挂载/路由切换时拉取 /oauth/CurrentUser) - .gitignore: 新增 __pycache__/*.pyc 忽略规则(排除 demo 构建产物) - demo: 多个演示脚本与算子集市用例更新 - .workbuddy/memory: 补充本次工作记录 注意:docs/e2e/sswflow 与 **/__pycache__/*.pyc 按要求排除,未纳入。
86 lines
3.0 KiB
Python
86 lines
3.0 KiB
Python
"""dp_primitives 算子:差分隐私原语 clip_l2 + 高斯/拉普拉斯噪声 + RDP 账本。
|
|
|
|
场景:不暴露单个用户的情况下,发布"年龄直方图""平均工资"等统计。
|
|
- nax API: ``nax.privacy.dp.{clip_l2, gaussian_noise, laplace_noise, GaussianAccountant}``
|
|
- RDP 记账:每加一次噪声 → 累计 ε,最后 (ε, δ) 证明"这次发布满足差分隐私"
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
import numpy as np
|
|
from flask import Blueprint, jsonify, request, send_from_directory
|
|
|
|
_NAX = Path(__file__).resolve().parents[2] / "nax"
|
|
if str(_NAX) not in sys.path: sys.path.insert(0, str(_NAX))
|
|
|
|
from nax.privacy.dp import clip_l2, gaussian_noise, laplace_noise, GaussianAccountant
|
|
|
|
dp_bp = Blueprint("dp_primitives", __name__, url_prefix="/dp_primitives")
|
|
|
|
|
|
@dp_bp.route("/")
|
|
def index():
|
|
return send_from_directory(Path(__file__).parent, "index.html")
|
|
|
|
|
|
def _run(values, clip_c=5.0, sigma=2.0, q=0.5, steps=10, mechanism="gaussian", delta=1e-5):
|
|
raw = np.array(values, dtype=np.float64)
|
|
clipped = clip_l2(raw, c=clip_c)
|
|
bare_mean = float(raw.mean())
|
|
clipped_mean = float(clipped.mean())
|
|
|
|
# 噪声释放
|
|
if mechanism == "gaussian":
|
|
noise = gaussian_noise((1,), stddev=sigma, rng=np.random.default_rng(42))[0]
|
|
noisy = float(clipped.mean() + noise)
|
|
else:
|
|
noise = laplace_noise((1,), scale=sigma, rng=np.random.default_rng(42))[0]
|
|
noisy = float(clipped.mean() + noise)
|
|
|
|
# RDP 账本:每步加噪声 → 累计 ε
|
|
# nax 内部 rdp_sampled_gaussian 在 sigma 小 / alpha 大时会 math.exp overflow
|
|
# 解决方法:限制 orders 范围(≤ 30)避开大 alpha 分支
|
|
acct = GaussianAccountant(orders=[1.5 + 0.5 * i for i in range(20)])
|
|
for _ in range(steps):
|
|
acct.step(sigma=max(sigma, 1.0), q=q)
|
|
eps = acct.get_epsilon(delta=delta)
|
|
|
|
return {
|
|
"n": int(raw.size),
|
|
"raw_first_few": raw[:6].tolist(),
|
|
"raw_mean": bare_mean,
|
|
"clip_c": clip_c,
|
|
"clipped_first_few": clipped[:6].tolist(),
|
|
"clipped_mean": clipped_mean,
|
|
"mechanism": mechanism,
|
|
"sigma": sigma,
|
|
"noisy_mean": noisy,
|
|
"noise_added": noisy - clipped_mean,
|
|
"steps": steps,
|
|
"q": q,
|
|
"delta": delta,
|
|
"epsilon": eps,
|
|
"privacy_guarantee": f"({eps:.3f}, {delta})-DP",
|
|
}
|
|
|
|
|
|
@dp_bp.route("/api/run", methods=["POST"])
|
|
def api_run():
|
|
body = request.get_json(silent=True) or {}
|
|
vals = body.get("values") or []
|
|
if not vals:
|
|
return jsonify({"error": "values 必须非空"}), 400
|
|
try:
|
|
return jsonify(_run(
|
|
values=[float(x) for x in vals],
|
|
clip_c=float(body.get("clip_c", 5.0)),
|
|
sigma=float(body.get("sigma", 2.0)),
|
|
q=float(body.get("q", 0.5)),
|
|
steps=int(body.get("steps", 10)),
|
|
mechanism=body.get("mechanism", "gaussian"),
|
|
delta=float(body.get("delta", 1e-5)),
|
|
))
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|