python 25 lines · 1 tab

Encoding categorical variables without creating leakage

1 tab
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric_features = ['age', 'income', 'tenure_months']
categorical_features = ['country', 'plan_tier', 'device_type']

numeric_pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler()),
])

categorical_pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False)),
])

preprocessor = ColumnTransformer([
    ('num', numeric_pipeline, numeric_features),
    ('cat', categorical_pipeline, categorical_features),
])

print(preprocessor)
1 file · python Explain with highlit

Categoricals are where good intentions become leakage. I use one-hot encoding for low-cardinality stable fields, ordinal encoders only when order is real, and frequency or target encoders with strict cross-validation boundaries. The encoder strategy should reflect both statistical behavior and production serving constraints.


Related snips

python
import cv2

image = cv2.imread('receipt.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresholded = cv2.adaptiveThreshold(

OpenCV image preprocessing for OCR and vision pipelines

opencv image-processing computer-vision
by Dr. Elena Vasquez 1 tab
python
import pandas as pd

df = pd.read_csv('customers.csv')

df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_', regex=False)

Cleaning missing values and normalizing messy CSV exports

pandas data-cleaning missing-values
by Dr. Elena Vasquez 1 tab
python
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.metrics import mean_absolute_error, root_mean_squared_error

models = {
    'linear': LinearRegression(),
    'ridge': Ridge(alpha=1.0),

Regression workflows with linear, ridge, lasso, and elastic net

scikit-learn regression ridge
by Dr. Elena Vasquez 1 tab
sql
WITH ordered_events AS (
  SELECT
    customer_id,
    event_time,
    revenue,
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY event_time DESC) AS event_rank,

SQL window functions for feature extraction and behavioral ranking

sql window-functions feature-engineering
by Dr. Elena Vasquez 1 tab
python
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier

grid_search = GridSearchCV(
    estimator=RandomForestClassifier(random_state=42, n_jobs=-1),
    param_grid={

Hyperparameter tuning with GridSearchCV and randomized search

hyperparameter-tuning gridsearch scikit-learn
by Dr. Elena Vasquez 1 tab
python
import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title='Churn Prediction API')

Serving scikit-learn models behind a FastAPI prediction API

fastapi scikit-learn model-serving
by Dr. Elena Vasquez 1 tab

Share this code

Here's the card — post it anywhere.

Encoding categorical variables without creating leakage — share card
Link copied