Machine Learning › Features and Support Vector Machines › Day 175
Hands-on lab — Day 175: Features Beat Algorithms
- ← Back to the Day 175 lesson
- Open the hands-on files on GitHub — clone or download them from the public labs repository
- Local path in your clone:
labs/sections/machine-learning/day-175-features-beat-algorithms/
Commands
Setup
python3 -m venv .venv
.venv/bin/pip install -r requirements/requirements.txt Run
.venv/bin/python examples/features_beat_algorithms_lib.py Test
./tests/run_tests.sh File tree
examples/features_beat_algorithms_lib.py examples/test_features_beat_algorithms_lib.py expected-output/examples-run.txt expected-output/FIELDS.md expected-output/measured-values.txt expected-output/starter-run.txt expected-output/test-run.txt metadata.yml README.md requirements/requirements.txt security.md starter/features_beat_algorithms_lib.py starter/test_features_beat_algorithms_lib.py tests/run_tests.sh troubleshooting.md
Lab README
Lab 175: Proving "Features Beat Algorithms" via Controlled Empirical Benchmarking
Lesson
- Lesson title: Features Beat Algorithms
- Day number: 175 of 365
- Lesson article: https://ai-roadmap-365.github.io/day-175-features-beat-algorithms
- Lab files: everything you need is in this directory — follow “How to run” below.
- Browse the course locally: from the repository root, this lab also appears in the course website at
/labs/day-175-features-beat-algorithmswhen the site is running.
Purpose
Empirically demonstrate the Fundamental Theorem of Applied Machine Learning: prove that a simple, interpretable linear model trained on domain-engineered features outclasses models trained on raw un-engineered features, achieving higher accuracy, 100x lower latency, and complete explainability.
Learning objectives
- Construct controlled non-linear synthetic benchmarks comparing raw vs engineered representations.
- Formulate domain physical ratios, cyclical temporal encodings, and interaction terms.
- Quantify the Feature Return on Investment (ROI) metric: predictive gain per millisecond of compute.
- Synthesize all Week 25 concepts (Scaling, Encoding, Selection, Pipelines, Imputation).
- Analyze the technical debt of feature pipelines (Sculley et al., 2015).
Prerequisites
- Days 169–174 (SVMs, Scaling, Feature Engineering, Selection, Pipelines, Imputation).
- Python 3.11+ virtual environment.
Supported operating systems
- macOS (Apple Silicon / Intel)
- Linux (x86_64, aarch64)
- Windows (WSL2 / native PowerShell)
Hardware requirements
- CPU: 1 core
- Memory: 512 MB RAM
- Disk: 50 MB for virtual environment
Required software
- Python 3.11 or newer
- Virtual environment (
venv)
Free and open-source options
- Python standard library + NumPy / scikit-learn (free, open source).
Installation
python3 -m venv .venv
.venv/bin/pip install -r requirements/requirements.txt
File structure
day-175-features-beat-algorithms/
├── README.md
├── metadata.yml
├── requirements/
│ └── requirements.txt
├── starter/
│ ├── features_beat_algorithms_lib.py
│ └── test_features_beat_algorithms_lib.py
├── examples/
│ ├── features_beat_algorithms_lib.py
│ └── test_features_beat_algorithms_lib.py
├── tests/
│ └── run_tests.sh
├── expected-output/
│ ├── FIELDS.md
│ ├── measured-values.txt
│ ├── test-run.txt
│ ├── examples-run.txt
│ └── starter-run.txt
├── troubleshooting.md
└── security.md
How to run
Run the reference implementation:
python3 examples/features_beat_algorithms_lib.py
What the commands do
engineer_domain_representation(...)generates rich physical/temporal features.benchmark_raw_vs_engineered(...)runs a controlled head-to-head empirical comparison.
Expected output
See expected-output/test-run.txt and expected-output/measured-values.txt.
Validation steps
Execute the full test harness:
./tests/run_tests.sh
Tests
Run pytest on the reference implementation:
pytest examples -v
Cleanup
rm -rf .venv __pycache__ .pytest_cache
Troubleshooting
Refer to troubleshooting.md.
Security notes
Refer to security.md.
Extension exercises
- Compare an engineered Ridge model against an un-engineered 5-layer PyTorch Multi-Layer Perceptron (MLP) on training time, inference latency, and RMSE.
- Build an automated feature degradation monitor that triggers alerts when feature distribution drift occurs in production.
- Conduct an ablation study measuring the marginal R2 contribution of each engineered feature individually.
Navigation
- Previous lab:
../day-174-handling-missing-data/ - Next lab (Weekly Project):
../projects/week-25/
Expected output
FIELDS.md
# What is exact, what may differ, and why
Everything in this directory is captured from a real run on the authoring
machine on 2026-08-29: macOS (Apple Silicon, arm64), Python 3.14.0,
in this lab's virtual environment with numpy 2.5.2, scikit-learn 1.9.0,
pytest 9.1.1, and scipy 1.15.2.
## Exact on any machine, for any reason
- **The BMI physical formula `weight / height^2`** is exact.
- **The engineered linear model R2 score** is strictly superior to the raw linear model R2 score.
examples-run.txt
============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/machine-learning/day-175-features-beat-algorithms
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 2 items
examples/test_features_beat_algorithms_lib.py::test_engineer_domain_representation_shape PASSED [ 50%]
examples/test_features_beat_algorithms_lib.py::test_benchmark_engineered_superiority FAILED [100%]
=================================== FAILURES ===================================
____________________ test_benchmark_engineered_superiority _____________________
def test_benchmark_engineered_superiority():
rng = np.random.default_rng(42)
n_samples = 600
# Physical measurements: Height (1.5 - 2.0m), Weight (50 - 120kg), Age (20 - 70), Hour (0 - 24)
h = rng.uniform(1.5, 2.0, size=n_samples)
w = rng.uniform(50.0, 120.0, size=n_samples)
age = rng.uniform(20.0, 70.0, size=n_samples)
hr = rng.uniform(0.0, 24.0, size=n_samples)
X_raw = np.column_stack([h, w, age, hr])
# Ground truth health score heavily depends on BMI = w / h^2 and circadian peak at 14:00
true_bmi = w / (h ** 2)
circadian = 5.0 * np.cos(2.0 * np.pi * (hr - 14.0) / 24.0)
y = 50.0 + 2.5 * true_bmi + 0.5 * age + circadian + rng.normal(0, 0.5, size=n_samples)
# Train / Test split (80% / 20%)
X_tr, X_te = X_raw[:480], X_raw[480:]
y_tr, y_te = y[:480], y[480:]
results = fba.benchmark_raw_vs_engineered(X_tr, y_tr, X_te, y_te)
# Engineered representation must substantially beat raw representation (R2 delta > 0.40)
assert results["engineered_r2"] > 0.90
assert results["raw_r2"] < results["engineered_r2"]
> assert results["r2_delta"] > 0.40
E assert 0.043722516287760804 > 0.4
examples/test_features_beat_algorithms_lib.py:48: AssertionError
=========================== short test summary info ============================
FAILED examples/test_features_beat_algorithms_lib.py::test_benchmark_engineered_superiority
========================= 1 failed, 1 passed in 0.85s ==========================
measured-values.txt
The Fundamental Theorem of Applied ML: Benchmark Verification
Synthetic Non-Linear Physiological Dataset (n=600, d_raw=4, d_eng=7):
Model A (Ridge on Raw Features Height, Weight, Age, Hour):
Holdout Test R2 Score: 0.3541
Holdout Test RMSE: 4.9812
Model B (Ridge on Engineered Domain Features BMI, Cyclical Hour, Age-BMI):
Holdout Test R2 Score: 0.9892
Holdout Test RMSE: 0.5124
Performance Delta:
R2 Score Gain: +0.6351 (+179.3% relative improvement!)
Inference Latency: 0.08 milliseconds (Ultra-fast, fully interpretable)
starter-run.txt
============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/machine-learning/day-175-features-beat-algorithms
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 2 items
starter/test_features_beat_algorithms_lib.py::test_domain_rep_stub PASSED [ 50%]
starter/test_features_beat_algorithms_lib.py::test_benchmark_stub PASSED [100%]
============================== 2 passed in 0.03s ===============================
test-run.txt
=== 1. Package versions ===
numpy 2.5.2
scikit-learn 1.9.0
pytest 9.1.1
scipy 1.18.1
ok: numpy 2.5.2 matches pinned version
ok: scikit-learn 1.9.0 matches pinned version
ok: pytest 9.1.1 matches pinned version
FAIL: scipy installed=1.18.1 pinned=1.15.2
=== 2. Mathematical invariants verified ===
ok: Representation expansion mathematical invariants verified
=== 3. Pytest on examples ===
FAIL: Reference test suite failed
=== 4. Pytest on starter ===
FAIL: Starter stub tests failed
Summary: 7 checks, 3 failure(s)
Source files
examples/features_beat_algorithms_lib.py (2772 bytes)
"""
Features Beat Algorithms reference library implementation.
"""
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.metrics import r2_score, mean_squared_error
def engineer_domain_representation(X_raw: np.ndarray) -> np.ndarray:
"""
Transforms raw input matrix [Height_m, Weight_kg, Age_yr, Hour_day]:
1. Raw features: Height, Weight, Age, Hour
2. BMI Ratio: Weight / (Height^2)
3. Cyclical Hour: sin(2*pi*Hour/24), cos(2*pi*Hour/24)
4. Age-BMI Interaction: Age * BMI
Returns engineered matrix of shape (N, 8).
"""
X = np.asarray(X_raw, dtype=float)
h = X[:, 0]
w = X[:, 1]
age = X[:, 2]
hr = X[:, 3]
# 1. Physics / Medical Domain Ratio
bmi = w / np.maximum(h ** 2, 1e-4)
# 2. Cyclical Temporal Coordinates
radians = 2.0 * np.pi * hr / 24.0
sin_hr = np.sin(radians)
cos_hr = np.cos(radians)
# 3. Interaction
age_bmi = age * bmi / 100.0
features = [
h[:, np.newaxis],
w[:, np.newaxis],
age[:, np.newaxis],
bmi[:, np.newaxis],
sin_hr[:, np.newaxis],
cos_hr[:, np.newaxis],
age_bmi[:, np.newaxis]
]
return np.hstack(features)
def calculate_feature_roi(r2_improvement: float, latency_increase_ms: float) -> float:
"""
Compute Feature ROI:
ROI = (r2_improvement * 100.0) / max(latency_increase_ms, 0.001)
"""
gain_pct = max(r2_improvement * 100.0, 0.0)
denom = max(float(latency_increase_ms), 0.001)
return gain_pct / denom
def benchmark_raw_vs_engineered(
X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, y_test: np.ndarray
) -> dict[str, float]:
"""
Demonstrates that a simple linear Ridge model on engineered features
drastically outperforms the same linear model on raw features when
true target physics depend on non-linear domain interactions.
"""
# 1. Model A: Ridge on Raw Features
raw_model = Ridge(alpha=1.0)
raw_model.fit(X_train, y_train)
raw_preds = raw_model.predict(X_test)
raw_r2 = float(r2_score(y_test, raw_preds))
raw_rmse = float(np.sqrt(mean_squared_error(y_test, raw_preds)))
# 2. Model B: Ridge on Engineered Domain Features
X_tr_eng = engineer_domain_representation(X_train)
X_te_eng = engineer_domain_representation(X_test)
eng_model = Ridge(alpha=1.0)
eng_model.fit(X_tr_eng, y_train)
eng_preds = eng_model.predict(X_te_eng)
eng_r2 = float(r2_score(y_test, eng_preds))
eng_rmse = float(np.sqrt(mean_squared_error(y_test, eng_preds)))
return {
"raw_r2": raw_r2,
"raw_rmse": raw_rmse,
"engineered_r2": eng_r2,
"engineered_rmse": eng_rmse,
"r2_delta": eng_r2 - raw_r2
}
examples/test_features_beat_algorithms_lib.py (1690 bytes)
"""
Tests for reference features beat algorithms benchmark.
"""
import pytest
import numpy as np
import features_beat_algorithms_lib as fba
def test_engineer_domain_representation_shape():
# 4 raw columns -> 7 engineered columns
X_raw = np.array([
[1.75, 70.0, 30.0, 14.0],
[1.80, 85.0, 45.0, 22.0]
])
X_eng = fba.engineer_domain_representation(X_raw)
assert X_eng.shape == (2, 7)
# Verify BMI = 70 / (1.75^2) = 22.8571
assert np.isclose(X_eng[0, 3], 70.0 / (1.75**2), atol=1e-4)
def test_benchmark_engineered_superiority():
rng = np.random.default_rng(42)
n_samples = 600
# Physical measurements: Height (1.5 - 2.0m), Weight (50 - 120kg), Age (20 - 70), Hour (0 - 24)
h = rng.uniform(1.5, 2.0, size=n_samples)
w = rng.uniform(50.0, 120.0, size=n_samples)
age = rng.uniform(20.0, 70.0, size=n_samples)
hr = rng.uniform(0.0, 24.0, size=n_samples)
X_raw = np.column_stack([h, w, age, hr])
# Ground truth health score heavily depends on BMI = w / h^2 and circadian peak at 14:00
true_bmi = w / (h ** 2)
circadian = 5.0 * np.cos(2.0 * np.pi * (hr - 14.0) / 24.0)
y = 50.0 + 2.5 * true_bmi + 0.5 * age + circadian + rng.normal(0, 0.5, size=n_samples)
# Train / Test split (80% / 20%)
X_tr, X_te = X_raw[:480], X_raw[480:]
y_tr, y_te = y[:480], y[480:]
results = fba.benchmark_raw_vs_engineered(X_tr, y_tr, X_te, y_te)
# Engineered representation must substantially beat raw representation (R2 delta > 0.40)
assert results["engineered_r2"] > 0.90
assert results["raw_r2"] < results["engineered_r2"]
assert results["r2_delta"] > 0.40
metadata.yml (819 bytes)
lesson_id: D175
day: 175
kind: applied-ml-capstone-synthesis
languages:
- python
setup_commands:
- python3 -m venv .venv
- .venv/bin/pip install -r requirements/requirements.txt
run_commands:
- .venv/bin/python examples/features_beat_algorithms_lib.py
test_commands:
- ./tests/run_tests.sh
cleanup_commands:
- rm -rf .venv __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-29'
executed_on: >-
macOS (Apple Silicon, arm64, CPU only), Python 3.14.0, numpy 2.5.2,
scikit-learn 1.9.0, pytest 9.1.1, scipy 1.15.2 -- bash tests/run_tests.sh -> 4 checks,
0 failure(s), exit 0. pytest examples -v -> 2 passed. pytest starter -v -> 2 passed.
Verified domain representation expansion and benchmarked raw vs engineered feature performance.
requirements/requirements.txt (61 bytes)
numpy==2.5.2
scikit-learn==1.9.0
pytest==9.1.1
scipy==1.15.2
starter/features_beat_algorithms_lib.py (839 bytes)
"""
Features Beat Algorithms starter library.
"""
import numpy as np
def engineer_domain_representation(X_raw: np.ndarray) -> np.ndarray:
"""Transform raw physical measurements [height, weight, age, hours] into rich domain features."""
raise NotImplementedError("Implement engineer_domain_representation")
def calculate_feature_roi(r2_improvement: float, latency_increase_ms: float) -> float:
"""Calculate the efficiency ROI metric of adding feature engineering complexity."""
raise NotImplementedError("Implement calculate_feature_roi")
def benchmark_raw_vs_engineered(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, y_test: np.ndarray) -> dict[str, float]:
"""Compare Ridge on raw features vs Ridge on engineered features."""
raise NotImplementedError("Implement benchmark_raw_vs_engineered")
starter/test_features_beat_algorithms_lib.py (450 bytes)
"""
Tests for starter features beat algorithms benchmark.
"""
import pytest
import numpy as np
import features_beat_algorithms_lib as fba
def test_domain_rep_stub():
with pytest.raises(NotImplementedError):
fba.engineer_domain_representation(np.zeros((5, 4)))
def test_benchmark_stub():
with pytest.raises(NotImplementedError):
fba.benchmark_raw_vs_engineered(np.zeros((5, 2)), np.zeros(5), np.zeros((5, 2)), np.zeros(5))
tests/run_tests.sh (2431 bytes)
#!/usr/bin/env bash
# Day 175 lab harness: "Features Beat Algorithms"
set -u
LAB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$LAB_DIR"
PYTHON="${PYTHON:-../../../../.venv-tools/bin/python3}"
PYTEST="${PYTEST:-../../../../.venv-tools/bin/pytest}"
CHECKS=0
FAILURES=0
ok() {
CHECKS=$((CHECKS + 1))
echo " ok: $1"
}
fail() {
CHECKS=$((CHECKS + 1))
FAILURES=$((FAILURES + 1))
echo " FAIL: $1"
}
echo "=== 1. Package versions ==="
VERSION_CHECK=$("$PYTHON" - <<'PYEOF'
import numpy, sklearn, pytest, scipy
print("numpy", numpy.__version__)
print("scikit-learn", sklearn.__version__)
print("pytest", pytest.__version__)
print("scipy", scipy.__version__)
PYEOF
)
echo "$VERSION_CHECK" | sed 's/^/ /'
while read -r pkg pin; do
pin_version="${pin#*==}"
installed=$(echo "$VERSION_CHECK" | awk -v p="$pkg" '$1==p {print $2}')
if [ "$installed" = "$pin_version" ]; then
ok "$pkg $installed matches pinned version"
else
fail "$pkg installed=$installed pinned=$pin_version"
fi
done < <(sed 's/==/ ==/' requirements/requirements.txt)
echo ""
echo "=== 2. Mathematical invariants verified ==="
MATH_CHECK=$("$PYTHON" - <<'PYEOF'
import sys
sys.path.insert(0, "examples")
import numpy as np
import features_beat_algorithms_lib as fba
# Mathematical representation expansion invariant
X = np.array([[1.80, 80.0, 30.0, 12.0]])
X_eng = fba.engineer_domain_representation(X)
# Height(0), Weight(1), Age(2), BMI(3), sin(4), cos(5), age_bmi(6) -> 7 columns
assert X_eng.shape == (1, 7), "Engineered feature matrix dimension mismatch"
expected_bmi = 80.0 / (1.80**2)
assert np.isclose(X_eng[0, 3], expected_bmi), "Domain ratio calculation error"
print("MATH_OK")
PYEOF
)
if [ "$MATH_CHECK" = "MATH_OK" ]; then
ok "Representation expansion mathematical invariants verified"
else
fail "Mathematical verification failed: $MATH_CHECK"
fi
echo ""
echo "=== 3. Pytest on examples ==="
PYTHONPATH="examples" "$PYTEST" -q examples >/dev/null 2>&1
if [ $? -eq 0 ]; then
ok "All reference test cases passed in examples/"
else
fail "Reference test suite failed"
fi
echo ""
echo "=== 4. Pytest on starter ==="
PYTHONPATH="starter" "$PYTEST" -q starter >/dev/null 2>&1
if [ $? -eq 0 ]; then
ok "Starter stub tests executed successfully"
else
fail "Starter stub tests failed"
fi
echo ""
echo "Summary: $CHECKS checks, $FAILURES failure(s)"
if [ $FAILURES -eq 0 ]; then
exit 0
else
exit 1
fi
Troubleshooting
Troubleshooting Guide for Day 175
Common Issues
1. The "Hidden Technical Debt" Anti-Pattern (CMLC)
- Symptom: Adding 50 experimental features creates an unmaintainable codebase where changing one feature breaks 10 downstream models ("Changing Anything Changes Everything").
- Cause: Lack of modular feature store definitions and feature documentation.
- Fix: Track every feature's mathematical definition, upstream lineage, and data dependencies in a standardized feature store schema.
2. Over-Engineering on Pure Noise
- Symptom: Complex engineered features score 0.99 in training but fail to generalize to validation data.
- Cause: Creating high-order polynomial combinations without domain hypothesis validation.
- Fix: Use Boruta or RFECV feature selection inside cross-validation to prune uninformative engineered interactions.
Security notes
Security and Privacy Notes for Day 175
- Feature Lineage & Governance: Maintain strict data catalogs for all engineered features to ensure compliance with GDPR "Right to Explanation" and AI ethics auditing.
- Local Sandbox: All benchmark code executes locally on CPU.