The user wants a "feature quality scorecard" that measures three specific dimensions:
- Coverage: How much of the dataset has the feature? (Missing values)
- Data Freshness: How up-to-date is the feature data? (Recency)
- Predictive Power: How useful is the feature for the target variable? (Correlation/Importance)
Target Audience: Data Scientists, Machine Learning Engineers, Data Analysts.
Goal: Create a structured, actionable tool (a scorecard) to evaluate feature quality.
Step 1: Define the Metrics for each dimension.
-
Coverage:
- Metric: Non-null rate (or Missing Value %).
- Nuance: Distinct value count (cardinality) might be relevant but strictly "coverage" usually means availability. Let's stick to non-null rate for the core metric.
- Thresholds: 0-20% (Bad), 20-80% (Okay), >80% (Good), 100% (Ideal).
-
Data Freshness:
- Metric: Time since last update.
- Context: This depends heavily on the data source (streaming vs. batch). A generic scorecard needs to be adaptable.
- Metric Calculation:
Current_Time - Max(Timestamp_Of_Feature_Data).
- Thresholds: Real-time (<1hr), Daily (<24hr), Stale (>7 days).
-
Predictive Power:
- Metric:
- For Classification: Information Value (IV), AUC (ROC), or Mutual Information.
- For Regression: Correlation (Pearson/Spearman), RMSE contribution (Permutation Importance).
- Selection: Let's use Information Value (IV) or Predictive Power Score (PPS) as they are model-agnostic and standard. IV is great for binning/linear relationships; PPS is great for non-linear. Let's suggest IV or Mutual Information for simplicity, or Feature Importance from a baseline model.
- Thresholds: IV < 0.02 (Useless), 0.02-0.1 (Weak), 0.1-0.3 (Medium), >0.3 (Strong).
Step 2: Structure the Scorecard.
A good scorecard needs:
- Metric Name: What are we measuring?
- Definition: How is it calculated?
- Scoring Logic/Thresholds: What constitutes a "Pass", "Warn", or "Fail"?
- Weight: How important is this metric relative to others? (Optional but adds depth).
- Remediation: What to do if the score is low?
Step 3: Develop a Composite Score Formula.
How do we combine these?
- Score=w1×Cover
Step 4: Create the Implementation Guide (Python/SQL).
Users usually want code. I should provide a Python snippet using pandas to demonstrate how to calculate these scores programmatically.
Step 5: Refine the specific metrics.
-
Freshness is tricky in a static dataset. I need to clarify that this applies mostly to feature stores or production pipelines. If analyzing a static CSV, freshness is irrelevant (it's just old). I will assume this is for a Feature Store or MLOps context.
-
Predictive Power: I'll define a metric called "Univariate Predictive Power" to keep it simple (e.g., correlation for regression, AUC for classification).
Drafting the Content:
- Introduction: Define the scope.
- Dimension 1: Coverage (Availability)
- Focus: Null rates, zero-inflation.
- Dimension 2: Freshness (Timeliness)
- Focus: Latency, update frequency.
- Dimension 3: Predictive Power (Signal)
- Focus: Correlation, IV, Feature Importance.
- The Scoring System: A table with ranges.
- Python Implementation: A class or function that takes a dataframe and target column and outputs the report.
Refining the Python Code:
- Need
pandas and numpy.
- Need a way to handle freshness. Since I don't have a live DB, I'll mock a "last_updated" timestamp or assume a timestamp column exists.
- Need a way to handle predictive power. I'll use Absolute Correlation for regression and a simple univariate ROC AUC for classification (using sklearn).
Self-Correction/Review:
- Critique: Is "Predictive Power" just correlation?
- Correction: No, linear correlation misses non-linear patterns. I should suggest using Predictive Power Score (PPS) or Mutual Information as a better alternative, or simply standardizing on AUC/Correlation with a disclaimer. I'll stick to a generic "Importance Score" in the explanation and use Correlation/AUC in the code for demonstration purposes.
Final Output Structure:
- Executive Summary: What is the scorecard?
- Metric Definitions: Detailed breakdown of the three pillars.
- Scoring Thresholds: The "Traffic Light" system (Green/Yellow/Red).
- Composite Formula: How to aggregate into one number.
- Python Implementation: A copy-paste code block to generate the scorecard.
Let's build the Python code mentally:
class FeatureScorecard:
__init__(df, target)
calculate_coverage(): 1 - df.isnull().mean()
calculate_freshness(): Needs a reference time and a column time. (now - col.max()). Need to normalize this to a score (e.g., fresh=1, week old=0.5).
calculate_predictive_power(): df.corrwith(target).abs() (simple) or mutual_info_classif.
Okay, the plan is solid. I will structure the response clearly with headings and tables.
- Dimension 1: Coverage. Metric: Fill Rate. Formula: (Ntotal−Nmissing.
I will present this as a "MLOps Feature Store" style evaluation.
Let's write it out.
Structure Check:
- Concept Overview
- The Framework (The 3 Metrics)
- The Scorecard Grid (Thresholds)
- Code Example (Python)
Refining Freshness:
Freshness is hard to score universally. Is "1 day old" good? For stock prices, no. For credit scores, yes.
I will introduce a "Half-Life" parameter for freshness to make it customizable.
Refining Predictive Power:
I will recommend using Predictive Power Score (PPS) logic: use a Decision Tree to predict Target ~ Feature and calculate the score. Since that requires a library, I'll stick to standard libraries (pandas/sklearn) and use ROC-AUC (for classification) or R^2 (for regression) of a simple decision stump. It's more robust than correlation.
Let's go.
Plan:
- Introduction: Define the holistic approach.
- Metric 1: Coverage (Reliability): Fill rate logic.
- Metric 2: Freshness (Latency): Time-decay logic.
- Metric 3: Predictive Power (Signal): Univariate performance logic.
- The Scorecard Table: Red/Amber/Green thresholds.
- Implementation: Python code using
pandas and sklearn.
(Self-correction during drafting code): I won't implement full PPS from scratch in the code block as it's too verbose. I will use roc_auc_score for binary classification and r2_score for regression as proxies for predictive power, noting that more complex metrics exist.
Final check on the "Scorecard" aspect: It needs to output a "Grade" or "Status" (e.g., "Approved", "Review Needed", "Deprecated").
Let's execute.
Developing a Feature Quality Scorecard requires a standardized framework to evaluate the utility of data inputs for Machine Learning. Below is a comprehensive design for a scorecard that quantifies Coverage, Freshness, and Predictive Power, culminating in a single Feature Quality Score (FQS).
1. Metric Definitions & Logic
To create a scorecard, we first define how to measure each component on a normalized scale (0.0 to 1.0).
A. Coverage (Reliability)
Definition: The percentage of non-null, valid values within the feature.
- Why it matters: A feature with 99% coverage is generally implementation-ready. A feature with 50% coverage introduces bias or requires complex imputation.
- Formula: 1−(Total RowsNull Count+Invalid Count)
- Edge Case: A feature with 0% variance (e.g., all values are "5") has 100% coverage but 0% information. (This is handled by Predictive Power).
B. Data Freshness (Timeliness)
Definition: How recently the feature data was updated relative to the prediction time.
- Why it matters: Stale data degrades model performance in production (Training-Serving Skew).
- Formula: This is normalized based on a "Expected Update Frequency" (e.g., daily, hourly, realtime).
- Score Logic:
- Real-time: 1.0 (Updated < 1 hour ago)
- Fresh: 0.8 (Updated < 24 hours ago)
- Stale: 0.5 (Updated < 7 days ago)
- Dead: 0.0 (Updated > 30 days ago or static lookup table)
C. Predictive Power (Signal)
Definition: The univariate relationship between the feature and the target variable.
- Why it matters: This identifies if the feature actually helps the model predict the outcome.
- Formula:
- Classification: ROC-AUC score (normalized: ∣AUC−0.5∣×2) or Mutual Information.
- Regression: Absolute Pearson Correlation or R2 score.
- Constraint: The score should be 0 if the relationship is random, and 1 if the relationship is perfect.
2. The Scoring Rubric (Traffic Lights)
We assign a "Health Grade" to the raw metrics to make the scorecard interpretable for Data Scientists and Stakeholders.
| Metric | Critical (0.0 - 0.4) | Warning (0.4 - 0.7) | Healthy (0.7 - 1.0) |
|---|
| Coverage | < 60% filled. High imputation risk. | 60% - 90% filled. Manageable gaps. | > 90% filled. Ready for use. |
| Freshness | Stale (> 7 days old or static). | Lagging (1 - 7 days old). | Fresh (< 24 hours old). |
| Predictive | Noise (AUC ≈ 0.5 or Corr < 0.05). | Weak Signal (AUC 0.55-0.6). | Strong Signal (AUC > 0.6). |
3. The Composite Score Formula
We calculate the Feature Quality Score (FQS) using a weighted average.
- Weights can be adjusted based on business needs, but generally, Predictive Power is paramount.
FQS=(Wc×Coverage)+(W
Recommended Weights:
- Coverage (Wc): 0.2 (Hygiene factor)
- Freshness (Wf): 0.2 (Operational factor)
- Predictive (W): 0.6 (Utility factor)
4. Python Implementation
Here is a reusable Python class to generate this scorecard for a pandas DataFrame.
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score, mutual_info_classif
from datetime import datetime, timedelta
class FeatureQualityScorecard:
def __init__(self, df, target_col, freshness_date_col=None, current_time=None):
"""
df: pandas DataFrame containing features and target.
target_col: Name of the target variable column.
freshness_date_col: Column containing the timestamp of when the row was generated.
current_time: datetime object representing 'now' for freshness calculation.
"""
self.df = df
self.target = target_col
self.freshness_col = freshness_date_col
self.current_time = current_time if current_time else datetime.now()
self.scores = []
def _calculate_coverage(self, series):
"""Calculates percentage of non-null values."""
return series.notna().mean()
def _calculate_freshness(self, date_series):
"""
Calculates freshness score based on time decay.
Score = 1.0 if < 24h, decays to 0.0 over 30 days.
"""
if date_series is None:
return 1.0 # Default to max freshness if no date provided (static features)
# Ensure datetime format
date_series = pd.to_datetime(date_series)
# Calculate hours since last update
max_date = date_series.max()
hours_diff = (self.current_time - max_date).total_seconds() / 3600
# Simple Linear Decay Logic:
# 0-24h: 1.0
# 24h - 168h (1 week): 0.8
# > 720h (30 days): 0.0
if hours_diff <= 24:
return 1.0
elif hours_diff <= 168:
return 0.8
elif hours_diff <= 720:
return 0.5
else:
return 0.1
def _calculate_predictive_power(self, feature_series, target_series):
"""
Calculates predictive power using ROC-AUC for classification.
Handles categorical features using simple mapping for demonstration.
"""
# Drop NAs for calculation
valid_idx = feature_series.notna() & target_series.notna()
f = feature_series[valid_idx]
t = target_series[valid_idx]
if len(f) == 0: return 0.0
# Handle non-numeric features (simple factorize)
if f.dtype == 'object':
f = pd.factorize(f)[0]
# Check if target is binary (Classification)
if t.nunique() == 2:
try:
auc = roc_auc_score(t, f)
# Normalize AUC: 0.5 is random, 1.0 is perfect.
# We want 0.5 -> 0.0 score, 1.0 -> 1.0 score
return max(0, (auc - 0.5) * 2)
except:
return 0.0 # Constant feature or error
else:
# Regression: Use absolute correlation
return abs(f.corr(t))
def generate_report(self):
features = [c for c in self.df.columns if c != self.target and c != self.freshness_col]
for col in features:
cov = self._calculate_coverage(self.df[col])
fresh = 1.0
if self.freshness_col:
fresh = self._calculate_freshness(self.df[self.freshness_col])
pred = self._calculate_predictive_power(self.df[col], self.df[self.target])
# Weighted Score (20% Cov, 20% Fresh, 60% Pred)
final_score = (0.2 * cov) + (0.2 * fresh) + (0.6 * pred)
self.scores.append({
"Feature": col,
"Coverage": round(cov, 3),
"Freshness": round(fresh, 3),
"Predictive": round(pred, 3),
"FQS": round(final_score, 3)
})
return pd.DataFrame(self.scores).sort_values("FQS", ascending=False)
# --- Example Usage ---
# 1. Create Mock Data
data = {
'user_id': range(100),
'age': np.random.normal(40, 10, 100), # Good coverage, decent predictor
'income': np.random.normal(50000, 10000, 100), # Good coverage, weak predictor
'loyalty_pts': [np.nan] * 40 + list(np.random.randint(0, 100, 60)), # Bad coverage
'signup_date': [datetime.now() - timedelta(days=np.random.randint(0, 10)) for _ in range(100)],
'churn_label': np.random.randint(0, 2, 100) # Target
}
df = pd.DataFrame(data)
# 2. Run Scorecard
scorecard = FeatureQualityScorecard(
df,
target_col='churn_label',
freshness_date_col='signup_date'
)
report = scorecard.generate_report()
print(report)
Expected Output Interpretation
The output table allows you to quickly make decisions:
- High FQS (> 0.7): Green light for modeling.
- Low Coverage, High Predictive: Investigate Missing Not At Random (MNAR). If we can fix the collection of this feature, it could be a "Gold Mine" feature.
- High Coverage, Low Predictive: This is "Noise." Consider dropping it to reduce dimensionality.
- Low Freshness: This feature is likely a legacy data feed. Check if the pipeline is broken.
5. Operational Workflow
- Ingestion: When new data lands in the Data Lake/Feature Store, trigger the Scorecard script.
- Gating: If
FQS < 0.4, automatically flag the feature as "Quarantined" so Data Scientists cannot accidentally use it in training pipelines.
- Monitoring: Plot FQS over time. If
Predictive Power drifts down, the feature is suffering from Concept Drift. If Coverage drops, there is an upstream Data Engineering failure.