executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
ds-metrics-and-kpis"Defines, selects, and monitors key performance indicators (KPIs), business metrics, and evaluation metrics for decision-making"
Independent GitHub snapshot · Automated classification · Original documentation governs
name: ds-metrics-and-kpis compatibility: opencode completeness: 95 content-types:
Comprehensive guide to metrics and kpis in machine learning and data science workflows.
Metrics and KPIs is a critical component of the machine learning workflow. This skill covers:
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, mean_squared_error, r2_score
def compute_basic_metrics(y_true: pd.Series, y_pred: pd.Series, task_type: str = "classification") -> dict:
"""Compute basic evaluation metrics for classification or regression tasks."""
if y_true is None or y_pred is None:
raise ValueError("y_true and y_pred cannot be None")
if len(y_true) != len(y_pred):
raise ValueError("y_true and y_pred must have the same length")
metrics = {}
if task_type == "classification":
metrics["accuracy"] = accuracy_score(y_true, y_pred)
metrics["precision"] = precision_score(y_true, y_pred, average="weighted", zero_division=0)
metrics["recall"] = recall_score(y_true, y_pred, average="weighted", zero_division=0)
metrics["f1"] = f1_score(y_true, y_pred, average="weighted", zero_division=0)
elif task_type == "regression":
metrics["mse"] = mean_squared_error(y_true, y_pred)
metrics["rmse"] = np.sqrt(metrics["mse"])
metrics["mae"] = np.mean(np.abs(y_true - y_pred))
metrics["r2"] = r2_score(y_true, y_pred)
else:
raise ValueError("task_type must be 'classification' or 'regression'")
metrics["sample_size"] = len(y_true)
return metrics
# Example usage
if __name__ == "__main__":
y_true = pd.Series([0, 1, 1, 0, 1, 0, 1, 1, 0, 0])
y_pred = pd.Series([0, 1, 0, 0, 1, 1, 1, 0, 0, 1])
results = compute_basic_metrics(y_true, y_pred, task_type="classification")
print("Classification Metrics:", results)
import logging
import pandas as pd
import numpy as np
from typing import Any, Dict, List
from sklearn.metrics import classification_report, confusion_matrix
logger = logging.getLogger(__name__)
class MetricsAndKPIs:
"""Production-grade metrics and KPIs tracker and calculator."""
def __init__(self, kpi_names: List[str] = None):
self.kpi_names = kpi_names or ["accuracy", "precision", "recall", "f1", "business_roi"]
self.history: List[Dict[str, Any]] = []
logger.info("Initialized MetricsAndKPIs tracker")
def _validate_inputs(self, y_true: pd.Series, y_pred: pd.Series) -> None:
if not isinstance(y_true, pd.Series) or not isinstance(y_pred, pd.Series):
raise TypeError("Inputs must be pandas Series")
if y_true.empty or y_pred.empty:
raise ValueError("Input Series cannot be empty")
if len(y_true) != len(y_pred):
raise ValueError("y_true and y_pred must have matching lengths")
def execute(self, data: pd.DataFrame, target_col: str = "y_true", pred_col: str = "y_pred") -> Dict[str, Any]:
"""Execute metrics calculation on provided DataFrame."""
try:
self._validate_inputs(data[target_col], data[pred_col])
y_true = data[target_col]
y_pred = data[pred_col]
report = classification_report(y_true, y_pred, output_dict=True, zero_division=0)
cm = confusion_matrix(y_true, y_pred).tolist()
f1 = report.get("macro avg", {}).get("f1-score", 0.0)
business_roi = f1 * 1000
result = {
"metrics": {
"accuracy": report["accuracy"]
"precision_macro": report["macro avg"]["precision"]
"recall_macro": report["macro avg"]["recall"]
"f1_macro": report["macro avg"]["f1-score"]
"confusion_matrix": cm
"business_roi": business_roi
}
"metadata": {
"rows_processed": len(data)
"kpi_names": self.kpi_names
"timestamp": pd.Timestamp.now().isoformat()
}
}
self.history.append(result)
logger.info(f"Metrics computed successfully for {len(data)} rows")
return result
except Exception as e:
logger.error(f"Metrics execution failed: {str(e)}")
raise RuntimeError(f"Failed to compute metrics: {e}") from e
| Pitfall | Problem | Solution | |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.