Spaces:
Sleeping
Sleeping
File size: 45,266 Bytes
6f12524 | 1 2 3 4 5 6 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 | """
Data Quality Agent Environment Implementation.
Simulates a realistic data-quality audit workflow that every ML engineer
faces before training: inspect a messy dataset, detect quality issues
(missing values, outliers, duplicates, label noise, type errors, class
imbalance, distribution drift), apply appropriate fixes, and submit a
quality report.
Grading dimensions (all 0-1, combined into final reward):
- Detection recall: did the agent find the injected issues? (0.25)
- Fix quality: were appropriate remediation methods chosen? (0.30)
- Quality improvement: delta between initial and final quality (0.25)
- Efficiency: fewer steps -> higher score (0.10)
- Report submitted: did the agent finish with SUBMIT_REPORT? (0.10)
"""
from __future__ import annotations
import math
import random
import statistics
from typing import Any, Dict, List, Optional, Set, Tuple
from uuid import uuid4
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State
try:
from ..models import DataQualityAgentAction, DataQualityAgentObservation
except ImportError:
from models import DataQualityAgentAction, DataQualityAgentObservation
# ---------------------------------------------------------------------------
# Helpers for synthetic data generation
# ---------------------------------------------------------------------------
COLUMN_DEFS = {
"age": {"type": "numeric", "mean": 35, "std": 12, "min": 18, "max": 80},
"income": {"type": "numeric", "mean": 55000, "std": 25000, "min": 15000, "max": 300000},
"credit_score": {"type": "numeric", "mean": 680, "std": 80, "min": 300, "max": 850},
"loan_amount": {"type": "numeric", "mean": 25000, "std": 15000, "min": 1000, "max": 100000},
"employment_years": {"type": "numeric", "mean": 8, "std": 5, "min": 0, "max": 40},
"num_dependents": {"type": "numeric", "mean": 1.5, "std": 1.2, "min": 0, "max": 8},
"education": {"type": "categorical", "values": ["high_school", "bachelors", "masters", "phd"]},
"employment_type": {"type": "categorical", "values": ["full_time", "part_time", "self_employed", "unemployed"]},
"region": {"type": "categorical", "values": ["north", "south", "east", "west", "central"]},
"approved": {"type": "label", "values": [0, 1]},
}
# Issue types the environment can inject
ISSUE_TYPES = [
"missing_values",
"outliers",
"duplicates",
"label_noise",
"type_mismatch",
"class_imbalance",
"distribution_drift",
]
# Mapping of issue -> valid fix commands
VALID_FIXES: Dict[str, List[str]] = {
"missing_values": ["FIX_MISSING"],
"outliers": ["FIX_OUTLIERS"],
"duplicates": ["REMOVE_DUPLICATES"],
"label_noise": ["FIX_LABELS"],
"type_mismatch": ["FIX_TYPES"],
"class_imbalance": ["REBALANCE"],
"distribution_drift": ["FIX_OUTLIERS", "FIX_DISTRIBUTION"],
}
# Mapping of issue -> valid check commands
VALID_CHECKS: Dict[str, List[str]] = {
"missing_values": ["CHECK_MISSING"],
"outliers": ["CHECK_OUTLIERS"],
"duplicates": ["CHECK_DUPLICATES"],
"label_noise": ["CHECK_LABELS"],
"type_mismatch": ["INSPECT", "DESCRIBE"],
"class_imbalance": ["CHECK_DISTRIBUTION", "CHECK_LABELS"],
"distribution_drift": ["CHECK_DISTRIBUTION", "CHECK_OUTLIERS"],
}
# ---------------------------------------------------------------------------
# Task / scenario definitions
# ---------------------------------------------------------------------------
TASKS: Dict[str, Dict[str, Any]] = {
"messy_csv": {
"description": (
"A customer-loan CSV exported from a legacy CRM system. "
"Common ETL issues: missing fields, duplicate rows, and type "
"mismatches from free-text entry."
),
"issues": ["missing_values", "duplicates", "type_mismatch"],
"num_rows": 2000,
"missing_rate": 0.12,
"duplicate_rate": 0.08,
"difficulty": "easy",
},
"noisy_labels": {
"description": (
"A crowd-sourced labelling dataset for loan-approval prediction. "
"Annotator disagreements created label noise, and minority class "
"is severely under-represented."
),
"issues": ["missing_values", "label_noise", "class_imbalance"],
"num_rows": 5000,
"missing_rate": 0.06,
"label_noise_rate": 0.15,
"imbalance_ratio": 0.12,
"difficulty": "medium",
},
"production_drift": {
"description": (
"Production inference data that has drifted significantly from "
"training distribution. Outliers from bot traffic, shifted "
"demographics, and corrupted pipeline fields."
),
"issues": [
"missing_values",
"outliers",
"duplicates",
"type_mismatch",
"distribution_drift",
],
"num_rows": 10000,
"missing_rate": 0.09,
"outlier_rate": 0.07,
"duplicate_rate": 0.05,
"difficulty": "hard",
},
}
DEFAULT_TASK = "messy_csv"
MAX_STEPS = 40
# ---------------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------------
class DataQualityAgentEnvironment(Environment):
"""
RL environment for data-quality assessment & remediation.
The agent receives a simulated messy dataset and must use inspection,
diagnosis, and fix commands to improve the dataset quality before
submitting a final report.
"""
SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self):
self._state = State(episode_id=str(uuid4()), step_count=0)
self._rng = random.Random(42)
# Episode state
self._task_name: str = DEFAULT_TASK
self._task_cfg: Dict[str, Any] = TASKS[DEFAULT_TASK]
self._num_rows: int = 2000
self._num_cols: int = len(COLUMN_DEFS)
self._columns: List[str] = list(COLUMN_DEFS.keys())
# Ground-truth injected issues
self._injected_issues: Set[str] = set()
# What the agent has detected
self._detected_issues: Set[str] = set()
# What the agent has fixed
self._fixed_issues: Set[str] = set()
# Commands the agent has used (for scoring check coverage)
self._checks_performed: Set[str] = set()
self._fixes_applied: List[Dict[str, str]] = []
# Whether agent submitted report
self._report_submitted: bool = False
# Quality scores (initial vs current)
self._initial_quality: float = 0.0
self._current_quality: float = 0.0
# Per-dimension quality
self._completeness: float = 1.0
self._consistency: float = 1.0
self._accuracy: float = 1.0
# Simulated dataset stats (we don't store actual data, just stats)
self._col_stats: Dict[str, Dict[str, Any]] = {}
self._missing_cols: Dict[str, float] = {}
self._outlier_cols: Dict[str, int] = {}
self._duplicate_count: int = 0
self._label_noise_count: int = 0
self._type_mismatch_cols: List[str] = []
self._class_distribution: Dict[str, float] = {}
self._drift_cols: List[str] = []
# -------------------------------------------------------------------
# Reset
# -------------------------------------------------------------------
def reset(self) -> DataQualityAgentObservation:
self._state = State(episode_id=str(uuid4()), step_count=0)
# Pick task from seed
task_names = list(TASKS.keys())
self._task_name = self._rng.choice(task_names)
self._task_cfg = TASKS[self._task_name]
self._num_rows = self._task_cfg["num_rows"]
# Reset episode tracking
self._injected_issues = set(self._task_cfg["issues"])
self._detected_issues = set()
self._fixed_issues = set()
self._checks_performed = set()
self._fixes_applied = []
self._report_submitted = False
# Generate synthetic column stats
self._generate_dataset()
# Compute initial quality
self._compute_quality()
self._initial_quality = self._current_quality
dashboard = self._render_dashboard(
f"DATA QUALITY AUDIT STARTED\n"
f"Dataset: {self._task_name}\n"
f"Description: {self._task_cfg['description']}\n"
f"Shape: {self._num_rows} rows x {self._num_cols} columns\n"
f"Columns: {', '.join(self._columns)}\n\n"
f"Your mission: inspect this dataset, find quality issues, "
f"fix them, then SUBMIT_REPORT.\n"
f"Available commands: DESCRIBE, INSPECT <col>, CHECK_MISSING, "
f"CHECK_DUPLICATES, CHECK_OUTLIERS <col>, CHECK_LABELS, "
f"CHECK_DISTRIBUTION <col>, CHECK_CORRELATION, "
f"FIX_MISSING <col> <method>, FIX_OUTLIERS <col> <method>, "
f"REMOVE_DUPLICATES, FIX_LABELS <method>, REBALANCE <method>, "
f"FIX_TYPES <col>, VALIDATE, SUBMIT_REPORT"
)
return DataQualityAgentObservation(
dashboard=dashboard,
step_number=0,
total_steps=MAX_STEPS,
dataset_name=self._task_name,
num_rows=self._num_rows,
num_columns=self._num_cols,
issues_detected=0,
issues_fixed=0,
total_issues=len(self._injected_issues),
quality_score=self._current_quality,
completeness=self._completeness,
consistency=self._consistency,
accuracy=self._accuracy,
phase="inspection",
task_name=self._task_name,
task_description=self._task_cfg["description"],
done=False,
reward=0.0,
)
# -------------------------------------------------------------------
# Step
# -------------------------------------------------------------------
def step(self, action: DataQualityAgentAction) -> DataQualityAgentObservation:
self._state.step_count += 1
step = self._state.step_count
# Parse semicolon-separated commands
raw_cmds = [c.strip() for c in action.message.split(";") if c.strip()]
outputs: List[str] = []
step_reward = 0.0
for cmd_str in raw_cmds:
result, reward = self._execute_command(cmd_str)
outputs.append(result)
step_reward += reward
done = self._report_submitted or step >= MAX_STEPS
# If episode ends, compute final graded reward
if done:
final_reward = self._compute_final_reward()
step_reward += final_reward
outputs.append(f"\n=== EPISODE COMPLETE === Final Score: {final_reward:.4f}")
# Clamp step reward to [0, 1]
step_reward = max(0.0, min(1.0, step_reward))
# Determine phase
if self._fixes_applied:
phase = "remediation"
elif self._report_submitted:
phase = "validation"
else:
phase = "inspection"
dashboard = self._render_dashboard("\n".join(outputs))
return DataQualityAgentObservation(
dashboard=dashboard,
step_number=step,
total_steps=MAX_STEPS,
dataset_name=self._task_name,
num_rows=self._num_rows,
num_columns=self._num_cols,
issues_detected=len(self._detected_issues),
issues_fixed=len(self._fixed_issues),
total_issues=len(self._injected_issues),
quality_score=self._current_quality,
completeness=self._completeness,
consistency=self._consistency,
accuracy=self._accuracy,
phase=phase,
task_name=self._task_name,
task_description=self._task_cfg["description"],
done=done,
reward=step_reward,
metadata={
"step": step,
"detected": list(self._detected_issues),
"fixed": list(self._fixed_issues),
},
)
@property
def state(self) -> State:
return self._state
# -------------------------------------------------------------------
# Command execution
# -------------------------------------------------------------------
def _execute_command(self, cmd_str: str) -> Tuple[str, float]:
"""Execute a single command. Returns (output_text, reward)."""
parts = cmd_str.strip().split()
if not parts:
return "Empty command. Try DESCRIBE to start.", 0.0
cmd = parts[0].upper()
args = parts[1:]
handlers = {
"DESCRIBE": self._cmd_describe,
"INSPECT": self._cmd_inspect,
"CHECK_MISSING": self._cmd_check_missing,
"CHECK_DUPLICATES": self._cmd_check_duplicates,
"CHECK_OUTLIERS": self._cmd_check_outliers,
"CHECK_LABELS": self._cmd_check_labels,
"CHECK_DISTRIBUTION": self._cmd_check_distribution,
"CHECK_CORRELATION": self._cmd_check_correlation,
"FIX_MISSING": self._cmd_fix_missing,
"FIX_OUTLIERS": self._cmd_fix_outliers,
"REMOVE_DUPLICATES": self._cmd_remove_duplicates,
"FIX_LABELS": self._cmd_fix_labels,
"REBALANCE": self._cmd_rebalance,
"FIX_TYPES": self._cmd_fix_types,
"FIX_DISTRIBUTION": self._cmd_fix_distribution,
"VALIDATE": self._cmd_validate,
"SUBMIT_REPORT": self._cmd_submit_report,
}
handler = handlers.get(cmd)
if handler is None:
return (
f"Unknown command: {cmd}. Available: {', '.join(sorted(handlers.keys()))}",
0.0,
)
return handler(args)
# -------------------------------------------------------------------
# Inspection commands
# -------------------------------------------------------------------
def _cmd_describe(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("DESCRIBE")
lines = [
f"DATASET OVERVIEW: {self._task_name}",
f"Shape: {self._num_rows} rows x {self._num_cols} columns",
f"",
f"{'Column':<20} {'Type':<12} {'Non-Null':<10} {'Unique':<8} {'Sample Values'}",
f"{'-'*75}",
]
for col in self._columns:
stats = self._col_stats[col]
dtype = stats["dtype"]
non_null_pct = (1.0 - self._missing_cols.get(col, 0.0)) * 100
unique = stats.get("unique", "N/A")
sample = stats.get("sample_values", "")
lines.append(
f"{col:<20} {dtype:<12} {non_null_pct:>6.1f}% {str(unique):<8} {sample}"
)
# Flag potential issues visible in overview
if self._type_mismatch_cols:
lines.append(f"\nWARNING: Possible type issues in: {', '.join(self._type_mismatch_cols)}")
self._detected_issues.add("type_mismatch")
reward = 0.02 # small reward for starting investigation
return "\n".join(lines), reward
def _cmd_inspect(self, args: List[str]) -> Tuple[str, float]:
if not args:
return "Usage: INSPECT <column_name>", 0.0
col = args[0].lower()
if col not in self._col_stats:
return f"Column '{col}' not found. Available: {', '.join(self._columns)}", 0.0
self._checks_performed.add(f"INSPECT_{col}")
stats = self._col_stats[col]
lines = [f"COLUMN INSPECTION: {col}", f"Type: {stats['dtype']}"]
missing_rate = self._missing_cols.get(col, 0.0)
lines.append(f"Missing: {missing_rate*100:.1f}% ({int(missing_rate * self._num_rows)} rows)")
if stats["dtype"] == "numeric":
lines.extend([
f"Mean: {stats['mean']:.2f}",
f"Std: {stats['std']:.2f}",
f"Min: {stats['min']:.2f}",
f"Max: {stats['max']:.2f}",
f"Median: {stats['median']:.2f}",
f"Skewness: {stats.get('skew', 0):.2f}",
])
if col in self._outlier_cols:
n_outliers = self._outlier_cols[col]
lines.append(f"ALERT: {n_outliers} potential outliers detected (>{stats['mean'] + 3*stats['std']:.1f})")
self._detected_issues.add("outliers")
else:
lines.append(f"Unique values: {stats.get('unique', 'N/A')}")
lines.append(f"Top values: {stats.get('value_counts', '')}")
if missing_rate > 0.01:
self._detected_issues.add("missing_values")
reward = 0.01
return "\n".join(lines), reward
def _cmd_check_missing(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_MISSING")
lines = ["MISSING VALUE ANALYSIS", f"{'-'*40}"]
any_missing = False
for col in self._columns:
rate = self._missing_cols.get(col, 0.0)
if rate > 0:
any_missing = True
count = int(rate * self._num_rows)
bar = "#" * int(rate * 30)
lines.append(f" {col:<20} {rate*100:>5.1f}% ({count:>5} rows) |{bar}")
if any_missing:
self._detected_issues.add("missing_values")
lines.append(f"\nRecommendation: Use FIX_MISSING <column> <method>")
lines.append(f" Methods: mean, median, mode, drop, forward_fill")
reward = 0.03
else:
lines.append(" No missing values detected.")
reward = 0.01
return "\n".join(lines), reward
def _cmd_check_duplicates(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_DUPLICATES")
lines = ["DUPLICATE ROW ANALYSIS", f"{'-'*40}"]
if self._duplicate_count > 0:
pct = self._duplicate_count / self._num_rows * 100
lines.append(f" Found {self._duplicate_count} duplicate rows ({pct:.1f}%)")
lines.append(f" Affected {self._duplicate_count * 2} total rows (original + dupes)")
lines.append(f"\n Recommendation: Use REMOVE_DUPLICATES")
self._detected_issues.add("duplicates")
reward = 0.03
else:
lines.append(" No duplicate rows detected.")
reward = 0.01
return "\n".join(lines), reward
def _cmd_check_outliers(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_OUTLIERS")
if not args:
# Check all numeric columns
lines = ["OUTLIER ANALYSIS (all numeric columns)", f"{'-'*40}"]
any_outliers = False
for col in self._columns:
if self._col_stats[col]["dtype"] == "numeric" and col in self._outlier_cols:
n = self._outlier_cols[col]
if n > 0:
any_outliers = True
pct = n / self._num_rows * 100
lines.append(f" {col:<20} {n:>5} outliers ({pct:.1f}%)")
if any_outliers:
self._detected_issues.add("outliers")
lines.append(f"\n Recommendation: Use FIX_OUTLIERS <column> <method>")
lines.append(f" Methods: clip, remove, winsorize")
else:
lines.append(" No significant outliers detected.")
reward = 0.03 if any_outliers else 0.01
else:
col = args[0].lower()
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
lines = [f"OUTLIER ANALYSIS: {col}", f"{'-'*40}"]
if col in self._outlier_cols and self._outlier_cols[col] > 0:
n = self._outlier_cols[col]
stats = self._col_stats[col]
lines.extend([
f" Outliers: {n} values",
f" IQR bounds: [{stats.get('q1', 0):.1f}, {stats.get('q3', 0):.1f}]",
f" Outlier range: >{stats['mean'] + 3*stats['std']:.1f} or <{stats['mean'] - 3*stats['std']:.1f}",
])
self._detected_issues.add("outliers")
reward = 0.02
else:
lines.append(" No outliers detected in this column.")
reward = 0.01
return "\n".join(lines), reward
def _cmd_check_labels(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_LABELS")
lines = ["LABEL QUALITY ANALYSIS", f"{'-'*40}"]
label_col = "approved"
dist = self._class_distribution
lines.append(f" Label column: {label_col}")
for cls, pct in dist.items():
count = int(pct * self._num_rows)
bar = "#" * int(pct * 40)
lines.append(f" Class {cls}: {pct*100:>5.1f}% ({count:>5} rows) |{bar}")
# Check imbalance
ratios = list(dist.values())
if ratios and min(ratios) < 0.2:
lines.append(f"\n WARNING: Severe class imbalance detected (minority: {min(ratios)*100:.1f}%)")
self._detected_issues.add("class_imbalance")
# Check label noise
if self._label_noise_count > 0:
noise_pct = self._label_noise_count / self._num_rows * 100
lines.append(f" WARNING: Estimated ~{noise_pct:.1f}% label noise ({self._label_noise_count} suspicious labels)")
lines.append(f" Cross-referencing feature correlations shows inconsistency.")
self._detected_issues.add("label_noise")
lines.append(f"\n Fix commands: FIX_LABELS <method>, REBALANCE <method>")
lines.append(f" Label methods: confidence_filter, majority_vote, relabel")
lines.append(f" Balance methods: oversample, undersample, smote")
reward = 0.03 if ("label_noise" in self._detected_issues or "class_imbalance" in self._detected_issues) else 0.01
return "\n".join(lines), reward
def _cmd_check_distribution(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_DISTRIBUTION")
if not args:
return "Usage: CHECK_DISTRIBUTION <column_name>", 0.0
col = args[0].lower()
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
stats = self._col_stats[col]
lines = [f"DISTRIBUTION ANALYSIS: {col}", f"{'-'*40}"]
if stats["dtype"] == "numeric":
lines.extend([
f" Mean: {stats['mean']:.2f}, Median: {stats['median']:.2f}",
f" Std: {stats['std']:.2f}",
f" Skewness: {stats.get('skew', 0):.2f}",
f" Kurtosis: {stats.get('kurtosis', 0):.2f}",
])
# Show histogram-like visualization
lines.append(f" Distribution:")
n_bins = 8
bin_width = (stats["max"] - stats["min"]) / n_bins
for i in range(n_bins):
lo = stats["min"] + i * bin_width
hi = lo + bin_width
# Approximate count using normal distribution
frac = 1.0 / n_bins # simplified
bar = "#" * max(1, int(frac * 40))
lines.append(f" [{lo:>8.1f}, {hi:>8.1f}) {bar}")
if col in self._drift_cols:
lines.append(f"\n ALERT: Distribution shift detected compared to training baseline!")
lines.append(f" KL-divergence: {self._rng.uniform(0.3, 0.8):.3f} (threshold: 0.1)")
self._detected_issues.add("distribution_drift")
else:
lines.append(f" Value counts: {stats.get('value_counts', '')}")
reward = 0.02 if col in self._drift_cols else 0.01
return "\n".join(lines), reward
def _cmd_check_correlation(self, args: List[str]) -> Tuple[str, float]:
self._checks_performed.add("CHECK_CORRELATION")
numeric_cols = [c for c in self._columns if self._col_stats[c]["dtype"] == "numeric"]
lines = ["CORRELATION MATRIX (top pairs)", f"{'-'*40}"]
pairs = []
for i, c1 in enumerate(numeric_cols):
for c2 in numeric_cols[i+1:]:
corr = self._rng.uniform(-0.3, 0.9)
pairs.append((c1, c2, corr))
pairs.sort(key=lambda x: abs(x[2]), reverse=True)
for c1, c2, corr in pairs[:8]:
bar = "#" * int(abs(corr) * 20)
lines.append(f" {c1:<18} <-> {c2:<18} r={corr:+.3f} {bar}")
if any(abs(p[2]) > 0.85 for p in pairs[:8]):
lines.append(f"\n WARNING: High multicollinearity detected. Consider feature selection.")
return "\n".join(lines), 0.01
# -------------------------------------------------------------------
# Fix commands
# -------------------------------------------------------------------
def _cmd_fix_missing(self, args: List[str]) -> Tuple[str, float]:
if len(args) < 2:
return "Usage: FIX_MISSING <column> <method>\nMethods: mean, median, mode, drop, forward_fill", 0.0
col = args[0].lower()
method = args[1].lower()
valid_methods = ["mean", "median", "mode", "drop", "forward_fill"]
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
if method not in valid_methods:
return f"Invalid method '{method}'. Use: {', '.join(valid_methods)}", 0.0
old_rate = self._missing_cols.get(col, 0.0)
if old_rate == 0:
return f"Column '{col}' has no missing values.", 0.0
# Evaluate fix quality
dtype = self._col_stats[col]["dtype"]
reward = 0.02
# Good method selection
if dtype == "numeric" and method in ["mean", "median", "forward_fill"]:
self._missing_cols[col] = 0.0
reward = 0.04
quality_msg = "Excellent choice for numeric data."
elif dtype == "categorical" and method in ["mode", "forward_fill"]:
self._missing_cols[col] = 0.0
reward = 0.04
quality_msg = "Excellent choice for categorical data."
elif method == "drop":
rows_dropped = int(old_rate * self._num_rows)
self._num_rows -= rows_dropped
self._missing_cols[col] = 0.0
reward = 0.02 # dropping is less ideal
quality_msg = f"Dropped {rows_dropped} rows. Data loss may affect model performance."
else:
self._missing_cols[col] = old_rate * 0.3 # partial fix
reward = 0.02
quality_msg = f"Suboptimal method for {dtype} data. Partial fix applied."
self._fixes_applied.append({"type": "FIX_MISSING", "col": col, "method": method})
if "missing_values" in self._injected_issues:
# Check if all missing columns are now fixed
remaining = sum(1 for v in self._missing_cols.values() if v > 0.01)
if remaining == 0:
self._fixed_issues.add("missing_values")
self._compute_quality()
return (
f"FIX_MISSING {col} {method}: {quality_msg}\n"
f" Before: {old_rate*100:.1f}% missing -> After: {self._missing_cols.get(col, 0)*100:.1f}% missing\n"
f" Quality score: {self._current_quality:.3f}"
), reward
def _cmd_fix_outliers(self, args: List[str]) -> Tuple[str, float]:
if len(args) < 2:
return "Usage: FIX_OUTLIERS <column> <method>\nMethods: clip, remove, winsorize", 0.0
col = args[0].lower()
method = args[1].lower()
valid_methods = ["clip", "remove", "winsorize"]
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
if method not in valid_methods:
return f"Invalid method '{method}'. Use: {', '.join(valid_methods)}", 0.0
n_outliers = self._outlier_cols.get(col, 0)
if n_outliers == 0:
return f"No outliers in column '{col}'.", 0.0
reward = 0.03
if method == "clip":
self._outlier_cols[col] = 0
quality_msg = "Clipped to IQR bounds. Good for preserving data volume."
reward = 0.04
elif method == "winsorize":
self._outlier_cols[col] = 0
quality_msg = "Winsorized to 5th/95th percentile. Robust approach."
reward = 0.05
elif method == "remove":
self._outlier_cols[col] = 0
self._num_rows -= n_outliers
quality_msg = f"Removed {n_outliers} rows. Consider if data loss is acceptable."
reward = 0.03
self._fixes_applied.append({"type": "FIX_OUTLIERS", "col": col, "method": method})
remaining = sum(1 for v in self._outlier_cols.values() if v > 0)
if remaining == 0 and "outliers" in self._injected_issues:
self._fixed_issues.add("outliers")
if remaining == 0 and "distribution_drift" in self._injected_issues:
self._fixed_issues.add("distribution_drift")
self._compute_quality()
return (
f"FIX_OUTLIERS {col} {method}: {quality_msg}\n"
f" Outliers resolved: {n_outliers}\n"
f" Quality score: {self._current_quality:.3f}"
), reward
def _cmd_remove_duplicates(self, args: List[str]) -> Tuple[str, float]:
if self._duplicate_count == 0:
return "No duplicate rows found.", 0.0
removed = self._duplicate_count
self._num_rows -= removed
self._duplicate_count = 0
self._fixed_issues.add("duplicates")
self._fixes_applied.append({"type": "REMOVE_DUPLICATES", "col": "all", "method": "exact"})
self._compute_quality()
return (
f"REMOVE_DUPLICATES: Removed {removed} duplicate rows.\n"
f" Dataset now: {self._num_rows} rows\n"
f" Quality score: {self._current_quality:.3f}"
), 0.04
def _cmd_fix_labels(self, args: List[str]) -> Tuple[str, float]:
if not args:
return "Usage: FIX_LABELS <method>\nMethods: confidence_filter, majority_vote, relabel", 0.0
method = args[0].lower()
valid_methods = ["confidence_filter", "majority_vote", "relabel"]
if method not in valid_methods:
return f"Invalid method '{method}'. Use: {', '.join(valid_methods)}", 0.0
if self._label_noise_count == 0:
return "No label noise detected.", 0.0
old_noise = self._label_noise_count
if method == "confidence_filter":
self._label_noise_count = int(old_noise * 0.15)
quality_msg = "Filtered low-confidence labels using model ensemble. Best practice."
reward = 0.05
elif method == "majority_vote":
self._label_noise_count = int(old_noise * 0.25)
quality_msg = "Applied majority vote across annotators. Good approach."
reward = 0.04
elif method == "relabel":
self._label_noise_count = int(old_noise * 0.4)
quality_msg = "Re-labelled with single model. May propagate existing biases."
reward = 0.03
if self._label_noise_count < 5:
self._label_noise_count = 0
self._fixed_issues.add("label_noise")
self._fixes_applied.append({"type": "FIX_LABELS", "col": "approved", "method": method})
self._compute_quality()
return (
f"FIX_LABELS {method}: {quality_msg}\n"
f" Noisy labels: {old_noise} -> {self._label_noise_count}\n"
f" Quality score: {self._current_quality:.3f}"
), reward
def _cmd_rebalance(self, args: List[str]) -> Tuple[str, float]:
if not args:
return "Usage: REBALANCE <method>\nMethods: oversample, undersample, smote", 0.0
method = args[0].lower()
valid_methods = ["oversample", "undersample", "smote"]
if method not in valid_methods:
return f"Invalid method '{method}'. Use: {', '.join(valid_methods)}", 0.0
ratios = list(self._class_distribution.values())
if ratios and min(ratios) >= 0.3:
return "Classes are already balanced (minority >= 30%).", 0.0
if method == "smote":
self._class_distribution = {k: 0.5 for k in self._class_distribution}
quality_msg = "Applied SMOTE. Synthetic minority oversampling preserves decision boundary."
reward = 0.05
elif method == "oversample":
self._class_distribution = {k: 0.5 for k in self._class_distribution}
self._num_rows = int(self._num_rows * 1.3)
quality_msg = "Random oversampling applied. Risk of overfitting on minority class."
reward = 0.03
elif method == "undersample":
old_rows = self._num_rows
self._class_distribution = {k: 0.5 for k in self._class_distribution}
self._num_rows = int(self._num_rows * 0.6)
quality_msg = f"Undersampled majority class. Lost {old_rows - self._num_rows} rows."
reward = 0.03
self._fixed_issues.add("class_imbalance")
self._fixes_applied.append({"type": "REBALANCE", "col": "approved", "method": method})
self._compute_quality()
return (
f"REBALANCE {method}: {quality_msg}\n"
f" New class distribution: {self._class_distribution}\n"
f" Dataset size: {self._num_rows} rows\n"
f" Quality score: {self._current_quality:.3f}"
), reward
def _cmd_fix_types(self, args: List[str]) -> Tuple[str, float]:
if not args:
return "Usage: FIX_TYPES <column>", 0.0
col = args[0].lower()
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
if col not in self._type_mismatch_cols:
return f"No type issues detected in '{col}'.", 0.0
self._type_mismatch_cols.remove(col)
if not self._type_mismatch_cols:
self._fixed_issues.add("type_mismatch")
self._fixes_applied.append({"type": "FIX_TYPES", "col": col, "method": "cast"})
self._compute_quality()
return (
f"FIX_TYPES {col}: Coerced to correct type.\n"
f" Remaining type issues: {len(self._type_mismatch_cols)}\n"
f" Quality score: {self._current_quality:.3f}"
), 0.03
def _cmd_fix_distribution(self, args: List[str]) -> Tuple[str, float]:
if not args:
return "Usage: FIX_DISTRIBUTION <column>", 0.0
col = args[0].lower()
if col not in self._col_stats:
return f"Column '{col}' not found.", 0.0
if col in self._drift_cols:
self._drift_cols.remove(col)
if not self._drift_cols:
self._fixed_issues.add("distribution_drift")
self._fixes_applied.append({"type": "FIX_DISTRIBUTION", "col": col, "method": "normalize"})
self._compute_quality()
return (
f"FIX_DISTRIBUTION {col}: Re-normalized to training distribution.\n"
f" Quality score: {self._current_quality:.3f}"
), 0.04
else:
return f"No distribution drift detected in '{col}'.", 0.0
# -------------------------------------------------------------------
# Validation & reporting
# -------------------------------------------------------------------
def _cmd_validate(self, args: List[str]) -> Tuple[str, float]:
self._compute_quality()
lines = [
"DATA QUALITY VALIDATION REPORT",
f"{'='*50}",
f" Overall Quality Score: {self._current_quality:.3f}",
f" Completeness: {self._completeness:.3f}",
f" Consistency: {self._consistency:.3f}",
f" Accuracy: {self._accuracy:.3f}",
f"",
f" Issues detected: {len(self._detected_issues)}/{len(self._injected_issues)}",
f" Issues fixed: {len(self._fixed_issues)}/{len(self._injected_issues)}",
f" Fixes applied: {len(self._fixes_applied)}",
f"",
f" Detected: {', '.join(sorted(self._detected_issues)) or 'none'}",
f" Fixed: {', '.join(sorted(self._fixed_issues)) or 'none'}",
f"",
]
# Show remaining issues
unfixed = self._injected_issues - self._fixed_issues
if unfixed:
lines.append(f" REMAINING ISSUES: {', '.join(sorted(unfixed))}")
else:
lines.append(f" All issues resolved!")
lines.append(f"\n When ready, use SUBMIT_REPORT to finalize.")
return "\n".join(lines), 0.01
def _cmd_submit_report(self, args: List[str]) -> Tuple[str, float]:
self._report_submitted = True
return "REPORT SUBMITTED. Episode complete.", 0.0
# -------------------------------------------------------------------
# Internal helpers
# -------------------------------------------------------------------
def _generate_dataset(self) -> None:
"""Generate synthetic column stats and inject issues."""
cfg = self._task_cfg
self._missing_cols = {}
self._outlier_cols = {}
self._duplicate_count = 0
self._label_noise_count = 0
self._type_mismatch_cols = []
self._drift_cols = []
self._col_stats = {}
for col, cdef in COLUMN_DEFS.items():
if cdef["type"] == "numeric":
mean = cdef["mean"] + self._rng.gauss(0, cdef["std"] * 0.05)
std = cdef["std"] * self._rng.uniform(0.8, 1.2)
q1 = mean - 0.674 * std
q3 = mean + 0.674 * std
self._col_stats[col] = {
"dtype": "numeric",
"mean": mean,
"std": std,
"min": cdef["min"],
"max": cdef["max"],
"median": mean + self._rng.gauss(0, std * 0.05),
"q1": q1,
"q3": q3,
"skew": self._rng.uniform(-0.5, 0.5),
"kurtosis": self._rng.uniform(-0.3, 1.5),
"unique": min(self._num_rows, int(self._num_rows * 0.85)),
"sample_values": f"{mean:.0f}, {mean+std:.0f}, {mean-std:.0f}",
}
elif cdef["type"] in ("categorical", "label"):
vals = cdef["values"]
vc = {str(v): self._rng.uniform(0.1, 0.4) for v in vals}
total = sum(vc.values())
vc = {k: v / total for k, v in vc.items()}
self._col_stats[col] = {
"dtype": "categorical" if cdef["type"] == "categorical" else "binary",
"unique": len(vals),
"value_counts": ", ".join(f"{k}: {v*100:.0f}%" for k, v in vc.items()),
"sample_values": ", ".join(str(v) for v in vals[:3]),
}
if cdef["type"] == "label":
self._class_distribution = vc
# Inject issues based on task config
issues = cfg["issues"]
if "missing_values" in issues:
rate = cfg.get("missing_rate", 0.1)
n_missing_cols = self._rng.randint(2, 4)
cols_to_miss = self._rng.sample(self._columns, min(n_missing_cols, len(self._columns)))
for c in cols_to_miss:
self._missing_cols[c] = rate * self._rng.uniform(0.5, 1.5)
if "duplicates" in issues:
dup_rate = cfg.get("duplicate_rate", 0.05)
self._duplicate_count = int(self._num_rows * dup_rate)
if "outliers" in issues:
outlier_rate = cfg.get("outlier_rate", 0.05)
numeric_cols = [c for c in self._columns if self._col_stats[c]["dtype"] == "numeric"]
n_outlier_cols = self._rng.randint(1, 3)
for c in self._rng.sample(numeric_cols, min(n_outlier_cols, len(numeric_cols))):
self._outlier_cols[c] = int(self._num_rows * outlier_rate * self._rng.uniform(0.5, 1.5))
if "label_noise" in issues:
noise_rate = cfg.get("label_noise_rate", 0.1)
self._label_noise_count = int(self._num_rows * noise_rate)
if "class_imbalance" in issues:
imb = cfg.get("imbalance_ratio", 0.15)
self._class_distribution = {"0": 1.0 - imb, "1": imb}
if "type_mismatch" in issues:
n_type_cols = self._rng.randint(1, 2)
self._type_mismatch_cols = self._rng.sample(self._columns, min(n_type_cols, len(self._columns)))
if "distribution_drift" in issues:
numeric_cols = [c for c in self._columns if self._col_stats[c]["dtype"] == "numeric"]
n_drift = self._rng.randint(1, 3)
self._drift_cols = self._rng.sample(numeric_cols, min(n_drift, len(numeric_cols)))
def _compute_quality(self) -> None:
"""Compute current quality score based on remaining issues."""
# Completeness: based on missing values
if self._missing_cols:
avg_missing = sum(self._missing_cols.values()) / len(self._missing_cols)
self._completeness = max(0.0, 1.0 - avg_missing * 3)
else:
self._completeness = 1.0
# Consistency: based on duplicates, type mismatches
dup_penalty = (self._duplicate_count / max(1, self._num_rows)) * 5
type_penalty = len(self._type_mismatch_cols) * 0.1
self._consistency = max(0.0, 1.0 - dup_penalty - type_penalty)
# Accuracy: based on outliers, label noise, drift
outlier_penalty = sum(self._outlier_cols.values()) / max(1, self._num_rows) * 3
noise_penalty = self._label_noise_count / max(1, self._num_rows) * 3
drift_penalty = len(self._drift_cols) * 0.1
imb_penalty = 0.0
if self._class_distribution:
ratios = list(self._class_distribution.values())
if ratios and min(ratios) < 0.2:
imb_penalty = (0.2 - min(ratios)) * 2
self._accuracy = max(0.0, 1.0 - outlier_penalty - noise_penalty - drift_penalty - imb_penalty)
self._current_quality = (
self._completeness * 0.35
+ self._consistency * 0.30
+ self._accuracy * 0.35
)
self._current_quality = max(0.0, min(1.0, self._current_quality))
def _compute_final_reward(self) -> float:
"""Compute the final graded reward (0-1) for the episode."""
self._compute_quality()
# 1. Detection recall (0.25)
if self._injected_issues:
detection_score = len(self._detected_issues & self._injected_issues) / len(self._injected_issues)
else:
detection_score = 1.0
# 2. Fix quality (0.30)
if self._injected_issues:
fix_score = len(self._fixed_issues & self._injected_issues) / len(self._injected_issues)
else:
fix_score = 1.0
# Bonus for good method choices
good_fixes = 0
for fix in self._fixes_applied:
if fix["type"] == "FIX_MISSING" and fix["method"] in ["median", "mean", "forward_fill"]:
good_fixes += 1
elif fix["type"] == "FIX_OUTLIERS" and fix["method"] in ["winsorize", "clip"]:
good_fixes += 1
elif fix["type"] == "FIX_LABELS" and fix["method"] == "confidence_filter":
good_fixes += 1
elif fix["type"] == "REBALANCE" and fix["method"] == "smote":
good_fixes += 1
elif fix["type"] in ["REMOVE_DUPLICATES", "FIX_TYPES", "FIX_DISTRIBUTION"]:
good_fixes += 1
method_bonus = min(0.1, good_fixes * 0.02) if self._fixes_applied else 0.0
fix_score = min(1.0, fix_score + method_bonus)
# 3. Quality improvement (0.25)
improvement = self._current_quality - self._initial_quality
quality_delta_score = min(1.0, max(0.0, improvement / max(0.01, 1.0 - self._initial_quality)))
# 4. Efficiency (0.10)
steps = self._state.step_count
efficiency_score = max(0.0, 1.0 - (steps / MAX_STEPS) * 0.6)
# 5. Report submitted (0.10)
report_score = 1.0 if self._report_submitted else 0.0
# Weighted sum
final = (
detection_score * 0.25
+ fix_score * 0.30
+ quality_delta_score * 0.25
+ efficiency_score * 0.10
+ report_score * 0.10
)
return max(0.0, min(1.0, final))
def _render_dashboard(self, content: str) -> str:
"""Wrap command output in a dashboard frame."""
sep = "=" * 60
return (
f"{sep}\n"
f"DATA QUALITY AGENT | Step {self._state.step_count}/{MAX_STEPS} "
f"| Quality: {self._current_quality:.3f} "
f"| Issues: {len(self._detected_issues)} detected, {len(self._fixed_issues)} fixed\n"
f"{sep}\n\n"
f"{content}\n"
)
|