技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
ml-classical-ml【数据与研究】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), gr…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
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.
Exact user phrases: "scikit-learn", "XGBoost", "LightGBM", "CatBoost", "regression", "classification", "clustering", "ensemble", "random forest", "gradient boosting", "SVM", "PCA", "feature importance", "cross-validation", "imbalanced data", "SMOTE", "hyperparameter tuning".
Before activating, verify:
ML pipeline with model selection, hyperparameter configuration, cross-validation strategy, and training code as Python.
# Pipeline definition (preprocessing + model)
# Training and validation code
# Hyperparameter search configuration
# Model hyperparameters
# Cross-validation config
No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.
300 lines of code and configuration.
Regression: MSE/RMSE, MAE, R-squared, MAPE. Binary classification: AUC-ROC, F1, log loss, precision@k, recall. Multiclass: macro/micro/weighted F1. Ranking: NDCG, MAP.
from sklearn.metrics import (
mean_squared_error, mean_absolute_error, r2_score,
roc_auc_score, f1_score, log_loss,
precision_recall_curve, average_precision_score,
classification_report
)
Linear: LogisticRegression, LinearRegression, Ridge — interpretable, fast. Tree: DecisionTree, RandomForest — non-linear, robust. Gradient Boosting: XGBoost (fast, defaults), LightGBM (fastest, large data), CatBoost (categorical native). SVM: high-dimensional spaces.
# Model selection guide
regression:
linear: LinearRegression, Ridge, Lasso, ElasticNet
tree: RandomForestRegressor, GradientBoostingRegressor
boosting: XGBRegressor, LGBMRegressor, CatBoostRegressor
classification:
linear: LogisticRegression, LinearSVC
tree: RandomForestClassifier, ExtraTreesClassifier
boosting: XGBClassifier, LGBMClassifier, CatBoostClassifier
svm: SVC, NuSVC
scikit-learn Pipeline chains transforms. ColumnTransformer applies different transforms by column type. Numeric: StandardScaler, MinMaxScaler, RobustScaler, PowerTransformer. Categorical: OneHotEncoder, OrdinalEncoder. Missing: SimpleImputer, KNNImputer.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder, OrdinalEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
numeric_features = ["age", "income", "score"]
categorical_features = ["region", "tier"]
ordinal_features = ["education"]
preprocessor = ColumnTransformer(transformers=[
("num", Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
]), numeric_features),
("cat", Pipeline([
("imputer", SimpleImputer(strategy="constant", fill_value="MISSING")),
("encoder", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
]), categorical_features),
("ord", Pipeline([
("encoder", OrdinalEncoder(categories=[["HS", "BS", "MS", "PhD"]])),
]), ordinal_features),
])
pipeline = Pipeline([
("preprocessor", preprocessor),
("classifier", RandomForestClassifier(n_estimators=200, random_state=42)),
])
K-Fold: default for i.i.d. data. StratifiedKFold: classification with imbalanced classes. GroupKFold: no leakage across groups. TimeSeriesSplit: temporal data. Repeated K-Fold: lower variance estimate.
from sklearn.model_selection import (
KFold, StratifiedKFold, GroupKFold,
TimeSeriesSplit, RepeatedKFold, cross_validate
)
# Stratified CV for imbalanced classification
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# Time series CV
ts_cv = TimeSeriesSplit(n_splits=5, gap=0)
# Group CV
group_cv = GroupKFold(n_splits=5)
scores = cross_validate(
pipeline, X_train, y_train,
cv=cv, scoring=["roc_auc", "f1", "precision", "recall"],
n_jobs=-1, return_estimator=True,
return_train_score=True,
)
GridSearchCV: exhaustive (small spaces). RandomizedSearchCV: random sampling (large spaces). Optuna: Bayesian optimization with pruning. HalvingGridSearchCV: successive halving for faster search.
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform
param_dist = {
"classifier__n_estimators": randint(100, 1000),
"classifier__max_depth": randint(3, 20),
"classifier__min_samples_split": randint(2, 20),
"classifier__min_samples_leaf": randint(1, 10),
"classifier__max_features": uniform(0.3, 0.7),
}
random_search = RandomizedSearchCV(
pipeline, param_distributions=param_dist,
n_iter=50, cv=5, scoring="roc_auc",
n_jobs=-1, random_state=42, verbose=1,
)
random_search.fit(X_train, y_train)
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.
import shap
import matplotlib.pyplot as plt
# Permutation importance
from sklearn.inspection import permutation_importance
result = permutation_importance(
best_model, X_val, y_val,
n_repeats=10, random_state=42, n_jobs=-1,
)
feature_importance = pd.DataFrame({
"feature": feature_names,
"importance": result.importances_mean,
"std": result.importances_std,
}).sort_values("importance", ascending=False)
# SHAP explanation
explainer = shap.TreeExplainer(best_model.named_steps["classifier"])
shap_values = explainer.shap_values(
preprocessor.transform(X_val[:100])
)
shap.summary_plot(shap_values, X_val[:100])
Resampling: SMOTE, RandomUnderSampler, SMOTEENN. Algorithmic: class_weight='balanced', scale_pos_weight (XGBoost). Metric: precision-recall curve, AUC-PR. Threshold tuning.
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()]
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)
Beyond individual models, use ensemble methods: Voting classifier (soft/hard voting), Stacking (meta-model on base model predictions), and Bagging (bootstrap aggregation).
from sklearn.ensemble import VotingClassifier, StackingClassifier
# Soft voting
voting = VotingClassifier(estimators=[
("lr", LogisticRegression()),
("rf", RandomForestClassifier(n_estimators=200)),
("xgb", XGBClassifier(eval_metric="logloss")),
], voting="soft")
# Stacking with meta-model
stacking = StackingClassifier(estimators=[
("rf", RandomForestClassifier(n_estimators=200)),
("xgb", XGBClassifier(eval_metric="logloss")),
("cat", CatBoostClassifier(verbose=0)),
], final_estimator=LogisticRegression(), cv=5)
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,
)
Problem type
├── Regression (continuous target)
│ ├── Linear relationship + interpretability → LinearRegression / Ridge
│ ├── Non-linear, robust → RandomForest / XGBoost
│ ├── High cardinality categorical → CatBoost
│ └── Large dataset (> 100K rows) → LightGBM
├── Classification (binary)
│ ├── Interpretability needed → LogisticRegression
│ ├── Imbalanced → XGBoost + scale_pos_weight or SMOTE
│ ├── High-dimensional → LinearSVC
│ └── Default robust → GradientBoosting / RandomForest
├── Multiclass
│ └── Any ensemble method with multiclass support
├── Clustering (unsupervised)
│ ├── Known clusters → K-Means
│ ├── Unknown shape → DBSCAN
│ └── Hierarchical → Agglomerative
└── Dimensionality reduction
├── Linear → PCA
└── Non-linear → t-SNE / UMAP (visualization)
Data type
├── I.I.D. samples → KFold (regression), StratifiedKFold (classification)
├── Grouped data (same subject, multiple samples) → GroupKFold
├── Time series → TimeSeriesSplit (no future leakage)
├── Small dataset (< 1000 samples) → LeaveOneOut or RepeatedKFold
└── Large dataset (> 100K samples) → ShuffleSplit (fewer folds)
| 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.
| 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 |
ml-deep-learning for deep learning/neural network methods
ml-feature-engineering for feature extraction and 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 |
`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
numeric_features = ['age', 'income', 'score'] categorical_features = ['region', 'plan_type']
preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features) ])
pipeline = Pipeline([ ('preprocessor', preprocessor), ('classifier', RandomForestClassifier( n_estimators=200, max_depth=10, random_state=42 )) ])
pipeline.fit(X_train, y_train) cv_scores = cross_val_score(pipeline, X_train, y_train, cv=5, scoring='f1_macro') print(f'CV F1: {cv_scores.mean():.3f} +/- {cv_scores.std():.3f}') `
`python import xgboost as xgb from sklearn.model_selection import RandomizedSearchCV
param_grid = { 'max_depth': [3, 5, 7, 9], 'learning_rate': [0.01, 0.05, 0.1, 0.3], 'n_estimators': [100, 200, 300], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.6, 0.8, 1.0] }
xgb_model = xgb.XGBClassifier( objective='binary:logistic', eval_metric='auc', early_stopping_rounds=20, random_state=42 )
search = RandomizedSearchCV( xgb_model, param_grid, n_iter=50, cv=5, scoring='roc_auc', n_jobs=-1, verbose=1 ) search.fit(X_train, y_train, eval_set=[(X_val, y_val)]) `
| Anti-Pattern | Symptom | Solution |
|---|---|---|
| Data leakage | Unrealistically high CV scores | Use pipelines, never fit on full data before split |
| Target encoding without regularization | Overfitting to rare categories | Use smoothing (e.g., CatBoost ordered encoding) |
| Ignoring class imbalance | High accuracy but zero recall on minority class | Use class weights, SMOTE, or specialized sampling |
| P-hacking features | Overfit on spurious correlations | Use feature selection with cross-validation |
| One-hot encoding high cardinality | Exploding feature space | Use target encoding, embeddings, or feature hashing |