MLOPS_LIFECYCLE / src /components /data_validation.py
Sai-sathwik's picture
Upload 955 files
5e6746d verified
Raw History Blame Contribute Delete
6 kB
"""Data validation and drift detection component."""
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy import stats
from src.logger import get_logger
logger = get_logger(__name__)
class DataValidator:
"""Validates datasets for quality and detects data drift."""
def __init__(self, drift_threshold: float = 0.05):
self.drift_threshold = drift_threshold
def validate(self, df: pd.DataFrame) -> Dict:
"""Run comprehensive data validation checks."""
logger.info("Running data validation...")
issues = []
warnings = []
passed_checks = []
# Check 1: Non-empty dataset
if len(df) == 0:
issues.append("Dataset is empty")
else:
passed_checks.append("Dataset is non-empty")
# Check 2: Missing values
missing_pct = (df.isnull().sum() / len(df) * 100).round(2)
high_missing = missing_pct[missing_pct > 50].to_dict()
if high_missing:
for col, pct in high_missing.items():
warnings.append(f"Column '{col}' has {pct:.1f}% missing values")
else:
passed_checks.append("No columns with >50% missing values")
# Check 3: Duplicate rows
dup_count = df.duplicated().sum()
dup_pct = (dup_count / len(df) * 100) if len(df) > 0 else 0.0
if dup_pct > 10:
warnings.append(f"Dataset has {dup_count} duplicate rows ({dup_pct:.1f}%)")
else:
passed_checks.append(f"Duplicate rows within acceptable range ({dup_count})")
# Check 4: Constant columns
constant_cols = [col for col in df.columns if df[col].nunique() <= 1]
if constant_cols:
warnings.append(f"Constant (zero-variance) columns: {constant_cols}")
else:
passed_checks.append("No constant columns detected")
# Check 5: High cardinality
cat_cols = df.select_dtypes(include=["object"]).columns
high_card = [c for c in cat_cols if df[c].nunique() > 100]
if high_card:
warnings.append(f"High cardinality columns (>100 unique): {high_card}")
else:
passed_checks.append("Categorical cardinality within acceptable range")
# Check 6: Outliers in numeric columns
num_cols = df.select_dtypes(include=[np.number]).columns
outlier_cols = []
for col in num_cols:
z = np.abs(stats.zscore(df[col].dropna()))
if (z > 5).sum() > len(df) * 0.05:
outlier_cols.append(col)
if outlier_cols:
warnings.append(f"Extreme outliers detected in: {outlier_cols}")
else:
passed_checks.append("No extreme outliers detected")
status = "FAILED" if issues else ("WARNING" if warnings else "PASSED")
return {
"status": status,
"issues": issues,
"warnings": warnings,
"passed_checks": passed_checks,
"missing_per_column": missing_pct.to_dict(),
"duplicate_count": int(dup_count),
"constant_columns": constant_cols,
"high_cardinality_columns": high_card,
"outlier_columns": outlier_cols,
"total_rows": len(df),
"total_columns": len(df.columns),
}
def detect_drift(
self, reference_df: pd.DataFrame, current_df: pd.DataFrame
) -> Dict:
"""Detect data drift between reference and current datasets using KS test."""
logger.info("Running data drift detection...")
num_cols = reference_df.select_dtypes(include=[np.number]).columns
drift_results = {}
drifted_features = []
for col in num_cols:
if col not in current_df.columns:
continue
ref_data = reference_df[col].dropna().values
cur_data = current_df[col].dropna().values
if len(ref_data) < 10 or len(cur_data) < 10:
continue
ks_stat, p_value = stats.ks_2samp(ref_data, cur_data)
is_drifted = p_value < self.drift_threshold
drift_results[col] = {
"ks_statistic": round(float(ks_stat), 4),
"p_value": round(float(p_value), 4),
"is_drifted": is_drifted,
"ref_mean": round(float(ref_data.mean()), 4),
"cur_mean": round(float(cur_data.mean()), 4),
"ref_std": round(float(ref_data.std()), 4),
"cur_std": round(float(cur_data.std()), 4),
}
if is_drifted:
drifted_features.append(col)
drift_score = len(drifted_features) / max(len(drift_results), 1)
return {
"drift_score": round(drift_score, 4),
"drifted_features": drifted_features,
"total_features_checked": len(drift_results),
"feature_drift": drift_results,
"drift_detected": drift_score > 0.1,
}
def generate_schema(self, df: pd.DataFrame) -> Dict:
"""Generate data schema from DataFrame."""
schema = {}
for col in df.columns:
schema[col] = {
"dtype": str(df[col].dtype),
"nullable": bool(df[col].isnull().any()),
"unique_count": int(df[col].nunique()),
"min": df[col].min() if pd.api.types.is_numeric_dtype(df[col]) else None,
"max": df[col].max() if pd.api.types.is_numeric_dtype(df[col]) else None,
}
return schema
def validate_prediction_input(
self, input_data: Dict, expected_columns: List[str]
) -> Tuple[bool, List[str]]:
"""Validate prediction input against expected schema."""
errors = []
missing_cols = [c for c in expected_columns if c not in input_data]
if missing_cols:
errors.append(f"Missing required columns: {missing_cols}")
return len(errors) == 0, errors