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-regression-evaluation"Evaluates regression models using MSE, RMSE, MAE, MAPE, R-squared and other metrics for assessing predictive accuracy"
Independent GitHub snapshot · Automated classification · Original documentation governs
name: ds-regression-evaluation compatibility: opencode completeness: 95 content-types:
Comprehensive guide to regression evaluation in machine learning and data science workflows.
Regression Evaluation is a critical component of the machine learning workflow. This skill covers:
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from typing import Dict, Tuple
def basic_regression_evaluation(X: np.ndarray, y: np.ndarray) -> Dict[str, float]:
"""Train a linear regression model and compute core evaluation metrics."""
if X.shape[0] != y.shape[0]:
raise ValueError("X and y must have the same number of samples")
if X.ndim != 2 or y.ndim != 1:
raise ValueError("X must be 2D array and y must be 1D array")
test_ratio: float = 0.2
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_ratio, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
metrics: Dict[str, float] = {
'mse': float(mean_squared_error(y_test, y_pred))
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred)))
'mae': float(mean_absolute_error(y_test, y_pred))
'r2': float(r2_score(y_test, y_pred))
}
return metrics
import logging
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
class RegressionEvaluator:
"""Production-grade regression evaluation with comprehensive metrics and logging."""
def __init__(self, test_size: float = 0.2, random_state: int = 42) -> None:
self.test_size: float = test_size
self.random_state: int = random_state
self.model: Optional[RandomForestRegressor] = None
def evaluate(self, X: pd.DataFrame, y: pd.Series) -> Dict[str, Any]:
"""Evaluate regression performance on provided data."""
if X.empty or y.empty:
raise ValueError("Input data cannot be empty")
if X.shape[0] != y.shape[0]:
raise ValueError("X and y must have matching row counts")
logger.info("Starting regression evaluation pipeline")
X_train, X_test, y_train, y_test = self._split_data(X, y)
self.model = RandomForestRegressor(n_estimators=100, random_state=self.random_state)
self.model.fit(X_train, y_train)
y_pred = self.model.predict(X_test)
metrics: Dict[str, Any] = {
'mse': float(mean_squared_error(y_test, y_pred))
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred)))
'mae': float(mean_absolute_error(y_test, y_pred))
'r2': float(r2_score(y_test, y_pred))
'mape': float(np.mean(np.abs((y_test - y_pred) / y_test)) * 100)
}
logger.info(f"Evaluation complete. R2: {metrics['r2']:.4f}")
return metrics
def _split_data(self, X: pd.DataFrame, y: pd.Series) -> Tuple[pd.DataFrame, pd.DataFrame, pd.Series, pd.Series]:
"""Split data into training and testing sets."""
from sklearn.model_selection import train_test_split
return train_test_split(X, y, test_size=self.test_size, random_state=self.random_state)
BAD: Computing metrics on training data without validation, using hardcoded values, and ignoring dimension checks
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
def bad_evaluation(X: pd.DataFrame, y: pd.Series) -> float:
"""Bad practice: no test split, hardcoded parameters, missing validation."""
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
score = r2_score(y, y_pred)
return score # Returns overfit metric, no error handling, no type hints
GOOD: Proper train/test split with comprehensive metric reporting, explicit validation, and type hints
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from typing import Dict, Tuple
def good_evaluation(X: pd.DataFrame, y: pd.Series) -> Dict[str, float]:
"""Good practice: proper split, validation, type hints, and multiple metrics."""
if X.shape[0] != y.shape[0]:
raise ValueError("Dimension mismatch between features and targets")
if X.isnull().any().any() or y.isnull().any():
raise ValueError("Input data contains missing values")
test_ratio: float = 0.2
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_ratio, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
metrics: Dict[str, float] = {
'r2': float(r2_score(y_test, y_pred))
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred)))
'mae': float(mean_absolute_error(y_test, y_pred))
}
return metrics
| 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.