Scikit-learn
Overview
This skill provides comprehensive guidance for machine learning tasks using scikit-learn, the industry-standard Python library for classical machine learning. Use this skill for classification, regression, clustering, dimensionality reduction, preprocessing, model evaluation, and building production-ready ML pipelines.
Installation
# Install scikit-learn using uv
uv uv pip install scikit-learn
# Optional: Install visualization dependencies
uv uv pip install matplotlib seaborn
# Commonly used with
uv uv pip install pandas numpy
When to Use This Skill
Use the scikit-learn skill when:
- Building classification or regression models
- Performing clustering or dimensionality reduction
- Preprocessing and transforming data for machine learning
- Evaluating model performance with cross-validation
- Tuning hyperparameters with grid or random search
- Creating ML pipelines for production workflows
- Comparing different algorithms for a task
- Working with both structured (tabular) and text data
- Need interpretable, classical machine learning approaches
Quick Start
Classification Example
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
# Preprocess
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# Evaluate
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))
Complete Pipeline with Mixed Data
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier
# Define feature types
numeric_features = ['age', 'income']
categorical_features = ['gender', 'occupation']
# Create preprocessing pipelines
numeric_transformer = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
categorical_transformer = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Combine transformers
preprocessor = ColumnTransformer([
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
])
# Full pipeline
model = Pipeline([
('preprocessor', preprocessor),
('classifier', GradientBoostingClassifier(random_state=42))
])
# Fit and predict
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Core Capabilities
1. Supervised Learning
Comprehensive algorithms for classification and regression tasks.
Key algorithms:
- Linear models: Logistic Regression, Linear Regression, Ridge, Lasso, ElasticNet
- Tree-based: Decision Trees, Random Forest, Gradient Boosting
- Support Vector Machines: SVC, SVR with various kernels
- Ensemble methods: AdaBoost, Voting, Stacking
- Neural Networks: MLPClassifier, MLPRegressor
- Others: Naive Bayes, K-Nearest Neighbors
When to use:
- Classification: Predicting discrete categories (spam detection, image classification, fraud detection)
- Regression: Predicting continuous values (price prediction, demand forecasting)
See: references/supervised_learning.md for detailed algorithm documentation, parameters, and usage examples.
2. Unsupervised Learning
Discover patterns in unlabeled data through clustering and dimensionality reduction.
Clustering algorithms:
- Partition-based: K-Means, MiniBatchKMeans
- Density-based: DBSCAN, HDBSCAN, OPTICS
- Hierarchical: AgglomerativeClustering
- Probabilistic: Gaussian Mixture Models
- Others: MeanShift, SpectralClustering, BIRCH
Dimensionality reduction:
- Linear: PCA, TruncatedSVD, NMF
- Manifold learning: t-SNE, UMAP, Isomap, LLE
- Feature extraction: FastICA, LatentDirichletAllocation
When to use:
- Customer segmentation, anomaly detection, data visualization
- Reducing feature dimensions, exploratory data analysis
- Topic modeling, image compression
See: references/unsupervised_learning.md for detailed documentation.
3. Model Evaluation and Selection
Tools for robust model evaluation, cross-validation, and hyperparameter tuning.
Cross-validation strategies:
- KFold, StratifiedKFold (classification)
- TimeSeriesSplit (temporal data)
- GroupKFold (grouped samples)
Hyperparameter tuning:
- GridSearchCV (exhaustive search)
- RandomizedSearchCV (random sampling)
- HalvingGridSearchCV (successive halving)
Metrics:
1---2name: scikit-learn3description: Machine learning in Python with scikit-learn. Use for classification, regression, clustering, model evaluation, and ML pipelines.4---567# Scikit-learn89## Overview1011This skill provides comprehensive guidance for machine learning tasks using scikit-learn, the industry-standard Python library for classical machine learning. Use this skill for classification, regression, clustering, dimensionality reduction, preprocessing, model evaluation, and building production-ready ML pipelines.1213## Installation1415```bash16# Install scikit-learn using uv17uv uv pip install scikit-learn1819# Optional: Install visualization dependencies20uv uv pip install matplotlib seaborn2122# Commonly used with23uv uv pip install pandas numpy24```2526## When to Use This Skill2728Use the scikit-learn skill when:2930- Building classification or regression models31- Performing clustering or dimensionality reduction32- Preprocessing and transforming data for machine learning33- Evaluating model performance with cross-validation34- Tuning hyperparameters with grid or random search35- Creating ML pipelines for production workflows36- Comparing different algorithms for a task37- Working with both structured (tabular) and text data38- Need interpretable, classical machine learning approaches3940## Quick Start4142### Classification Example4344```python45from sklearn.model_selection import train_test_split46from sklearn.preprocessing import StandardScaler47from sklearn.ensemble import RandomForestClassifier48from sklearn.metrics import classification_report4950# Split data51X_train, X_test, y_train, y_test = train_test_split(52 X, y, test_size=0.2, stratify=y, random_state=4253)5455# Preprocess56scaler = StandardScaler()57X_train_scaled = scaler.fit_transform(X_train)58X_test_scaled = scaler.transform(X_test)5960# Train model61model = RandomForestClassifier(n_estimators=100, random_state=42)62model.fit(X_train_scaled, y_train)6364# Evaluate65y_pred = model.predict(X_test_scaled)66print(classification_report(y_test, y_pred))67```6869### Complete Pipeline with Mixed Data7071```python72from sklearn.pipeline import Pipeline73from sklearn.compose import ColumnTransformer74from sklearn.preprocessing import StandardScaler, OneHotEncoder75from sklearn.impute import SimpleImputer76from sklearn.ensemble import GradientBoostingClassifier7778# Define feature types79numeric_features = ['age', 'income']80categorical_features = ['gender', 'occupation']8182# Create preprocessing pipelines83numeric_transformer = Pipeline([84 ('imputer', SimpleImputer(strategy='median')),85 ('scaler', StandardScaler())86])8788categorical_transformer = Pipeline([89 ('imputer', SimpleImputer(strategy='most_frequent')),90 ('onehot', OneHotEncoder(handle_unknown='ignore'))91])9293# Combine transformers94preprocessor = ColumnTransformer([95 ('num', numeric_transformer, numeric_features),96 ('cat', categorical_transformer, categorical_features)97])9899# Full pipeline100model = Pipeline([101 ('preprocessor', preprocessor),102 ('classifier', GradientBoostingClassifier(random_state=42))103])104105# Fit and predict106model.fit(X_train, y_train)107y_pred = model.predict(X_test)108```109110## Core Capabilities111112### 1. Supervised Learning113114Comprehensive algorithms for classification and regression tasks.115116**Key algorithms:**117- **Linear models**: Logistic Regression, Linear Regression, Ridge, Lasso, ElasticNet118- **Tree-based**: Decision Trees, Random Forest, Gradient Boosting119- **Support Vector Machines**: SVC, SVR with various kernels120- **Ensemble methods**: AdaBoost, Voting, Stacking121- **Neural Networks**: MLPClassifier, MLPRegressor122- **Others**: Naive Bayes, K-Nearest Neighbors123124**When to use:**125- Classification: Predicting discrete categories (spam detection, image classification, fraud detection)126- Regression: Predicting continuous values (price prediction, demand forecasting)127128**See:** `references/supervised_learning.md` for detailed algorithm documentation, parameters, and usage examples.129130### 2. Unsupervised Learning131132Discover patterns in unlabeled data through clustering and dimensionality reduction.133134**Clustering algorithms:**135- **Partition-based**: K-Means, MiniBatchKMeans136- **Density-based**: DBSCAN, HDBSCAN, OPTICS137- **Hierarchical**: AgglomerativeClustering138- **Probabilistic**: Gaussian Mixture Models139- **Others**: MeanShift, SpectralClustering, BIRCH140141**Dimensionality reduction:**142- **Linear**: PCA, TruncatedSVD, NMF143- **Manifold learning**: t-SNE, UMAP, Isomap, LLE144- **Feature extraction**: FastICA, LatentDirichletAllocation145146**When to use:**147- Customer segmentation, anomaly detection, data visualization148- Reducing feature dimensions, exploratory data analysis149- Topic modeling, image compression150151**See:** `references/unsupervised_learning.md` for detailed documentation.152153### 3. Model Evaluation and Selection154155Tools for robust model evaluation, cross-validation, and hyperparameter tuning.156157**Cross-validation strategies:**158- KFold, StratifiedKFold (classification)159- TimeSeriesSplit (temporal data)160- GroupKFold (grouped samples)161162**Hyperparameter tuning:**163- GridSearchCV (exhaustive search)164- RandomizedSearchCV (random sampling)165- HalvingGridSearchCV (successive halving)166167**Metrics:**168- **Cla