⚙️ Building an Enterprise Machine Learning Project
A professional Machine Learning Project goes far beyond fitting an algorithm on clean data inside a Jupyter Notebook. It requires an industrial-grade engineering pipeline: modular directory scaffolding, stratified dataset splitting, ColumnTransformer preprocessing (preventing feature leakage between numerical and categorical attributes), cross-validated model tournaments, automated hyperparameter search, model artifact serialization, and low-latency REST API deployment with strict schema validation.
ml_enterprise_project/
│
├── config/
│ └── settings.py # Hyperparameters, paths, and environment settings
│
├── data/
│ ├── raw/ # Immutable incoming raw data streams
│ └── processed/ # Cleaned, train-test split datasets
│
├── src/
│ ├── __init__.py
│ ├── data_loader.py # Database connection, validation & ingestion
│ ├── preprocessor.py # ColumnTransformer pipelines (Imputation + OneHot + Scaling)
│ ├── model_trainer.py # Multi-model benchmarking & GridSearchCV tuning
│ └── evaluator.py # Classification & regression performance scorecards
│
├── models/
│ └── churn_pipeline_v1.joblib # Versioned, ready-to-deploy serialized model artifact
│
├── api/
│ ├── app.py # FastAPI application serving /predict endpoint
│ └── schemas.py # Pydantic input/output contract schemas
│
├── tests/
│ ├── test_data_quality.py # Schema assertion and drift tests
│ └── test_inference_api.py # Pytest API functional and boundary tests
│
└── requirements.txt # Scikit-Learn, Pandas, NumPy, Joblib, FastAPI
import pandas as pd
import numpy as np
def load_customer_churn_dataset() -> pd.DataFrame:
"""Simulates loading customer records containing numerical and categorical attributes."""
data = {
"customer_id": [f"CUST-{i}" for i in range(1001, 1009)],
"monthly_charges": [450.0, 1200.0, 850.0, 2400.0, 310.0, 1850.0, 920.0, 1450.0],
"tenure_months": [2, 24, 6, 36, 1, 18, 12, 4],
"support_tickets": [4, 1, 3, 0, 5, 2, 1, 3],
"contract_type": ["Month-to-Month", "One-Year", "Month-to-Month", "Two-Year",
"Month-to-Month", "One-Year", "One-Year", "Month-to-Month"],
"payment_method": ["UPI", "Credit Card", "Net Banking", "Credit Card",
"UPI", "Net Banking", "Credit Card", "UPI"],
"churned": [1, 0, 1, 0, 1, 0, 0, 1] # Target: 1 = Churned, 0 = Retained
}
return pd.DataFrame(data)
df = load_customer_churn_dataset()
print("Ingested Raw Dataset Shape:", df.shape)
print("\nSample Data Records:\n", df[["customer_id", "monthly_charges", "tenure_months", "contract_type", "churned"]].head(4))
ColumnTransformer that applies StandardScaler and median imputation to continuous features while applying OneHotEncoder to discrete categories without data leakage.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
# Define feature boundaries
numerical_features = ["monthly_charges", "tenure_months", "support_tickets"]
categorical_features = ["contract_type", "payment_method"]
# Numerical transformation pipeline: Impute nulls with median + scale to unit variance
num_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
# Categorical transformation pipeline: Impute nulls with most frequent + One-Hot Encode
cat_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False))
])
# Combine into a unified preprocessor
preprocessor = ColumnTransformer(
transformers=[
("num", num_pipeline, numerical_features),
("cat", cat_pipeline, categorical_features)
]
)
print("Constructed Preprocessing Engine:")
print(preprocessor)
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.pipeline import Pipeline
import numpy as np
# Prepare training vectors
X = df[numerical_features + categorical_features]
y = df["churned"]
candidate_models = {
"Logistic Regression": LogisticRegression(random_state=42),
"Random Forest": RandomForestClassifier(n_estimators=50, random_state=42),
"Gradient Boosting": GradientBoostingClassifier(n_estimators=30, random_state=42)
}
cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
tournament_results = {}
for model_name, model_instance in candidate_models.items():
full_pipeline = Pipeline([
("prep", preprocessor),
("algo", model_instance)
])
# Benchmark using ROC-AUC metric
scores = cross_val_score(full_pipeline, X, y, cv=cv, scoring="accuracy")
tournament_results[model_name] = round(float(np.mean(scores)), 4)
print(f"Model: {model_name:22s} | Mean CV Accuracy: {np.mean(scores)*100:.1f}%")
champion_name = max(tournament_results, key=tournament_results.get)
print(f"\nChampion Selected: {champion_name}")
from sklearn.model_selection import GridSearchCV
# Build full pipeline integrating the chosen Gradient Boosting Classifier
champion_pipeline = Pipeline([
("prep", preprocessor),
("classifier", GradientBoostingClassifier(random_state=42))
])
# Parameter grid focusing on regularization & tree depth
param_grid = {
"classifier__learning_rate": [0.05, 0.1],
"classifier__max_depth": [2, 3],
"classifier__n_estimators": [20, 40]
}
grid_search = GridSearchCV(
estimator=champion_pipeline,
param_grid=param_grid,
cv=3,
scoring="accuracy",
n_jobs=-1
)
grid_search.fit(X, y)
print(f"Optimal Parameters Found:\n{grid_search.best_params_}")
print(f"Top Cross-Validated Accuracy: {grid_search.best_score_ * 100:.2f}%")
from sklearn.metrics import classification_report, confusion_matrix
best_model = grid_search.best_estimator_
# Generate in-sample predictions for verification
y_preds = best_model.predict(X)
cm = confusion_matrix(y, y_preds)
print("Confusion Matrix:\n", cm)
print("\nClassification Evaluation Metrics Report:")
print(classification_report(y, y_preds, target_names=["Retained (0)", "Churn Risk (1)"]))
joblib and compute its SHA-256 checksum for auditability and CI/CD deployment security.
import joblib
import hashlib
import os
import tempfile
artifact_dir = tempfile.gettempdir()
model_path = os.path.join(artifact_dir, "customer_churn_pipeline_v1.joblib")
# 1. Export the end-to-end fitted pipeline
joblib.dump(best_model, model_path)
# 2. Compute cryptographic SHA-256 hash
sha256_hash = hashlib.sha256()
with open(model_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
model_checksum = sha256_hash.hexdigest()
print(f"Model Artifact Successfully Saved to: {model_path}")
print(f"Artifact File Size: {os.path.getsize(model_path)} bytes")
print(f"Artifact SHA-256 Checksum: {model_checksum}")
from pydantic import BaseModel, Field
from typing import Literal
class CustomerInferenceRequest(BaseModel):
"""Pydantic schema enforcing incoming inference payload validation."""
monthly_charges: float = Field(gt=0, description="Monthly invoice charge in INR")
tenure_months: int = Field(ge=0, description="Total active months on platform")
support_tickets: int = Field(ge=0, description="Customer service ticket volume")
contract_type: Literal["Month-to-Month", "One-Year", "Two-Year"]
payment_method: Literal["UPI", "Credit Card", "Net Banking"]
# Valid client request test
client_json = {
"monthly_charges": 1850.0,
"tenure_months": 3,
"support_tickets": 4,
"contract_type": "Month-to-Month",
"payment_method": "UPI"
}
validated_input = CustomerInferenceRequest(**client_json)
print("Validated Client Payload:")
print(validated_input.model_dump())
import joblib
import pandas as pd
# Load serialized pipeline from disk
loaded_pipeline = joblib.load(model_path)
def predict_customer_churn_service(request: CustomerInferenceRequest) -> dict:
"""Production inference handler serving real-time predictions."""
# Convert validated Pydantic model into a 1-row DataFrame matching training feature columns
input_df = pd.DataFrame([request.model_dump()])
# Predict discrete class and probability score
prediction = int(loaded_pipeline.predict(input_df)[0])
probabilities = loaded_pipeline.predict_proba(input_df)[0]
churn_probability = float(probabilities[1])
return {
"status": "success",
"churn_prediction": "CHURN_RISK" if prediction == 1 else "RETAINED",
"churn_probability": round(churn_probability, 4),
"recommended_action": "ISSUE_RETENTION_COUPON" if churn_probability > 0.60 else "STANDARD_NURTURE"
}
# Execute live inference request
response = predict_customer_churn_service(validated_input)
print("API Response Output:")
for key, value in response.items():
print(f" {key:22s}: {value}")
def test_pipeline_inference_structure():
"""Validates that loaded pipeline returns valid structured predictions."""
sample = CustomerInferenceRequest(
monthly_charges=310.0,
tenure_months=36,
support_tickets=0,
contract_type="Two-Year",
payment_method="Credit Card"
)
res = predict_customer_churn_service(sample)
assert res["status"] == "success"
assert res["churn_prediction"] in ["CHURN_RISK", "RETAINED"]
assert 0.0 <= res["churn_probability"] <= 1.0
assert "recommended_action" in res
def test_pipeline_high_risk_scenario():
"""Asserts that high-risk inputs correctly flag churn risk."""
high_risk_sample = CustomerInferenceRequest(
monthly_charges=2500.0,
tenure_months=1,
support_tickets=6,
contract_type="Month-to-Month",
payment_method="UPI"
)
res = predict_customer_churn_service(high_risk_sample)
assert res["churn_prediction"] == "CHURN_RISK"
assert res["churn_probability"] >= 0.50
# Run assertions
test_pipeline_inference_structure()
test_pipeline_high_risk_scenario()
print("✓ test_pipeline_inference_structure: PASSED")
print("✓ test_pipeline_high_risk_scenario : PASSED")
print("\nAll Automated ML Pipeline CI Tests Passed Successfully.")