Spaces:
Sleeping
Sleeping
Commit ·
1cd50fe
1
Parent(s): 5e53438
Move to DataDesigner generation + SDMetrics/fairlearn tools (drop SDV/torch)
Browse files- Synthesizer: NVIDIA NeMo DataDesigner (statistical samplers fit to real data)
- Evaluators as tools: SDMetrics (fidelity/privacy/ML efficacy) + fairlearn (fairness)
- Tool-calling chat agent; single-generator dashboard
- Lightweight image: no SDV, no torch
- Dockerfile +1 -3
- README.md +15 -18
- app.py +82 -122
- pipeline/agent.py +17 -32
- pipeline/data.py +1 -9
- pipeline/evaluate.py +19 -17
- pipeline/fairness.py +64 -0
- pipeline/generate.py +40 -44
- pipeline/llm.py +6 -2
- pipeline/metadata.py +22 -0
- pipeline/run.py +0 -87
- requirements.txt +5 -5
Dockerfile
CHANGED
|
@@ -9,9 +9,7 @@ ENV HOME=/home/user \
|
|
| 9 |
|
| 10 |
WORKDIR /home/user/app
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
RUN pip install --no-cache-dir --user torch --index-url https://download.pytorch.org/whl/cpu
|
| 14 |
-
|
| 15 |
COPY --chown=user requirements.txt .
|
| 16 |
RUN pip install --no-cache-dir --user -r requirements.txt
|
| 17 |
|
|
|
|
| 9 |
|
| 10 |
WORKDIR /home/user/app
|
| 11 |
|
| 12 |
+
# No torch needed — DataDesigner generation + SDMetrics/fairlearn evaluation are lightweight.
|
|
|
|
|
|
|
| 13 |
COPY --chown=user requirements.txt .
|
| 14 |
RUN pip install --no-cache-dir --user -r requirements.txt
|
| 15 |
|
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: Memisis
|
| 3 |
emoji: 🧬
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
|
@@ -8,36 +8,33 @@ app_port: 7860
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
-
# Memisis
|
| 12 |
|
| 13 |
-
A
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
|
| 16 |
## Run locally
|
| 17 |
|
| 18 |
```bash
|
| 19 |
-
python3.11 -m venv .venv && source .venv/bin/activate
|
| 20 |
pip install -r requirements.txt
|
| 21 |
streamlit run app.py
|
| 22 |
```
|
| 23 |
|
| 24 |
-
##
|
| 25 |
|
| 26 |
-
``
|
| 27 |
-
|
| 28 |
-
```
|
| 29 |
|
| 30 |
## Layout
|
| 31 |
|
| 32 |
| File | Role |
|
| 33 |
|---|---|
|
| 34 |
-
| `pipeline/data.py` | Load OpenML 45040
|
| 35 |
-
| `pipeline/
|
| 36 |
-
| `pipeline/
|
| 37 |
-
| `pipeline/
|
|
|
|
|
|
|
| 38 |
| `app.py` | Streamlit UI |
|
| 39 |
-
|
| 40 |
-
## Metrics
|
| 41 |
-
|
| 42 |
-
SDMetrics **Quality Score** (0–1, higher = better) is the mean of **Column Shapes**
|
| 43 |
-
(per-column distributions) and **Column Pair Trends** (relationships between columns).
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Memisis Agent
|
| 3 |
emoji: 🧬
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
|
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Memisis Agent
|
| 12 |
|
| 13 |
+
A chat-driven synthetic-data copilot. Generation uses **NVIDIA NeMo DataDesigner**
|
| 14 |
+
(statistical samplers fit to the real data); evaluation uses **SDMetrics** (fidelity,
|
| 15 |
+
privacy, ML efficacy) and **fairlearn** (fairness) as tools. An LLM agent turns natural
|
| 16 |
+
language into generation requests and explains the metrics.
|
| 17 |
|
| 18 |
## Run locally
|
| 19 |
|
| 20 |
```bash
|
|
|
|
| 21 |
pip install -r requirements.txt
|
| 22 |
streamlit run app.py
|
| 23 |
```
|
| 24 |
|
| 25 |
+
## LLM
|
| 26 |
|
| 27 |
+
OpenAI (default when `OPENAI_API_KEY` is set) or a local Ollama. On Hugging Face, add
|
| 28 |
+
`OPENAI_API_KEY` as a Space secret.
|
|
|
|
| 29 |
|
| 30 |
## Layout
|
| 31 |
|
| 32 |
| File | Role |
|
| 33 |
|---|---|
|
| 34 |
+
| `pipeline/data.py` | Load OpenML 45040 |
|
| 35 |
+
| `pipeline/metadata.py` | SDMetrics metadata dict |
|
| 36 |
+
| `pipeline/generate.py` | **Synthesizer** — DataDesigner |
|
| 37 |
+
| `pipeline/evaluate.py` | **Evaluators (tools)** — SDMetrics fidelity/privacy/efficacy |
|
| 38 |
+
| `pipeline/fairness.py` | **Evaluator** — fairlearn fairness |
|
| 39 |
+
| `pipeline/agent.py` | Tool-calling chat agent |
|
| 40 |
| `app.py` | Streamlit UI |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
| 1 |
-
"""Memisis
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import pandas as pd
|
| 5 |
import streamlit as st
|
| 6 |
|
| 7 |
from pipeline import agent, llm
|
| 8 |
-
from pipeline.data import
|
| 9 |
from pipeline.evaluate import evaluate_all
|
| 10 |
-
from pipeline.generate import
|
|
|
|
| 11 |
|
| 12 |
-
st.set_page_config(page_title="Memisis
|
| 13 |
|
| 14 |
st.markdown(
|
| 15 |
"""
|
|
@@ -27,8 +28,8 @@ st.markdown(
|
|
| 27 |
)
|
| 28 |
st.markdown(
|
| 29 |
"<div class='hero-title'><span class='accent'>Memisis</span> Agent</div>"
|
| 30 |
-
"<div class='hero-sub'>
|
| 31 |
-
"
|
| 32 |
unsafe_allow_html=True,
|
| 33 |
)
|
| 34 |
|
|
@@ -43,7 +44,7 @@ def get_real() -> pd.DataFrame:
|
|
| 43 |
|
| 44 |
|
| 45 |
@st.cache_resource(show_spinner=False)
|
| 46 |
-
def get_metadata(_real: pd.DataFrame):
|
| 47 |
return build_metadata(_real)
|
| 48 |
|
| 49 |
|
|
@@ -51,62 +52,38 @@ real = get_real()
|
|
| 51 |
metadata = get_metadata(real)
|
| 52 |
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
return max(vals, key=lambda x: x[1]) if vals else None
|
| 74 |
-
|
| 75 |
-
bq = best(lambda r: r.get("overall_score"))
|
| 76 |
-
bp = best(lambda r: r.get("new_row_synthesis"))
|
| 77 |
-
bm = best(lambda r: r.get("ml_efficacy"))
|
| 78 |
-
parts = [f"✅ Generated & evaluated **{', '.join(order)}**."]
|
| 79 |
-
if bq:
|
| 80 |
-
parts.append(f"Best fidelity: **{bq[0]}** ({bq[1]:.3f}).")
|
| 81 |
-
if bp:
|
| 82 |
-
parts.append(f"Most private: **{bp[0]}** ({bp[1]:.3f}).")
|
| 83 |
-
if bm:
|
| 84 |
-
parts.append(f"Best ML efficacy: **{bm[0]}** ({bm[1]:.3f}).")
|
| 85 |
-
parts.append("Full comparison below. ⬇️")
|
| 86 |
-
return " ".join(parts)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
# ── Sidebar: manual controls (fallback to the agent) ─────────────────────────
|
| 90 |
with st.sidebar:
|
| 91 |
-
st.header("
|
| 92 |
-
st.caption("
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if st.button("🧪 Generate & Evaluate", type="primary", disabled=not m_models, use_container_width=True):
|
| 98 |
-
prog = st.progress(0.0, text="Starting…")
|
| 99 |
-
st.session_state["results"] = run_models(
|
| 100 |
-
m_models, m_sample, m_train, m_epochs,
|
| 101 |
-
progress=lambda n, i, t: prog.progress((i - 1) / t, text=f"{n}…"),
|
| 102 |
-
)
|
| 103 |
-
prog.empty()
|
| 104 |
st.session_state.setdefault("chat", [])
|
| 105 |
|
| 106 |
-
st.caption(f"**Input:** OpenML 45040 ·
|
| 107 |
-
f"LLM: {llm.provider()}")
|
| 108 |
|
| 109 |
-
# ── Agent chat
|
| 110 |
st.session_state.setdefault("chat", [])
|
| 111 |
for _m in st.session_state["chat"]:
|
| 112 |
with st.chat_message(_m["role"]):
|
|
@@ -114,31 +91,26 @@ for _m in st.session_state["chat"]:
|
|
| 114 |
|
| 115 |
if not llm.available():
|
| 116 |
st.info("Set `OPENAI_API_KEY` (or run a local Ollama) to enable the agent. "
|
| 117 |
-
"You can still
|
| 118 |
|
| 119 |
-
_prompt = st.chat_input("e.g. Generate
|
| 120 |
if _prompt and llm.available():
|
| 121 |
st.session_state["chat"].append({"role": "user", "content": _prompt})
|
| 122 |
with st.chat_message("user"):
|
| 123 |
st.markdown(_prompt)
|
| 124 |
with st.chat_message("assistant"):
|
| 125 |
try:
|
| 126 |
-
decision = agent.decide(_prompt, st.session_state.get("
|
| 127 |
st.session_state["chat"][:-1])
|
| 128 |
except Exception as _exc:
|
| 129 |
decision = {"action": "answer", "reply": f"Sorry, I hit an error: {_exc}"}
|
| 130 |
|
| 131 |
if decision.get("action") == "generate":
|
| 132 |
-
|
| 133 |
-
st.markdown(decision.get("reply") or "On it — generating with
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
p["synthesizers"], p["sample_rows"], p["train_rows"], p["epochs"],
|
| 138 |
-
progress=lambda n, i, t: prog.progress((i - 1) / t, text=f"{n}…"),
|
| 139 |
-
)
|
| 140 |
-
prog.empty()
|
| 141 |
-
_reply = summary_line(st.session_state["results"])
|
| 142 |
st.markdown(_reply)
|
| 143 |
else:
|
| 144 |
_reply = decision.get("reply") or "…"
|
|
@@ -146,59 +118,47 @@ if _prompt and llm.available():
|
|
| 146 |
st.session_state["chat"].append({"role": "assistant", "content": _reply})
|
| 147 |
st.rerun()
|
| 148 |
|
| 149 |
-
# ── Dashboard
|
| 150 |
-
|
| 151 |
-
if not
|
| 152 |
st.stop()
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
st.divider()
|
| 157 |
-
st.markdown("### Fidelity · Privacy · ML utility")
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
st.markdown("### Comparison")
|
| 170 |
-
chart_df = pd.DataFrame(
|
| 171 |
-
{
|
| 172 |
-
"Quality": [results[n].get("overall_score") for n in order],
|
| 173 |
-
"Privacy (new rows)": [results[n].get("new_row_synthesis") for n in order],
|
| 174 |
-
"ML efficacy": [results[n].get("ml_efficacy") for n in order],
|
| 175 |
-
},
|
| 176 |
-
index=order,
|
| 177 |
-
)
|
| 178 |
-
st.bar_chart(chart_df, color=["#4a90d9", "#2ecc71", "#9b59b6"])
|
| 179 |
-
|
| 180 |
-
table = pd.DataFrame(
|
| 181 |
-
{
|
| 182 |
-
"Quality": [results[n].get("overall_score") for n in order],
|
| 183 |
-
"Column Shapes": [results[n]["properties"].get("Column Shapes") for n in order],
|
| 184 |
-
"Column Pair Trends": [results[n]["properties"].get("Column Pair Trends") for n in order],
|
| 185 |
-
"Privacy (new rows)": [results[n].get("new_row_synthesis") for n in order],
|
| 186 |
-
"ML efficacy": [results[n].get("ml_efficacy") for n in order],
|
| 187 |
-
},
|
| 188 |
-
index=order,
|
| 189 |
-
).round(3)
|
| 190 |
-
st.dataframe(table, use_container_width=True)
|
| 191 |
st.caption(
|
| 192 |
-
"
|
| 193 |
-
"
|
| 194 |
-
"
|
| 195 |
)
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
st.
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Memisis Agent — chat-driven synthetic data with NVIDIA DataDesigner + SDMetrics/fairlearn tools."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import pandas as pd
|
| 5 |
import streamlit as st
|
| 6 |
|
| 7 |
from pipeline import agent, llm
|
| 8 |
+
from pipeline.data import load_real
|
| 9 |
from pipeline.evaluate import evaluate_all
|
| 10 |
+
from pipeline.generate import generate
|
| 11 |
+
from pipeline.metadata import build_metadata
|
| 12 |
|
| 13 |
+
st.set_page_config(page_title="Memisis Agent — DataDesigner × SDMetrics", page_icon="🧬", layout="wide")
|
| 14 |
|
| 15 |
st.markdown(
|
| 16 |
"""
|
|
|
|
| 28 |
)
|
| 29 |
st.markdown(
|
| 30 |
"<div class='hero-title'><span class='accent'>Memisis</span> Agent</div>"
|
| 31 |
+
"<div class='hero-sub'>Chat to generate synthetic data with <b>NVIDIA DataDesigner</b>, "
|
| 32 |
+
"evaluated for fidelity, privacy, ML utility & fairness with <b>SDMetrics + fairlearn</b> (as tools).</div>",
|
| 33 |
unsafe_allow_html=True,
|
| 34 |
)
|
| 35 |
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
@st.cache_resource(show_spinner=False)
|
| 47 |
+
def get_metadata(_real: pd.DataFrame) -> dict:
|
| 48 |
return build_metadata(_real)
|
| 49 |
|
| 50 |
|
|
|
|
| 52 |
metadata = get_metadata(real)
|
| 53 |
|
| 54 |
|
| 55 |
+
def run_generation(num_records: int) -> dict:
|
| 56 |
+
syn = generate(real, num_records)
|
| 57 |
+
result = evaluate_all(real, syn, metadata)
|
| 58 |
+
result["synthetic"] = syn
|
| 59 |
+
return result
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def summary_line(r: dict) -> str:
|
| 63 |
+
fair = r.get("fairness") or {}
|
| 64 |
+
return (
|
| 65 |
+
f"✅ Generated **{len(r['synthetic']):,}** rows with DataDesigner. "
|
| 66 |
+
f"Fidelity **{fmt(r.get('overall_score'))}** · "
|
| 67 |
+
f"Privacy **{fmt(r.get('new_row_synthesis'))}** · "
|
| 68 |
+
f"ML efficacy **{fmt(r.get('ml_efficacy'))}** · "
|
| 69 |
+
f"Fairness FPR gap **{fmt(fair.get('max_fpr_gap'))}**. Details below. ⬇️"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ── Sidebar: manual control ──────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
with st.sidebar:
|
| 75 |
+
st.header("Generate")
|
| 76 |
+
st.caption("DataDesigner fits statistical samplers to the real data and samples new rows.")
|
| 77 |
+
m_rows = st.number_input("Synthetic rows", 100, 11000, 1000, 100)
|
| 78 |
+
if st.button("🧪 Generate & Evaluate", type="primary", use_container_width=True):
|
| 79 |
+
with st.spinner("DataDesigner generating & evaluating…"):
|
| 80 |
+
st.session_state["result"] = run_generation(int(m_rows))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
st.session_state.setdefault("chat", [])
|
| 82 |
|
| 83 |
+
st.caption(f"**Input:** OpenML 45040 · **Generator:** NVIDIA DataDesigner · "
|
| 84 |
+
f"**Eval:** SDMetrics + fairlearn (tools) · **LLM:** {llm.provider()}")
|
| 85 |
|
| 86 |
+
# ── Agent chat ───────────────────────────────────────────────────────────────
|
| 87 |
st.session_state.setdefault("chat", [])
|
| 88 |
for _m in st.session_state["chat"]:
|
| 89 |
with st.chat_message(_m["role"]):
|
|
|
|
| 91 |
|
| 92 |
if not llm.available():
|
| 93 |
st.info("Set `OPENAI_API_KEY` (or run a local Ollama) to enable the agent. "
|
| 94 |
+
"You can still generate from the sidebar.")
|
| 95 |
|
| 96 |
+
_prompt = st.chat_input("e.g. Generate 2000 synthetic rows and tell me if it's private")
|
| 97 |
if _prompt and llm.available():
|
| 98 |
st.session_state["chat"].append({"role": "user", "content": _prompt})
|
| 99 |
with st.chat_message("user"):
|
| 100 |
st.markdown(_prompt)
|
| 101 |
with st.chat_message("assistant"):
|
| 102 |
try:
|
| 103 |
+
decision = agent.decide(_prompt, st.session_state.get("result"),
|
| 104 |
st.session_state["chat"][:-1])
|
| 105 |
except Exception as _exc:
|
| 106 |
decision = {"action": "answer", "reply": f"Sorry, I hit an error: {_exc}"}
|
| 107 |
|
| 108 |
if decision.get("action") == "generate":
|
| 109 |
+
n = (decision.get("params") or {}).get("num_records", 1000)
|
| 110 |
+
st.markdown(decision.get("reply") or "On it — generating with DataDesigner…")
|
| 111 |
+
with st.spinner("DataDesigner generating & evaluating…"):
|
| 112 |
+
st.session_state["result"] = run_generation(int(n))
|
| 113 |
+
_reply = summary_line(st.session_state["result"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
st.markdown(_reply)
|
| 115 |
else:
|
| 116 |
_reply = decision.get("reply") or "…"
|
|
|
|
| 118 |
st.session_state["chat"].append({"role": "assistant", "content": _reply})
|
| 119 |
st.rerun()
|
| 120 |
|
| 121 |
+
# ── Dashboard ────────────────────────────────────────────────────────────────
|
| 122 |
+
result = st.session_state.get("result")
|
| 123 |
+
if not result:
|
| 124 |
st.stop()
|
| 125 |
|
| 126 |
+
fair = result.get("fairness") or {}
|
|
|
|
| 127 |
st.divider()
|
| 128 |
+
st.markdown("### Evaluation — Fidelity · Privacy · ML utility · Fairness")
|
| 129 |
+
c = st.columns(4)
|
| 130 |
+
c[0].metric("Quality (fidelity)", fmt(result.get("overall_score")),
|
| 131 |
+
help="SDMetrics: Column Shapes + Column Pair Trends. Higher = closer to real.")
|
| 132 |
+
c[1].metric("Privacy — new rows", fmt(result.get("new_row_synthesis")),
|
| 133 |
+
help="Fraction of synthetic rows that are genuinely new. Higher = more private.")
|
| 134 |
+
c[2].metric("ML efficacy", fmt(result.get("ml_efficacy")),
|
| 135 |
+
help="F1 of a model trained on synthetic, tested on real. Higher = more useful.")
|
| 136 |
+
c[3].metric("Fairness — FPR gap ↓", fmt(fair.get("max_fpr_gap")),
|
| 137 |
+
help="Largest false-positive-rate gap across Race/Sex (fairlearn). LOWER = fairer.")
|
| 138 |
+
|
| 139 |
+
props = result.get("properties", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
st.caption(
|
| 141 |
+
f"Fidelity breakdown — Column Shapes: **{fmt(props.get('Column Shapes'))}**, "
|
| 142 |
+
f"Column Pair Trends: **{fmt(props.get('Column Pair Trends'))}**. "
|
| 143 |
+
"All scores 0–1 (fairness gap lower = better). Ask the agent above to explain any metric."
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# Fairness detail
|
| 147 |
+
with st.expander("Fairness detail — false-positive rate by group (fairlearn)"):
|
| 148 |
+
fpr_by = fair.get("fpr_by") or {}
|
| 149 |
+
if fpr_by:
|
| 150 |
+
cols = st.columns(len(fpr_by))
|
| 151 |
+
for col, (attr, groups) in zip(cols, fpr_by.items()):
|
| 152 |
+
with col:
|
| 153 |
+
st.caption(f"FPR by {attr}")
|
| 154 |
+
st.bar_chart(pd.DataFrame({"FPR": groups}), height=180)
|
| 155 |
+
st.caption("Lower and more equal bars = fairer. Model trained on synthetic, tested on real.")
|
| 156 |
+
else:
|
| 157 |
+
st.info("Fairness could not be computed for this run.")
|
| 158 |
+
|
| 159 |
+
# Synthetic preview + download
|
| 160 |
+
syn = result["synthetic"]
|
| 161 |
+
with st.expander(f"Synthetic sample — {len(syn):,} rows"):
|
| 162 |
+
st.dataframe(syn.head(20), use_container_width=True)
|
| 163 |
+
st.download_button("⬇️ Download synthetic CSV", data=syn.to_csv(index=False).encode("utf-8"),
|
| 164 |
+
file_name="memisis_synthetic.csv", mime="text/csv")
|
pipeline/agent.py
CHANGED
|
@@ -1,16 +1,14 @@
|
|
| 1 |
-
"""Chat-driven synthetic-data agent (
|
| 2 |
|
| 3 |
Routes a natural-language message to an action:
|
| 4 |
-
- "generate":
|
| 5 |
-
- "answer":
|
| 6 |
"""
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
from . import llm
|
| 10 |
-
from .generate import SYNTHESIZERS
|
| 11 |
|
| 12 |
-
|
| 13 |
-
DEFAULTS = {"synthesizers": list(SYNTHESIZERS), "sample_rows": 1000, "train_rows": 2000, "epochs": 100}
|
| 14 |
|
| 15 |
DECISION_SCHEMA = {
|
| 16 |
"type": "object",
|
|
@@ -19,38 +17,30 @@ DECISION_SCHEMA = {
|
|
| 19 |
"reply": {"type": "string"},
|
| 20 |
"params": {
|
| 21 |
"type": "object",
|
| 22 |
-
"properties": {
|
| 23 |
-
"synthesizers": {"type": "array", "items": {"type": "string", "enum": SYNTHESIZERS}},
|
| 24 |
-
"sample_rows": {"type": "integer"},
|
| 25 |
-
"train_rows": {"type": "integer"},
|
| 26 |
-
"epochs": {"type": "integer"},
|
| 27 |
-
},
|
| 28 |
},
|
| 29 |
},
|
| 30 |
"required": ["action", "reply"],
|
| 31 |
}
|
| 32 |
|
| 33 |
-
_SYSTEM =
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
Decide the user's intent:
|
| 38 |
-
- If they want to CREATE / GENERATE / MAKE synthetic data (or re-run with different
|
| 39 |
-
set action="generate" and fill
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
what you're about to generate in one friendly sentence.
|
| 44 |
-
- Otherwise set action="answer" and put a helpful, accurate answer in `reply`. Use the metric
|
| 45 |
-
definitions and the current RESULTS when the question is about the data or scores. You may also
|
| 46 |
-
answer general questions about synthetic data, SDV, or these metrics.
|
| 47 |
|
| 48 |
Never invent metric numbers; use only those provided. Be concise."""
|
| 49 |
|
| 50 |
|
| 51 |
def decide(user_message: str, results: dict | None = None, history: list[dict] | None = None) -> dict:
|
| 52 |
"""Return {action, reply, params?}. `results` is the current run's metrics (may be empty)."""
|
| 53 |
-
context = llm._summarize(results
|
| 54 |
messages = [
|
| 55 |
{"role": "system", "content": _SYSTEM},
|
| 56 |
{"role": "system", "content": f"METRIC DEFINITIONS:\n{llm.METRIC_GLOSSARY}\n\nCURRENT RESULTS:\n{context}"},
|
|
@@ -64,11 +54,6 @@ def decide(user_message: str, results: dict | None = None, history: list[dict] |
|
|
| 64 |
|
| 65 |
if decision.get("action") == "generate":
|
| 66 |
params = decision.get("params") or {}
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
if isinstance(params.get(k), int) and params[k] > 0:
|
| 70 |
-
merged[k] = params[k]
|
| 71 |
-
syn = [s for s in (params.get("synthesizers") or []) if s in SYNTHESIZERS]
|
| 72 |
-
merged["synthesizers"] = syn or DEFAULTS["synthesizers"]
|
| 73 |
-
decision["params"] = merged
|
| 74 |
return decision
|
|
|
|
| 1 |
+
"""Chat-driven synthetic-data agent (open SDV-Agent-style copilot, tool-calling orchestrator).
|
| 2 |
|
| 3 |
Routes a natural-language message to an action:
|
| 4 |
+
- "generate": create synthetic data with DataDesigner -> extract num_records
|
| 5 |
+
- "answer": reply in natural language (grounded in results/definitions)
|
| 6 |
"""
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
from . import llm
|
|
|
|
| 10 |
|
| 11 |
+
DEFAULTS = {"num_records": 1000}
|
|
|
|
| 12 |
|
| 13 |
DECISION_SCHEMA = {
|
| 14 |
"type": "object",
|
|
|
|
| 17 |
"reply": {"type": "string"},
|
| 18 |
"params": {
|
| 19 |
"type": "object",
|
| 20 |
+
"properties": {"num_records": {"type": "integer"}},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
},
|
| 22 |
},
|
| 23 |
"required": ["action", "reply"],
|
| 24 |
}
|
| 25 |
|
| 26 |
+
_SYSTEM = """You are Memisis Agent, a copilot for creating and evaluating synthetic tabular data.
|
| 27 |
+
Generation is done with NVIDIA NeMo DataDesigner (statistical samplers fit to the real data);
|
| 28 |
+
evaluation uses SDMetrics (fidelity, privacy, ML efficacy) and fairlearn (fairness) as tools.
|
| 29 |
+
The dataset is OpenML 45040 (~11k rows, health demographics, target 'Diagnosis').
|
| 30 |
|
| 31 |
Decide the user's intent:
|
| 32 |
+
- If they want to CREATE / GENERATE / MAKE synthetic data (or re-run with a different size),
|
| 33 |
+
set action="generate" and fill params.num_records from their request (default 1000). In `reply`,
|
| 34 |
+
confirm what you're generating in one friendly sentence.
|
| 35 |
+
- Otherwise set action="answer" and put a helpful, accurate answer in `reply`, using the metric
|
| 36 |
+
definitions and current RESULTS. You may also answer general questions about synthetic data.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
Never invent metric numbers; use only those provided. Be concise."""
|
| 39 |
|
| 40 |
|
| 41 |
def decide(user_message: str, results: dict | None = None, history: list[dict] | None = None) -> dict:
|
| 42 |
"""Return {action, reply, params?}. `results` is the current run's metrics (may be empty)."""
|
| 43 |
+
context = llm._summarize({"DataDesigner": results} if results else {})
|
| 44 |
messages = [
|
| 45 |
{"role": "system", "content": _SYSTEM},
|
| 46 |
{"role": "system", "content": f"METRIC DEFINITIONS:\n{llm.METRIC_GLOSSARY}\n\nCURRENT RESULTS:\n{context}"},
|
|
|
|
| 54 |
|
| 55 |
if decision.get("action") == "generate":
|
| 56 |
params = decision.get("params") or {}
|
| 57 |
+
n = params.get("num_records")
|
| 58 |
+
decision["params"] = {"num_records": n if isinstance(n, int) and n > 0 else DEFAULTS["num_records"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
return decision
|
pipeline/data.py
CHANGED
|
@@ -1,10 +1,9 @@
|
|
| 1 |
-
"""Load the OpenML benchmark dataset
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
from pathlib import Path
|
| 5 |
|
| 6 |
import pandas as pd
|
| 7 |
-
from sdv.metadata import SingleTableMetadata
|
| 8 |
|
| 9 |
DATA_ID = 45040 # OpenML: schizophrenia vs affective disorder + demographics
|
| 10 |
CACHE_DIR = Path(__file__).resolve().parent.parent / "data"
|
|
@@ -22,10 +21,3 @@ def load_real(data_id: int = DATA_ID, use_cache: bool = True) -> pd.DataFrame:
|
|
| 22 |
cache.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
frame.to_csv(cache, index=False)
|
| 24 |
return frame
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def build_metadata(df: pd.DataFrame) -> SingleTableMetadata:
|
| 28 |
-
"""Auto-detect SDV metadata (column types) from the DataFrame."""
|
| 29 |
-
metadata = SingleTableMetadata()
|
| 30 |
-
metadata.detect_from_dataframe(df)
|
| 31 |
-
return metadata
|
|
|
|
| 1 |
+
"""Load the OpenML benchmark dataset."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
from pathlib import Path
|
| 5 |
|
| 6 |
import pandas as pd
|
|
|
|
| 7 |
|
| 8 |
DATA_ID = 45040 # OpenML: schizophrenia vs affective disorder + demographics
|
| 9 |
CACHE_DIR = Path(__file__).resolve().parent.parent / "data"
|
|
|
|
| 21 |
cache.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
frame.to_csv(cache, index=False)
|
| 23 |
return frame
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pipeline/evaluate.py
CHANGED
|
@@ -1,31 +1,34 @@
|
|
| 1 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
from typing import Optional
|
| 5 |
|
| 6 |
import pandas as pd
|
| 7 |
-
from
|
| 8 |
-
from sdv.metadata import SingleTableMetadata
|
| 9 |
from sdmetrics.single_table import BinaryLogisticRegression, NewRowSynthesis
|
| 10 |
|
| 11 |
-
|
|
|
|
| 12 |
DEFAULT_TARGET = "Diagnosis"
|
| 13 |
|
| 14 |
|
| 15 |
-
def quality(real: pd.DataFrame, synthetic: pd.DataFrame, metadata:
|
| 16 |
"""SDMetrics Quality Report: overall + Column Shapes + Column Pair Trends (0..1, higher better)."""
|
| 17 |
-
report =
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
return {"overall_score": float(report.get_score()), "properties":
|
| 21 |
|
| 22 |
|
| 23 |
def privacy_new_row(real, synthetic, metadata, sample: int = 2000) -> Optional[float]:
|
| 24 |
-
"""SDMetrics NewRowSynthesis: fraction of synthetic rows that are genuinely new
|
| 25 |
-
(not copies of real rows). 0..1, higher = more private (no memorized real rows)."""
|
| 26 |
try:
|
| 27 |
return float(NewRowSynthesis.compute(
|
| 28 |
-
real_data=real, synthetic_data=synthetic, metadata=metadata
|
| 29 |
synthetic_sample_size=min(len(synthetic), sample),
|
| 30 |
))
|
| 31 |
except Exception:
|
|
@@ -33,21 +36,20 @@ def privacy_new_row(real, synthetic, metadata, sample: int = 2000) -> Optional[f
|
|
| 33 |
|
| 34 |
|
| 35 |
def ml_efficacy(real, synthetic, metadata, target: str = DEFAULT_TARGET) -> Optional[float]:
|
| 36 |
-
"""SDMetrics ML efficacy
|
| 37 |
-
test on REAL data. 0..1, higher = synthetic data is more useful for ML."""
|
| 38 |
if target not in real.columns or target not in synthetic.columns:
|
| 39 |
return None
|
| 40 |
try:
|
| 41 |
return float(BinaryLogisticRegression.compute(
|
| 42 |
-
test_data=real, train_data=synthetic, metadata=metadata
|
| 43 |
-
))
|
| 44 |
except Exception:
|
| 45 |
return None
|
| 46 |
|
| 47 |
|
| 48 |
def evaluate_all(real, synthetic, metadata, target: str = DEFAULT_TARGET) -> dict:
|
| 49 |
-
"""Full evaluation: fidelity (quality) + privacy
|
| 50 |
result = quality(real, synthetic, metadata)
|
| 51 |
result["new_row_synthesis"] = privacy_new_row(real, synthetic, metadata)
|
| 52 |
result["ml_efficacy"] = ml_efficacy(real, synthetic, metadata, target)
|
|
|
|
| 53 |
return result
|
|
|
|
| 1 |
+
"""Evaluators (tools) — SDMetrics fidelity + privacy + ML efficacy, and fairlearn fairness.
|
| 2 |
+
|
| 3 |
+
These wrap SDMetrics/fairlearn directly (no SDV dependency) so they can be called as tools on
|
| 4 |
+
any synthetic DataFrame, regardless of how it was generated.
|
| 5 |
+
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
from typing import Optional
|
| 9 |
|
| 10 |
import pandas as pd
|
| 11 |
+
from sdmetrics.reports.single_table import QualityReport
|
|
|
|
| 12 |
from sdmetrics.single_table import BinaryLogisticRegression, NewRowSynthesis
|
| 13 |
|
| 14 |
+
from .fairness import fairness as _fairness
|
| 15 |
+
|
| 16 |
DEFAULT_TARGET = "Diagnosis"
|
| 17 |
|
| 18 |
|
| 19 |
+
def quality(real: pd.DataFrame, synthetic: pd.DataFrame, metadata: dict) -> dict:
|
| 20 |
"""SDMetrics Quality Report: overall + Column Shapes + Column Pair Trends (0..1, higher better)."""
|
| 21 |
+
report = QualityReport()
|
| 22 |
+
report.generate(real, synthetic, metadata, verbose=False)
|
| 23 |
+
props = {str(r["Property"]): float(r["Score"]) for _, r in report.get_properties().iterrows()}
|
| 24 |
+
return {"overall_score": float(report.get_score()), "properties": props}
|
| 25 |
|
| 26 |
|
| 27 |
def privacy_new_row(real, synthetic, metadata, sample: int = 2000) -> Optional[float]:
|
| 28 |
+
"""SDMetrics NewRowSynthesis: fraction of synthetic rows that are genuinely new (higher=private)."""
|
|
|
|
| 29 |
try:
|
| 30 |
return float(NewRowSynthesis.compute(
|
| 31 |
+
real_data=real, synthetic_data=synthetic, metadata=metadata,
|
| 32 |
synthetic_sample_size=min(len(synthetic), sample),
|
| 33 |
))
|
| 34 |
except Exception:
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def ml_efficacy(real, synthetic, metadata, target: str = DEFAULT_TARGET) -> Optional[float]:
|
| 39 |
+
"""SDMetrics ML efficacy: train a classifier on synthetic, test on real (TSTR F1). Higher=useful."""
|
|
|
|
| 40 |
if target not in real.columns or target not in synthetic.columns:
|
| 41 |
return None
|
| 42 |
try:
|
| 43 |
return float(BinaryLogisticRegression.compute(
|
| 44 |
+
test_data=real, train_data=synthetic, metadata=metadata, target=target))
|
|
|
|
| 45 |
except Exception:
|
| 46 |
return None
|
| 47 |
|
| 48 |
|
| 49 |
def evaluate_all(real, synthetic, metadata, target: str = DEFAULT_TARGET) -> dict:
|
| 50 |
+
"""Full evaluation: fidelity (quality) + privacy + ML efficacy + fairness."""
|
| 51 |
result = quality(real, synthetic, metadata)
|
| 52 |
result["new_row_synthesis"] = privacy_new_row(real, synthetic, metadata)
|
| 53 |
result["ml_efficacy"] = ml_efficacy(real, synthetic, metadata, target)
|
| 54 |
+
result["fairness"] = _fairness(real, synthetic, target)
|
| 55 |
return result
|
pipeline/fairness.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fairness evaluation with fairlearn: train-on-synthetic, test-on-real, FPR by protected group."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from fairlearn.metrics import (
|
| 6 |
+
MetricFrame,
|
| 7 |
+
demographic_parity_difference,
|
| 8 |
+
false_positive_rate,
|
| 9 |
+
)
|
| 10 |
+
from sklearn.compose import ColumnTransformer
|
| 11 |
+
from sklearn.linear_model import LogisticRegression
|
| 12 |
+
from sklearn.pipeline import Pipeline
|
| 13 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 14 |
+
|
| 15 |
+
TARGET = "Diagnosis"
|
| 16 |
+
PROTECTED = ["Race", "Sex"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _model(X: pd.DataFrame) -> Pipeline:
|
| 20 |
+
cat = [c for c in X.columns if X[c].dtype == object]
|
| 21 |
+
num = [c for c in X.columns if c not in cat]
|
| 22 |
+
pre = ColumnTransformer([
|
| 23 |
+
("cat", OneHotEncoder(handle_unknown="ignore"), cat),
|
| 24 |
+
("num", StandardScaler(), num),
|
| 25 |
+
])
|
| 26 |
+
return Pipeline([("pre", pre), ("lr", LogisticRegression(max_iter=1000))])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def fairness(real, synthetic, target: str = TARGET, protected=PROTECTED) -> dict:
|
| 30 |
+
"""Train a classifier on SYNTHETIC data, test on REAL, and measure FPR disparities
|
| 31 |
+
across protected groups (fairlearn). Returns per-group FPR + parity gaps.
|
| 32 |
+
max_fpr_gap is the largest false-positive-rate difference across any protected group
|
| 33 |
+
(lower = fairer)."""
|
| 34 |
+
protected = [p for p in protected if p in real.columns and p in synthetic.columns]
|
| 35 |
+
if target not in real.columns or target not in synthetic.columns or not protected:
|
| 36 |
+
return {}
|
| 37 |
+
|
| 38 |
+
feats = [c for c in real.columns if c != target]
|
| 39 |
+
try:
|
| 40 |
+
model = _model(synthetic[feats])
|
| 41 |
+
model.fit(synthetic[feats], synthetic[target].astype(int))
|
| 42 |
+
y_true = real[target].astype(int)
|
| 43 |
+
y_pred = model.predict(real[feats])
|
| 44 |
+
except Exception:
|
| 45 |
+
return {}
|
| 46 |
+
|
| 47 |
+
out: dict = {"fpr_by": {}, "dp_difference": {}}
|
| 48 |
+
gaps = []
|
| 49 |
+
for attr in protected:
|
| 50 |
+
mf = MetricFrame(metrics=false_positive_rate, y_true=y_true, y_pred=y_pred,
|
| 51 |
+
sensitive_features=real[attr])
|
| 52 |
+
groups = {str(k): float(v) for k, v in mf.by_group.items()}
|
| 53 |
+
out["fpr_by"][attr] = groups
|
| 54 |
+
vals = [v for v in groups.values() if v == v] # drop NaN
|
| 55 |
+
if len(vals) >= 2:
|
| 56 |
+
gaps.append(max(vals) - min(vals))
|
| 57 |
+
try:
|
| 58 |
+
out["dp_difference"][attr] = float(
|
| 59 |
+
demographic_parity_difference(y_true, y_pred, sensitive_features=real[attr]))
|
| 60 |
+
except Exception:
|
| 61 |
+
out["dp_difference"][attr] = None
|
| 62 |
+
|
| 63 |
+
out["max_fpr_gap"] = float(max(gaps)) if gaps else None
|
| 64 |
+
return out
|
pipeline/generate.py
CHANGED
|
@@ -1,47 +1,43 @@
|
|
| 1 |
-
"""
|
| 2 |
-
from __future__ import annotations
|
| 3 |
|
| 4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
|
|
|
| 6 |
import pandas as pd
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
"""Fit one synthesizer on (a subsample of) the real data and sample synthetic rows."""
|
| 41 |
-
train = real
|
| 42 |
-
if train_rows and train_rows < len(real):
|
| 43 |
-
train = real.sample(train_rows, random_state=seed).reset_index(drop=True)
|
| 44 |
-
|
| 45 |
-
synth = make_synthesizer(name, metadata, epochs=epochs)
|
| 46 |
-
synth.fit(train)
|
| 47 |
-
return synth.sample(num_rows=sample_rows)
|
|
|
|
| 1 |
+
"""Synthesizer — NVIDIA NeMo DataDesigner.
|
|
|
|
| 2 |
|
| 3 |
+
Auto-configures a statistical sampler per column from the real data (CATEGORY samplers with the
|
| 4 |
+
real value distribution for categoricals, GAUSSIAN samplers for numerics) and generates synthetic
|
| 5 |
+
rows. Runs offline — statistical samplers need no LLM / API key.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
|
| 9 |
+
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
+
|
| 12 |
+
import data_designer.config as dd
|
| 13 |
+
from data_designer.interface import DataDesigner
|
| 14 |
+
|
| 15 |
+
from .metadata import is_categorical
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _build_config(real: pd.DataFrame) -> "dd.DataDesignerConfigBuilder":
|
| 19 |
+
b = dd.DataDesignerConfigBuilder()
|
| 20 |
+
for col in real.columns:
|
| 21 |
+
s = real[col].dropna()
|
| 22 |
+
if is_categorical(s):
|
| 23 |
+
vc = s.value_counts(normalize=True)
|
| 24 |
+
values = [v.item() if hasattr(v, "item") else v for v in vc.index.tolist()]
|
| 25 |
+
b.add_column(dd.SamplerColumnConfig(
|
| 26 |
+
name=col, sampler_type=dd.SamplerType.CATEGORY,
|
| 27 |
+
params=dd.CategorySamplerParams(values=values, weights=vc.values.tolist()),
|
| 28 |
+
))
|
| 29 |
+
else:
|
| 30 |
+
decimals = 0 if np.allclose(s, s.round()) else 2
|
| 31 |
+
b.add_column(dd.SamplerColumnConfig(
|
| 32 |
+
name=col, sampler_type=dd.SamplerType.GAUSSIAN,
|
| 33 |
+
params=dd.GaussianSamplerParams(
|
| 34 |
+
mean=float(s.mean()), stddev=float(s.std()), decimal_places=decimals),
|
| 35 |
+
))
|
| 36 |
+
return b
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate(real: pd.DataFrame, num_records: int = 1000) -> pd.DataFrame:
|
| 40 |
+
"""Generate `num_records` synthetic rows matching the real data's schema & marginals."""
|
| 41 |
+
designer = DataDesigner()
|
| 42 |
+
preview = designer.preview(config_builder=_build_config(real), num_records=int(num_records))
|
| 43 |
+
return preview.dataset[list(real.columns)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pipeline/llm.py
CHANGED
|
@@ -39,7 +39,10 @@ All scores are 0..1.
|
|
| 39 |
NEW (not exact copies of real training rows). ~1.0 means no memorized real rows.
|
| 40 |
- ML Efficacy / augmentation utility (higher better): F1 of a classifier trained on the
|
| 41 |
SYNTHETIC data and tested on the REAL data (train-on-synthetic, test-on-real). Higher means
|
| 42 |
-
the synthetic data preserves enough signal to be useful for downstream ML.
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
def _summarize(results: dict) -> str:
|
|
@@ -51,7 +54,8 @@ def _summarize(results: dict) -> str:
|
|
| 51 |
f"column_shapes={_fmt(p.get('Column Shapes'))}, "
|
| 52 |
f"column_pair_trends={_fmt(p.get('Column Pair Trends'))}, "
|
| 53 |
f"new_row_synthesis(privacy)={_fmt(r.get('new_row_synthesis'))}, "
|
| 54 |
-
f"ml_efficacy={_fmt(r.get('ml_efficacy'))}"
|
|
|
|
| 55 |
)
|
| 56 |
return "\n".join(lines) if lines else "No results available."
|
| 57 |
|
|
|
|
| 39 |
NEW (not exact copies of real training rows). ~1.0 means no memorized real rows.
|
| 40 |
- ML Efficacy / augmentation utility (higher better): F1 of a classifier trained on the
|
| 41 |
SYNTHETIC data and tested on the REAL data (train-on-synthetic, test-on-real). Higher means
|
| 42 |
+
the synthetic data preserves enough signal to be useful for downstream ML.
|
| 43 |
+
- Fairness max_fpr_gap (LOWER better): the largest false-positive-rate difference across
|
| 44 |
+
protected groups (Race, Sex), from a model trained on synthetic and tested on real. 0 = equal
|
| 45 |
+
error rates across groups. Higher means the synthetic data induces more biased predictions."""
|
| 46 |
|
| 47 |
|
| 48 |
def _summarize(results: dict) -> str:
|
|
|
|
| 54 |
f"column_shapes={_fmt(p.get('Column Shapes'))}, "
|
| 55 |
f"column_pair_trends={_fmt(p.get('Column Pair Trends'))}, "
|
| 56 |
f"new_row_synthesis(privacy)={_fmt(r.get('new_row_synthesis'))}, "
|
| 57 |
+
f"ml_efficacy={_fmt(r.get('ml_efficacy'))}, "
|
| 58 |
+
f"fairness_max_fpr_gap={_fmt((r.get('fairness') or {}).get('max_fpr_gap'))}"
|
| 59 |
)
|
| 60 |
return "\n".join(lines) if lines else "No results available."
|
| 61 |
|
pipeline/metadata.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build an SDMetrics metadata dict from a DataFrame (replaces SDV's SingleTableMetadata)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
# Columns with few distinct values are treated as categorical (matches the DataDesigner
|
| 7 |
+
# sampler config, which uses CATEGORY samplers for the same columns).
|
| 8 |
+
CATEGORICAL_MAX_UNIQUE = 12
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_categorical(s: pd.Series) -> bool:
|
| 12 |
+
return s.dtype == object or s.dropna().nunique() <= CATEGORICAL_MAX_UNIQUE
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def build_metadata(df: pd.DataFrame) -> dict:
|
| 16 |
+
"""SDMetrics single-table metadata: {'columns': {name: {'sdtype': 'categorical'|'numerical'}}}."""
|
| 17 |
+
return {
|
| 18 |
+
"columns": {
|
| 19 |
+
col: {"sdtype": "categorical" if is_categorical(df[col]) else "numerical"}
|
| 20 |
+
for col in df.columns
|
| 21 |
+
}
|
| 22 |
+
}
|
pipeline/run.py
DELETED
|
@@ -1,87 +0,0 @@
|
|
| 1 |
-
"""End-to-end: load OpenML data -> generate SDV variations -> evaluate with SDMetrics."""
|
| 2 |
-
from __future__ import annotations
|
| 3 |
-
|
| 4 |
-
import argparse
|
| 5 |
-
import json
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
import pandas as pd
|
| 9 |
-
|
| 10 |
-
from .data import build_metadata, load_real
|
| 11 |
-
from .evaluate import evaluate_all
|
| 12 |
-
from .generate import SYNTHESIZERS, generate
|
| 13 |
-
|
| 14 |
-
ROOT = Path(__file__).resolve().parent.parent
|
| 15 |
-
SYN_DIR = ROOT / "synthetic"
|
| 16 |
-
REP_DIR = ROOT / "reports"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def run(
|
| 20 |
-
models: list[str] | None = None,
|
| 21 |
-
sample_rows: int = 2000,
|
| 22 |
-
epochs: int = 100,
|
| 23 |
-
train_rows: int = 2000,
|
| 24 |
-
seed: int = 0,
|
| 25 |
-
progress=None,
|
| 26 |
-
):
|
| 27 |
-
"""Generate + evaluate each synthesizer. Returns (real_df, results dict).
|
| 28 |
-
|
| 29 |
-
`progress(name, i, total)` is an optional callback for UI progress.
|
| 30 |
-
"""
|
| 31 |
-
models = models or list(SYNTHESIZERS)
|
| 32 |
-
real = load_real()
|
| 33 |
-
metadata = build_metadata(real)
|
| 34 |
-
SYN_DIR.mkdir(exist_ok=True)
|
| 35 |
-
REP_DIR.mkdir(exist_ok=True)
|
| 36 |
-
|
| 37 |
-
results: dict[str, dict] = {}
|
| 38 |
-
for i, name in enumerate(models, 1):
|
| 39 |
-
if progress:
|
| 40 |
-
progress(name, i, len(models))
|
| 41 |
-
synth = generate(
|
| 42 |
-
name, real, metadata, sample_rows=sample_rows,
|
| 43 |
-
epochs=epochs, train_rows=train_rows, seed=seed,
|
| 44 |
-
)
|
| 45 |
-
synth.to_csv(SYN_DIR / f"synth_{name}.csv", index=False)
|
| 46 |
-
q = evaluate_all(real, synth, metadata)
|
| 47 |
-
q["synthetic"] = synth # kept in-memory for the UI; not serialized
|
| 48 |
-
results[name] = q
|
| 49 |
-
with open(REP_DIR / f"quality_{name}.json", "w") as f:
|
| 50 |
-
json.dump({k: v for k, v in q.items() if k != "synthetic"}, f, indent=2)
|
| 51 |
-
|
| 52 |
-
with open(REP_DIR / "comparison.json", "w") as f:
|
| 53 |
-
json.dump(
|
| 54 |
-
{n: {k: v for k, v in r.items() if k != "synthetic"} for n, r in results.items()},
|
| 55 |
-
f, indent=2,
|
| 56 |
-
)
|
| 57 |
-
return real, results
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _cli():
|
| 61 |
-
p = argparse.ArgumentParser(description="Generate + evaluate SDV synthetic data variations.")
|
| 62 |
-
p.add_argument("--models", nargs="*", default=list(SYNTHESIZERS), choices=SYNTHESIZERS)
|
| 63 |
-
p.add_argument("--sample-rows", type=int, default=2000)
|
| 64 |
-
p.add_argument("--epochs", type=int, default=100)
|
| 65 |
-
p.add_argument("--train-rows", type=int, default=2000)
|
| 66 |
-
p.add_argument("--seed", type=int, default=0)
|
| 67 |
-
args = p.parse_args()
|
| 68 |
-
|
| 69 |
-
real, results = run(
|
| 70 |
-
models=args.models, sample_rows=args.sample_rows,
|
| 71 |
-
epochs=args.epochs, train_rows=args.train_rows, seed=args.seed,
|
| 72 |
-
)
|
| 73 |
-
def _f(v):
|
| 74 |
-
return f"{v:.3f}" if isinstance(v, (int, float)) else " n/a"
|
| 75 |
-
|
| 76 |
-
print(f"\nReal rows: {len(real)} | columns: {len(real.columns)}\n")
|
| 77 |
-
print(f"{'Synthesizer':<16}{'Quality':>9}{'Shapes':>9}{'Pairs':>9}{'Privacy':>10}{'ML-Eff':>9}")
|
| 78 |
-
for name, r in results.items():
|
| 79 |
-
props = r["properties"]
|
| 80 |
-
print(f"{name:<16}{_f(r['overall_score']):>9}{_f(props.get('Column Shapes')):>9}"
|
| 81 |
-
f"{_f(props.get('Column Pair Trends')):>9}"
|
| 82 |
-
f"{_f(r.get('new_row_synthesis')):>10}{_f(r.get('ml_efficacy')):>9}")
|
| 83 |
-
print(f"\nSaved synthetic CSVs -> {SYN_DIR}\nSaved reports -> {REP_DIR}")
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
if __name__ == "__main__":
|
| 87 |
-
_cli()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
# Memisis
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
| 3 |
pandas==2.3.3
|
| 4 |
numpy==2.4.6
|
| 5 |
-
scikit-learn==1.9.0
|
| 6 |
-
sdv==1.34.1
|
| 7 |
-
sdmetrics==0.27.1
|
| 8 |
streamlit==1.58.0
|
| 9 |
plotly==6.8.0
|
| 10 |
requests==2.32.5
|
|
|
|
| 1 |
+
# Memisis Agent — DataDesigner generation + SDMetrics/fairlearn evaluation (no SDV, no torch).
|
| 2 |
+
data-designer==0.7.0
|
| 3 |
+
sdmetrics==0.27.1
|
| 4 |
+
fairlearn==0.13.0
|
| 5 |
+
scikit-learn==1.9.0
|
| 6 |
pandas==2.3.3
|
| 7 |
numpy==2.4.6
|
|
|
|
|
|
|
|
|
|
| 8 |
streamlit==1.58.0
|
| 9 |
plotly==6.8.0
|
| 10 |
requests==2.32.5
|