Sub topic 13
Detection: Log the Features the Model Actually Received
Assume you know basic Python and pandas, understand training and prediction, and have seen a model deployed behind an API or batch job. This chapter focuses on detection: recording the feature values that reach the model in production.
Why log model inputs?
A prediction request can change between the client, feature lookup, preprocessing code, and model. Logs from only the raw request cannot show what the model actually used. For example, a missing age value might become 0, a stale feature, or a training-time median before prediction.
Log an inference record containing:
- A timestamp and model version.
- A request or entity identifier.
- Feature names and values after production preprocessing.
- Missing-value indicators.
- The feature-definition or transformation version.
- The prediction and, when useful, the prediction probability.
The logged features should be comparable with the training features. If training used standardized values, log the standardized values or also preserve the raw values and the exact transformation version.
import hashlib
import json
from datetime import datetime, timezone
SENSITIVE_FEATURES = {"email", "phone_number"}
def stable_id(value: str) -> str:
"""Create a repeatable identifier without logging the original value."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
def make_inference_log(
entity_id: str,
features: dict,
prediction: int,
probability: float,
model_version: str,
transform_version: str,
) -> str:
safe_features = {
name: ("[REDACTED]" if name in SENSITIVE_FEATURES else value)
for name, value in features.items()
}
record = {
"event": "model_inference",
"timestamp": datetime.now(timezone.utc).isoformat(),
"entity_id": stable_id(entity_id),
"model_version": model_version,
"transform_version": transform_version,
"features": safe_features,
"missing_features": [
name for name, value in features.items() if value is None
],
"prediction": prediction,
"probability": probability,
}
return json.dumps(record, sort_keys=True)
print(make_inference_log(
entity_id="user-123",
features={"age": 40.0, "country_US": 1.0, "email": "[email protected]"},
prediction=1,
probability=0.82,
model_version="fraud-2026-11-01",
transform_version="features-7",
))Log safely and usefully
Feature logs can contain personal or confidential data. Apply data minimization:
- Log only features needed for debugging and monitoring.
- Hash identifiers when the original identifier is unnecessary.
- Redact direct identifiers and secrets.
- Restrict access and define a retention period.
- Sample high-volume traffic, but keep enough records for each model version and important segment.
- Record missingness separately. A value of
0is different from a missing value replaced with0.
Keep training reference data in the same feature representation. Then aggregate production logs by feature, model version, time window, and relevant segment. Compare those aggregates with training distributions using metrics such as the Population Stability Index (PSI) or the Kolmogorov-Smirnov (KS) statistic.
Interpreting an alert
A distribution difference is evidence for investigation, not proof that the model is broken. Check:
- Whether the alert began after a deployment or feature-source change.
- Whether one model version or all versions are affected.
- Whether missingness or category frequencies changed.
- Whether the same difference appears in a known-good shadow deployment.
- Whether predictions or business outcomes also degraded.
A confirmed logging or transformation bug usually calls for a rollback or pipeline fix. Retraining is appropriate only when production data is valid and the underlying population has genuinely changed.
Exercise
Why should a serving system log the transformed feature values instead of only the original request?
Show answer
The model predicts from transformed values. Logging them exposes differences caused by imputation, encoding, scaling, joins, or defaults, which raw-request logs cannot show.