La interfaz está localizada; las descripciones y documentos de las Skills se traducen automáticamente con IA a su idioma. El código, los comandos, rutas y términos técnicos se mantienen en el original, y prevalece el documento del autor.
name: ml-classical-ml
description: >
Use this skill when asked about scikit-learn, XGBoost, LightGBM, CatBoost, regression, classification, clustering, ensemble, random forest, gradient boosting, SVM, PCA, feature importance, or cross-validation. This skill enforces: supervised learning pipelines (regression and classification metrics), ensemble methods (bagging, boosting, stacking), gradient boosting hyperparameter tuning (XGBoost, LightGBM, CatBoost), unsupervised learning (clustering dimensionality reduction), scikit-learn Pipeline and ColumnTransformer, cross-validation strategies, and imbalanced data handling. Do NOT use for: deep neural networks, reinforcement learning, or transformer models.
version: "1.1.0"
author: "j4flmao"
license: "MIT"
compatibility:
claude-code: true
cursor: true
codex: true
windsurf: true
tags: [ml, classical, machine-learning, phase-11]
ML Classical ML
Purpose
Build supervised and unsupervised machine learning pipelines with scikit-learn, XGBoost, LightGBM, and CatBoost. Select models by problem type, tune hyperparameters systematically, validate with appropriate cross-validation, and handle class imbalance.
Feature importance (tree-based): gain-based, permutation importance, SHAP values. Partial dependence plots. LIME for local explanations. Use permutation importance as the most reliable global method.
from imblearn.over_sampling import SMOTE
from imblearn.combine import SMOTEENN
from imblearn.pipeline import Pipeline as ImbPipeline
# SMOTE within pipeline
imb_pipeline = ImbPipeline([
("preprocessor", preprocessor),
("smote", SMOTE(sampling_strategy="auto", random_state=42, k_neighbors=5)),
("classifier", XGBClassifier(
scale_pos_weight=len(y_train[y_train==0]) / len(y_train[y_train==1]),
eval_metric="logloss",
)),
])
# Threshold tuning from PR curve
from sklearn.metrics import precision_recall_curve
probs = imb_pipeline.predict_proba(X_val)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_val, probs)
f1_scores = 2 * precision * recall / (precision + recall)
best_threshold = thresholds[f1_scores.argmax()]
Step 8: Model Serialization
Joblib for numpy-heavy models. ONNX for cross-platform deployment. Native formats: XGBoost .json/.ubj, LightGBM .txt, CatBoost .cbm. Serialize full pipeline, not just model weights.
import joblib
# Save full pipeline
joblib.dump(pipeline, "models/churn_pipeline_v2.pkl")
# XGBoost native format
pipeline.named_steps["classifier"].save_model("models/xgb_model.json")
# Load and predict
loaded = joblib.load("models/churn_pipeline_v2.pkl")
predictions = loaded.predict(new_data)
Step 9: Ensemble Methods
Beyond individual models, use ensemble methods: Voting classifier (soft/hard voting), Stacking (meta-model on base model predictions), and Bagging (bootstrap aggregation).
Feature engineering transforms raw data into informative predictors. Include interaction features, polynomial features, binning, and target encoding for high-cardinality categoricals.
from sklearn.preprocessing import PolynomialFeatures, KBinsDiscretizer
from sklearn.feature_selection import SelectFromModel
# Add interaction and polynomial features
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
# Target encoding for high-cardinality categories
from category_encoders import TargetEncoder
# Feature selection from model importance
selector = SelectFromModel(
RandomForestClassifier(n_estimators=100, random_state=42),
threshold="median", max_features=50,
)
Imbalanced data with accuracy metric: 99% accuracy on 99:1 imbalance is misleading. Fix: use precision-recall, AUC-PR.
Too many features: overfitting and slow training. Fix: feature selection, dimensionality reduction.
Not cross-validating time series: random shuffle breaks temporal order. Fix: TimeSeriesSplit.
Confusing correlation with causation: feature importance shows correlation, not causation.
Using default hyperparameters without tuning: defaults are rarely optimal for your specific dataset.
Testing multiple hypotheses on same test set: each test set evaluation erodes statistical validity. Fix: hold out test set until final evaluation.
Ignoring multicollinearity in linear models: correlated features inflate coefficient variance in linear regression.
Not encoding cyclical features properly: hour, day of week, month need sin/cos encoding for ML algorithms to understand cyclical nature.
Applying SMOTE before train/test split: SMOTE on full dataset leaks synthetic samples across folds. Apply inside CV loop.
Not setting random_state: non-deterministic results make debugging and comparison impossible.
Using AUC-ROC for highly imbalanced data: AUC-ROC over-optimistic for 99:1 imbalance. Use AUC-PR.
Best Practices
Use Pipeline and ColumnTransformer for ALL preprocessing. Never manually transform.
Fit preprocessing on training data only. Transform validation/test with fitted transformer.
Select scoring metric based on business problem, not convention.
Stratified CV for classification. Group CV for grouped data. TimeSeriesSplit for time series.
Cross-validate hyperparameters on training folds, never tune on test set.
Use AUC-PR for imbalanced data instead of AUC-ROC.
Scale features for distance-based models (KNN, SVM, PCA, clustering).
Tree-based models need no scaling.
Feature importance from gradient boosting informs feature selection.
Test set is for final evaluation only — one inference.
Set random_state for reproducibility across all training runs.
Log all experiments with parameters, metrics, and data versions.
Use learning curves to diagnose bias vs variance.
Start with a simple baseline (mean, majority class) before complex models.
Monitor feature distributions over time for concept drift.
Validate model calibration with reliability diagrams (calibration curves).
Ensemble diverse models (different families) for better generalization.
Profile prediction latency before deploying to production.
Compared With
Model
Accuracy
Training Speed
Inference Speed
Interpretability
Categorical Support
Logistic Regression
Low
Very fast
Very fast
High
Requires encoding
Random Forest
Medium
Medium
Fast
Medium (importance)
Requires encoding
XGBoost
High
Medium
Fast
Medium
Requires encoding
LightGBM
High
Fast
Fast
Medium
Native
CatBoost
High
Slow
Medium
Medium
Native (best)
SVM (RBF)
Medium
Slow
Medium
Low
Requires encoding
Gradient Boosting
High
Slow
Fast
Medium
Requires encoding
KNN
Medium
None
Slow
Low
Requires encoding
Classical ML vs deep learning: classical ML (especially gradient boosting) often outperforms deep learning on tabular data with < 100K samples. Deep learning excels with unstructured data (images, text, audio) and large datasets. For tabular data, start with gradient boosting. Use deep learning when you have > 1M samples or unstructured inputs.
Classical ML vs rule-based: rule-based systems are fully interpretable but don't generalize beyond explicit rules. Classical ML learns patterns from data. Use rule-based for compliance-critical decisions (credit scoring, medical triage), ML for complex pattern recognition.
Performance
XGBoost vs LightGBM: LightGBM 2-4x faster training, similar accuracy. LightGBM uses histogram-based splits.
CatBoost: 1.5-2x slower training but best categorical support (no encoding needed).
Random Forest: scales with n_estimators * max_depth. O(1) per tree, parallel by default.
Pipeline overhead: minimal (< 5ms per prediction for 100 features).
SHAP: O(2^n * T) for exact TreeSHAP. Use approximate or interventional for large models.
Feature importance (permutation): O(n * T) where n = iterations, T = trees.
Inference optimization: convert to ONNX for 2-5x faster inference. Quantize to float16 for 2x memory reduction.
Large dataset strategy: for datasets > 1M rows, use histogram-based boosting (LightGBM/XGBoost hist). For > 10M rows, use sampling or distributed training (Spark + XGBoost).
Feature selection reduces training time linearly. Remove features with near-zero variance or extremely low importance.
Tooling
Tool
Purpose
scikit-learn
General ML pipeline, preprocessing, models
XGBoost
Gradient boosting (fast, well-tuned defaults)
LightGBM
Gradient boosting (very fast, large data)
CatBoost
Gradient boosting (native categorical)
Optuna / Hyperopt
Bayesian hyperparameter optimization
SHAP
Model interpretation
imbalanced-learn
SMOTE, sampling strategies
MLflow
Experiment tracking
ONNX
Cross-platform model deployment
category_encoders
Target encoding, leave-one-out encoding
feature-engine
Advanced feature engineering, selection
Pandas / Polars
Data manipulation and exploration
Yellowbrick
Visual diagnostics for ML models
Dask ML
Distributed scikit-learn for large datasets
Rules
Use Pipeline and ColumnTransformer for all preprocessing
Fit preprocessing on training data only, transform validation/test
Select scoring metric by business problem, not convention
Use stratified cross-validation for classification
Cross-validate hyperparameters, never tune on test set
Use AUC-PR instead of AUC-ROC for imbalanced data
Scale features for distance-based models (KNN, SVM, PCA)
Tree-based models need no scaling
Feature importance from gradient boosting informs feature selection
Test set is for final evaluation only — one inference
Set random_state for all experiments
Log experiments with parameters, metrics, data versions
Start with a simple baseline before complex models
Validate calibration for probabilistic predictions
Profile inference latency before production deployment
Monitor for concept drift post-deployment
Use learning curves to diagnose bias-variance tradeoff
Never apply SMOTE before train/test split
References
references/classical-ml-advanced.md — Classical Ml Advanced Topics
references/classical-ml-fundamentals.md — Classical Ml Fundamentals
references/imbalanced-learn.md — Handling Imbalanced Data
references/interpretable-ml.md — Interpretable Classical ML
references/classical-ml-model-selection.md — Model Selection Reference
Handoff
ml-deep-learning for deep learning/neural network methods
ml-feature-engineering for feature extraction and selection
Architecture Decision Trees
Algorithm Selection
Decision Point
Option A
Option B
Decision Criteria
Problem type
Regression (continuous output)
Classification (discrete labels)
Target variable type
Data size
Small (<10k samples) → LR/SVM kernel
Large (>100k) → RF/XGBoost/LightGBM
Training time, performance needs
Interpretability
Linear/Logistic Regression (glassbox)
XGBoost/Random Forest (blackbox)
Regulatory requirements, debugging needs
Linearity
Linear methods (if data is linear)
Tree-based/Kernel (if non-linear)
Feature-target relationship
Preprocessing Decision Tree
Missing values few → Impute (mean/median/mode)
Missing values many → Flag + impute, or drop feature
Categorical low cardinality → One-hot encode
Categorical high cardinality → Target encoding or embedding
Skewed numeric → Log/Box-Cox transform
Different scales → StandardScaler or MinMaxScaler
Implementation Patterns
End-to-End Classification Pipeline
`python
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import pandas as pd