Examples
Four end-to-end ML examples in compact form — each shows a different problem class with the right framing, baseline, model, and metric. Copy them as starting points for your own work.
Binary, multiclass, regression, and time-series
EXAMPLE
# 1) Binary classification: churn
import pandas as pd, numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.metrics import roc_auc_score, classification_report
from xgboost import XGBClassifier
df = pd.read_csv('churn.csv')
y = df.pop('churned'); X = df
num = X.select_dtypes('number').columns.tolist()
cat = X.select_dtypes(exclude='number').columns.tolist()
pipe = Pipeline([
('prep', ColumnTransformer([
('num', Pipeline([('imp', SimpleImputer(strategy='median')),
('sc', StandardScaler())]), num),
('cat', Pipeline([('imp', SimpleImputer(strategy='most_frequent')),
('ohe', OneHotEncoder(handle_unknown='ignore'))]), cat),
])),
('clf', XGBClassifier(n_estimators=400, max_depth=6, learning_rate=0.05, eval_metric='auc')),
])
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, test_size=.2, random_state=42)
print('cv AUC:', cross_val_score(pipe, X_tr, y_tr, cv=StratifiedKFold(5, shuffle=True, random_state=42),
scoring='roc_auc', n_jobs=-1).mean())
pipe.fit(X_tr, y_tr)
print('test AUC:', roc_auc_score(y_te, pipe.predict_proba(X_te)[:, 1]))
# 2) Multiclass text: support ticket triage
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
texts = pd.read_csv('tickets.csv')
y = texts.pop('category')
X = texts['body']
tfidf = TfidfVectorizer(min_df=3, ngram_range=(1, 2), strip_accents='unicode')
clf = LogisticRegression(max_iter=1000, n_jobs=-1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, test_size=.2, random_state=42)
clf.fit(tfidf.fit_transform(X_tr), y_tr)
pred = clf.predict(tfidf.transform(X_te))
print('macro F1:', f1_score(y_te, pred, average='macro'))
# 3) Regression: predict order value
from lightgbm import LGBMRegressor
from sklearn.metrics import mean_absolute_error
orders = pd.read_parquet('orders.parquet')
y = orders.pop('total_cents')
X = orders.drop(columns=['order_id'])
model = LGBMRegressor(n_estimators=600, learning_rate=0.03, random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=.2, random_state=42)
model.fit(X_tr, y_tr, eval_set=[(X_te, y_te)], callbacks=[])
print('test MAE $:', mean_absolute_error(y_te, model.predict(X_te)) / 100)
# 4) Time series: daily forecasts with Prophet
# pip install prophet
from prophet import Prophet
ts = pd.read_csv('daily_revenue.csv').rename(columns={'date': 'ds', 'revenue': 'y'})
m = Prophet(weekly_seasonality=True, yearly_seasonality=True,
holidays_prior_scale=10, seasonality_prior_scale=10)
m.add_country_holidays(country_name='AU')
m.fit(ts)
future = m.make_future_dataframe(periods=30)
forecast = m.predict(future)
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
Why it matters
Always ship a stupid baseline alongside the model — majority class for classification, mean for regression, naive lag-1 for time series. If the smart model does not beat the baseline by a margin you can defend in production, the right answer is the baseline.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…