scikit-learn
Machine learning in Python with scikit-learn. Use when working with supervised learning (classification, regression), unsupervised learning (clustering, dimensionality reduction), model evaluation, hyperparameter tuning, preprocessing, or building ML pipelines. Provides comprehensive reference documentation for algorithms, preprocessing techniques, pipelines, and best practices.
Overview
Machine learning in Python with scikit-learn. Use when working with supervised learning (classification, regression), unsupervised learning (clustering, dimensionality reduction), model evaluation, hyperparameter tuning, preprocessing, or building ML pipelines. Provides comprehensive reference documentation for algorithms, preprocessing techniques, pipelines, and best practices.
Source: https://github.com/DenDen047/claude-scientific-skills · BSD-3-CLAUSE LICENSE · © 2025 K-Dense Inc.
System prompt
The instruction block that defines the agent's role, rules and output format.
# 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
```bash
# 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
```python
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
```python
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:**
- **Classification**: accuracy, precision, recall, F1-score, ROC AUC, confusion matrix
- **Regression**: MSE, RMSE, MAE, R², MAPE
- **Clustering**: silhouette score, Calinski-Harabasz, Davies-Bouldin
**When to use:**
- Comparing model performance objectively
- Finding optimal hyperparameters
- Preventing overfitting through cross-validation
- Understanding model behavior with learning curves
**See:** `references/model_evaluation.md` for comprehensive metrics and tuning strategies.
### 4. Data Preprocessing
Transform raw data into formats suitable for machine learning.
**Scaling and normalization:**
- StandardScaler (zero mean, unit variance)
- MinMaxScaler (bounded range)
- RobustScaler (robust to outliers)
- Normalizer (sample-wise normalization)
**Encoding categorical variables:**
- OneHotEncoder (nominal categories)
- OrdinalEncoder (ordered categories)
- LabelEncoder (target encoding)
**Handling missing values:**
- SimpleImputer (mean, median, most frequent)
- KNNImputer (k-nearest neighbors)
- IterativeImputer (multivariate imputation)
**Feature engineering:**
- PolynomialFeatures (interaction terms)
- KBinsDiscretizer (binning)
- Feature selection (RFE, SelectKBest, SelectFromModel)
**When to use:**
- Before training any algorithm that requires scaled features (SVM, KNN, Neural Networks)
- Converting categorical variables to numeric format
- Handling missing data systematically
- Creating non-linear features for linear models
**See:** `references/preprocessing.md` for detailed preprocessing techniques.
### 5. Pipelines and Composition
Build reproducible, production-ready ML workflows.
**Key components:**
- **Pipeline**: Chain transformers and estimators sequentially
- **ColumnTransformer**: Apply different preprocessing to different columns
- **FeatureUnion**: Combine multiple transformers in parallel
- **TransformedTargetRegressor**: Transform target variable
**Benefits:**
- Prevents data leakage in cross-validation
- Simplifies code and improves maintainability
- Enables joint hyperparameter tuning
- Ensures consistency between training and prediction
**When to use:**
- Always use Pipelines for production workflows
- When mixing numerical and categorical features (use ColumnTransformer)
- When performing cross-validation with preprocessing steps
- When hyperparameter tuning includes preprocessing parameters
**See:** `references/pipelines_and_composition.md` for comprehensive pipeline patterns.
## Example Scripts
### Classification Pipeline
Run a complete classification workflow with preprocessing, model comparison, hyperparameter tuning, and evaluation:
```bash
python scripts/classification_pipeline.py
```
This script demonstrates:
- Handling mixed data types (numeric and categorical)
- Model comparison using cross-validation
- Hyperparameter tuning with GridSearchCV
- Comprehensive evaluation with multiple metrics
- Feature importance analysis
### Clustering Analysis
Perform clustering analysis with algorithm comparison and visualization:
```bash
python scripts/clustering_analysis.py
```
This script demonstrates:
- Finding optimal number of clusters (elbow method, silhouette analysis)
- Comparing multiple clustering algorithms (K-Means, DBSCAN, Agglomerative, Gaussian Mixture)
- Evaluating clustering quality without ground truth
- Visualizing results with PCA projection
## Reference Documentation
This skill includes comprehensive reference files for deep dives into specific topics:
### Quick Reference
**File:** `references/quick_reference.md`
- Common import patterns and installation instructions
- Quick workflow templates for common tasks
- Algorithm selection cheat sheets
- Common patterns and gotchas
- Performance optimization tips
### Supervised Learning
**File:** `references/supervised_learning.md`
- Linear models (regression and classification)
- Support Vector Machines
- Decision Trees and ensemble methods
- K-Nearest Neighbors, Naive Bayes, Neural Networks
- Algorithm selection guide
### Unsupervised Learning
**File:** `references/unsupervised_learning.md`
- All clustering algorithms with parameters and use cases
- Dimensionality reduction techniques
- Outlier and novelty detection
- Gaussian Mixture Models
- Method selection guide
### Model Evaluation
**File:** `references/model_evaluation.md`
- Cross-validation strategies
- Hyperparameter tuning methods
- Classification, regression, and clustering metrics
- Learning and validation curves
- Best practices for model selection
### Preprocessing
**File:** `references/preprocessing.md`
- Feature scaling and normalization
- Encoding categorical variables
- Missing value imputation
- Feature engineering techniques
- Custom transformers
### Pipelines and Composition
**File:** `references/pipelines_and_composition.md`
- Pipeline construction and usage
- ColumnTransformer for mixed data types
- FeatureUnion for parallel transformations
- Complete end-to-end examples
- Best practices
## Common Workflows
### Building a Classification Model
1. **Load and explore data**
```python
import pandas as pd
df = pd.read_csv('data.csv')
X = df.drop('target', axis=1)
y = df['target']
```
2. **Split data with stratification**
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
```
3. **Create preprocessing pipeline**
```python
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
# Handle numeric and categorical features separately
preprocessor = ColumnTransformer([
('num', StandardScaler(), numeric_features),
('cat', OneHotEncoder(), categorical_features)
])
```
4. **Build complete pipeline**
```python
model = Pipeline([
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])
```
5. **Tune hyperparameters**
```python
from sklearn.model_selection import GridSearchCV
param_grid = {
'classifier__n_estimators': [100, 200],
'classifier__max_depth': [10, 20, None]
}
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X_train, y_train)
```
6. **Evaluate on test set**
```python
from sklearn.metrics import classification_report
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_test)
print(classification_report(y_test, y_pred))
```
### Performing Clustering Analysis
1. **Preprocess data**
```python
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
```
2. **Find optimal number of clusters**
```python
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
scores = []
for k in range(2, 11):
kmeans = KMeans(n_clusters=k, random_state=42)
labels = kmeans.fit_predict(X_scaled)
scores.append(silhouette_score(X_scaled, labels))
optimal_k = range(2, 11)[np.argmax(scores)]
```
3. **Apply clustering**
```python
model = KMeans(n_clusters=optimal_k, random_state=42)
labels = model.fit_predict(X_scaled)
```
4. **Visualize with dimensionality reduction**
```python
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis')
```
## Best Practices
### Always Use Pipelines
Pipelines prevent data leakage and ensure consistency:
```python
# Good: Preprocessing in pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('model', LogisticRegression())
])
# Bad: Preprocessing outside (can leak information)
X_scaled = StandardScaler().fit_transform(X)
```
### Fit on Training Data Only
Never fit on test data:
```python
# Good
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Only transform
# Bad
scaler = StandardScaler()
X_all_scaled = scaler.fit_transform(np.vstack([X_train, X_test]))
```
### Use Stratified Splitting for Classification
Preserve class distribution:
```python
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
```
### Set Random State for Reproducibility
```python
model = RandomForestClassifier(n_estimators=100, random_state=42)
```
### Choose Appropriate Metrics
- Balanced data: Accuracy, F1-score
- Imbalanced data: Precision, Recall, ROC AUC, Balanced Accuracy
- Cost-sensitive: Define custom scorer
### Scale Features When Required
Algorithms requiring feature scaling:
- SVM, KNN, Neural Networks
- PCA, Linear/Logistic Regression with regularization
- K-Means clustering
Algorithms not requiring scaling:
- Tree-based models (Decision Trees, Random Forest, Gradient Boosting)
- Naive Bayes
## Troubleshooting Common Issues
### ConvergenceWarning
**Issue:** Model didn't converge
**Solution:** Increase `max_iter` or scale features
```python
model = LogisticRegression(max_iter=1000)
```
### Poor Performance on Test Set
**Issue:** Overfitting
**Solution:** Use regularization, cross-validation, or simpler model
```python
# Add regularization
model = Ridge(alpha=1.0)
# Use cross-validation
scores = cross_val_score(model, X, y, cv=5)
```
### Memory Error with Large Datasets
**Solution:** Use algorithms designed for large data
```python
# Use SGD for large datasets
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
# Or MiniBatchKMeans for clustering
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=8, batch_size=100)
```
## Additional Resources
- Official Documentation: https://scikit-learn.org/stable/
- User Guide: https://scikit-learn.org/stable/user_guide.html
- API Reference: https://scikit-learn.org/stable/api/index.html
- Examples Gallery: https://scikit-learn.org/stable/auto_examples/index.html User prompt template
Fill in the variables and send it to run the skill: {{variables}}
Variables
| Name | Required | Description | Example |
|---|
Full skill configuration
The standard .aiskill file in JSON and YAML.
{
"format": "aiskill/v1",
"skill": {
"name": "scikit-learn",
"slug": "scikit-learn",
"version": "1.0.0",
"description": "Machine learning in Python with scikit-learn. Use when working with supervised learning (classification, regression), unsupervised learning (clustering, dimensionality reduction), model evaluation, hyperparameter tuning, preprocessing, or building ML pipelines. Provides comprehensive reference documentation for algorithms, preprocessing techniques, pipelines, and best practices.",
"category": "Research",
"tags": [
"research-science",
"python"
],
"platforms": [
"chatgpt",
"claude-code",
"cursor"
],
"tested_environment": "Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and compatible agents",
"license": "BSD-3-CLAUSE LICENSE"
},
"prompts": {
"system": "# Scikit-learn\r\n\r\n## Overview\r\n\r\nThis 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.\r\n\r\n## Installation\r\n\r\n```bash\r\n# Install scikit-learn using uv\r\nuv uv pip install scikit-learn\r\n\r\n# Optional: Install visualization dependencies\r\nuv uv pip install matplotlib seaborn\r\n\r\n# Commonly used with\r\nuv uv pip install pandas numpy\r\n```\r\n\r\n## When to Use This Skill\r\n\r\nUse the scikit-learn skill when:\r\n\r\n- Building classification or regression models\r\n- Performing clustering or dimensionality reduction\r\n- Preprocessing and transforming data for machine learning\r\n- Evaluating model performance with cross-validation\r\n- Tuning hyperparameters with grid or random search\r\n- Creating ML pipelines for production workflows\r\n- Comparing different algorithms for a task\r\n- Working with both structured (tabular) and text data\r\n- Need interpretable, classical machine learning approaches\r\n\r\n## Quick Start\r\n\r\n### Classification Example\r\n\r\n```python\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import classification_report\r\n\r\n# Split data\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n)\r\n\r\n# Preprocess\r\nscaler = StandardScaler()\r\nX_train_scaled = scaler.fit_transform(X_train)\r\nX_test_scaled = scaler.transform(X_test)\r\n\r\n# Train model\r\nmodel = RandomForestClassifier(n_estimators=100, random_state=42)\r\nmodel.fit(X_train_scaled, y_train)\r\n\r\n# Evaluate\r\ny_pred = model.predict(X_test_scaled)\r\nprint(classification_report(y_test, y_pred))\r\n```\r\n\r\n### Complete Pipeline with Mixed Data\r\n\r\n```python\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n\r\n# Define feature types\r\nnumeric_features = ['age', 'income']\r\ncategorical_features = ['gender', 'occupation']\r\n\r\n# Create preprocessing pipelines\r\nnumeric_transformer = Pipeline([\r\n ('imputer', SimpleImputer(strategy='median')),\r\n ('scaler', StandardScaler())\r\n])\r\n\r\ncategorical_transformer = Pipeline([\r\n ('imputer', SimpleImputer(strategy='most_frequent')),\r\n ('onehot', OneHotEncoder(handle_unknown='ignore'))\r\n])\r\n\r\n# Combine transformers\r\npreprocessor = ColumnTransformer([\r\n ('num', numeric_transformer, numeric_features),\r\n ('cat', categorical_transformer, categorical_features)\r\n])\r\n\r\n# Full pipeline\r\nmodel = Pipeline([\r\n ('preprocessor', preprocessor),\r\n ('classifier', GradientBoostingClassifier(random_state=42))\r\n])\r\n\r\n# Fit and predict\r\nmodel.fit(X_train, y_train)\r\ny_pred = model.predict(X_test)\r\n```\r\n\r\n## Core Capabilities\r\n\r\n### 1. Supervised Learning\r\n\r\nComprehensive algorithms for classification and regression tasks.\r\n\r\n**Key algorithms:**\r\n- **Linear models**: Logistic Regression, Linear Regression, Ridge, Lasso, ElasticNet\r\n- **Tree-based**: Decision Trees, Random Forest, Gradient Boosting\r\n- **Support Vector Machines**: SVC, SVR with various kernels\r\n- **Ensemble methods**: AdaBoost, Voting, Stacking\r\n- **Neural Networks**: MLPClassifier, MLPRegressor\r\n- **Others**: Naive Bayes, K-Nearest Neighbors\r\n\r\n**When to use:**\r\n- Classification: Predicting discrete categories (spam detection, image classification, fraud detection)\r\n- Regression: Predicting continuous values (price prediction, demand forecasting)\r\n\r\n**See:** `references/supervised_learning.md` for detailed algorithm documentation, parameters, and usage examples.\r\n\r\n### 2. Unsupervised Learning\r\n\r\nDiscover patterns in unlabeled data through clustering and dimensionality reduction.\r\n\r\n**Clustering algorithms:**\r\n- **Partition-based**: K-Means, MiniBatchKMeans\r\n- **Density-based**: DBSCAN, HDBSCAN, OPTICS\r\n- **Hierarchical**: AgglomerativeClustering\r\n- **Probabilistic**: Gaussian Mixture Models\r\n- **Others**: MeanShift, SpectralClustering, BIRCH\r\n\r\n**Dimensionality reduction:**\r\n- **Linear**: PCA, TruncatedSVD, NMF\r\n- **Manifold learning**: t-SNE, UMAP, Isomap, LLE\r\n- **Feature extraction**: FastICA, LatentDirichletAllocation\r\n\r\n**When to use:**\r\n- Customer segmentation, anomaly detection, data visualization\r\n- Reducing feature dimensions, exploratory data analysis\r\n- Topic modeling, image compression\r\n\r\n**See:** `references/unsupervised_learning.md` for detailed documentation.\r\n\r\n### 3. Model Evaluation and Selection\r\n\r\nTools for robust model evaluation, cross-validation, and hyperparameter tuning.\r\n\r\n**Cross-validation strategies:**\r\n- KFold, StratifiedKFold (classification)\r\n- TimeSeriesSplit (temporal data)\r\n- GroupKFold (grouped samples)\r\n\r\n**Hyperparameter tuning:**\r\n- GridSearchCV (exhaustive search)\r\n- RandomizedSearchCV (random sampling)\r\n- HalvingGridSearchCV (successive halving)\r\n\r\n**Metrics:**\r\n- **Classification**: accuracy, precision, recall, F1-score, ROC AUC, confusion matrix\r\n- **Regression**: MSE, RMSE, MAE, R², MAPE\r\n- **Clustering**: silhouette score, Calinski-Harabasz, Davies-Bouldin\r\n\r\n**When to use:**\r\n- Comparing model performance objectively\r\n- Finding optimal hyperparameters\r\n- Preventing overfitting through cross-validation\r\n- Understanding model behavior with learning curves\r\n\r\n**See:** `references/model_evaluation.md` for comprehensive metrics and tuning strategies.\r\n\r\n### 4. Data Preprocessing\r\n\r\nTransform raw data into formats suitable for machine learning.\r\n\r\n**Scaling and normalization:**\r\n- StandardScaler (zero mean, unit variance)\r\n- MinMaxScaler (bounded range)\r\n- RobustScaler (robust to outliers)\r\n- Normalizer (sample-wise normalization)\r\n\r\n**Encoding categorical variables:**\r\n- OneHotEncoder (nominal categories)\r\n- OrdinalEncoder (ordered categories)\r\n- LabelEncoder (target encoding)\r\n\r\n**Handling missing values:**\r\n- SimpleImputer (mean, median, most frequent)\r\n- KNNImputer (k-nearest neighbors)\r\n- IterativeImputer (multivariate imputation)\r\n\r\n**Feature engineering:**\r\n- PolynomialFeatures (interaction terms)\r\n- KBinsDiscretizer (binning)\r\n- Feature selection (RFE, SelectKBest, SelectFromModel)\r\n\r\n**When to use:**\r\n- Before training any algorithm that requires scaled features (SVM, KNN, Neural Networks)\r\n- Converting categorical variables to numeric format\r\n- Handling missing data systematically\r\n- Creating non-linear features for linear models\r\n\r\n**See:** `references/preprocessing.md` for detailed preprocessing techniques.\r\n\r\n### 5. Pipelines and Composition\r\n\r\nBuild reproducible, production-ready ML workflows.\r\n\r\n**Key components:**\r\n- **Pipeline**: Chain transformers and estimators sequentially\r\n- **ColumnTransformer**: Apply different preprocessing to different columns\r\n- **FeatureUnion**: Combine multiple transformers in parallel\r\n- **TransformedTargetRegressor**: Transform target variable\r\n\r\n**Benefits:**\r\n- Prevents data leakage in cross-validation\r\n- Simplifies code and improves maintainability\r\n- Enables joint hyperparameter tuning\r\n- Ensures consistency between training and prediction\r\n\r\n**When to use:**\r\n- Always use Pipelines for production workflows\r\n- When mixing numerical and categorical features (use ColumnTransformer)\r\n- When performing cross-validation with preprocessing steps\r\n- When hyperparameter tuning includes preprocessing parameters\r\n\r\n**See:** `references/pipelines_and_composition.md` for comprehensive pipeline patterns.\r\n\r\n## Example Scripts\r\n\r\n### Classification Pipeline\r\n\r\nRun a complete classification workflow with preprocessing, model comparison, hyperparameter tuning, and evaluation:\r\n\r\n```bash\r\npython scripts/classification_pipeline.py\r\n```\r\n\r\nThis script demonstrates:\r\n- Handling mixed data types (numeric and categorical)\r\n- Model comparison using cross-validation\r\n- Hyperparameter tuning with GridSearchCV\r\n- Comprehensive evaluation with multiple metrics\r\n- Feature importance analysis\r\n\r\n### Clustering Analysis\r\n\r\nPerform clustering analysis with algorithm comparison and visualization:\r\n\r\n```bash\r\npython scripts/clustering_analysis.py\r\n```\r\n\r\nThis script demonstrates:\r\n- Finding optimal number of clusters (elbow method, silhouette analysis)\r\n- Comparing multiple clustering algorithms (K-Means, DBSCAN, Agglomerative, Gaussian Mixture)\r\n- Evaluating clustering quality without ground truth\r\n- Visualizing results with PCA projection\r\n\r\n## Reference Documentation\r\n\r\nThis skill includes comprehensive reference files for deep dives into specific topics:\r\n\r\n### Quick Reference\r\n**File:** `references/quick_reference.md`\r\n- Common import patterns and installation instructions\r\n- Quick workflow templates for common tasks\r\n- Algorithm selection cheat sheets\r\n- Common patterns and gotchas\r\n- Performance optimization tips\r\n\r\n### Supervised Learning\r\n**File:** `references/supervised_learning.md`\r\n- Linear models (regression and classification)\r\n- Support Vector Machines\r\n- Decision Trees and ensemble methods\r\n- K-Nearest Neighbors, Naive Bayes, Neural Networks\r\n- Algorithm selection guide\r\n\r\n### Unsupervised Learning\r\n**File:** `references/unsupervised_learning.md`\r\n- All clustering algorithms with parameters and use cases\r\n- Dimensionality reduction techniques\r\n- Outlier and novelty detection\r\n- Gaussian Mixture Models\r\n- Method selection guide\r\n\r\n### Model Evaluation\r\n**File:** `references/model_evaluation.md`\r\n- Cross-validation strategies\r\n- Hyperparameter tuning methods\r\n- Classification, regression, and clustering metrics\r\n- Learning and validation curves\r\n- Best practices for model selection\r\n\r\n### Preprocessing\r\n**File:** `references/preprocessing.md`\r\n- Feature scaling and normalization\r\n- Encoding categorical variables\r\n- Missing value imputation\r\n- Feature engineering techniques\r\n- Custom transformers\r\n\r\n### Pipelines and Composition\r\n**File:** `references/pipelines_and_composition.md`\r\n- Pipeline construction and usage\r\n- ColumnTransformer for mixed data types\r\n- FeatureUnion for parallel transformations\r\n- Complete end-to-end examples\r\n- Best practices\r\n\r\n## Common Workflows\r\n\r\n### Building a Classification Model\r\n\r\n1. **Load and explore data**\r\n ```python\r\n import pandas as pd\r\n df = pd.read_csv('data.csv')\r\n X = df.drop('target', axis=1)\r\n y = df['target']\r\n ```\r\n\r\n2. **Split data with stratification**\r\n ```python\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n )\r\n ```\r\n\r\n3. **Create preprocessing pipeline**\r\n ```python\r\n from sklearn.pipeline import Pipeline\r\n from sklearn.preprocessing import StandardScaler\r\n from sklearn.compose import ColumnTransformer\r\n\r\n # Handle numeric and categorical features separately\r\n preprocessor = ColumnTransformer([\r\n ('num', StandardScaler(), numeric_features),\r\n ('cat', OneHotEncoder(), categorical_features)\r\n ])\r\n ```\r\n\r\n4. **Build complete pipeline**\r\n ```python\r\n model = Pipeline([\r\n ('preprocessor', preprocessor),\r\n ('classifier', RandomForestClassifier(random_state=42))\r\n ])\r\n ```\r\n\r\n5. **Tune hyperparameters**\r\n ```python\r\n from sklearn.model_selection import GridSearchCV\r\n\r\n param_grid = {\r\n 'classifier__n_estimators': [100, 200],\r\n 'classifier__max_depth': [10, 20, None]\r\n }\r\n\r\n grid_search = GridSearchCV(model, param_grid, cv=5)\r\n grid_search.fit(X_train, y_train)\r\n ```\r\n\r\n6. **Evaluate on test set**\r\n ```python\r\n from sklearn.metrics import classification_report\r\n\r\n best_model = grid_search.best_estimator_\r\n y_pred = best_model.predict(X_test)\r\n print(classification_report(y_test, y_pred))\r\n ```\r\n\r\n### Performing Clustering Analysis\r\n\r\n1. **Preprocess data**\r\n ```python\r\n from sklearn.preprocessing import StandardScaler\r\n\r\n scaler = StandardScaler()\r\n X_scaled = scaler.fit_transform(X)\r\n ```\r\n\r\n2. **Find optimal number of clusters**\r\n ```python\r\n from sklearn.cluster import KMeans\r\n from sklearn.metrics import silhouette_score\r\n\r\n scores = []\r\n for k in range(2, 11):\r\n kmeans = KMeans(n_clusters=k, random_state=42)\r\n labels = kmeans.fit_predict(X_scaled)\r\n scores.append(silhouette_score(X_scaled, labels))\r\n\r\n optimal_k = range(2, 11)[np.argmax(scores)]\r\n ```\r\n\r\n3. **Apply clustering**\r\n ```python\r\n model = KMeans(n_clusters=optimal_k, random_state=42)\r\n labels = model.fit_predict(X_scaled)\r\n ```\r\n\r\n4. **Visualize with dimensionality reduction**\r\n ```python\r\n from sklearn.decomposition import PCA\r\n\r\n pca = PCA(n_components=2)\r\n X_2d = pca.fit_transform(X_scaled)\r\n\r\n plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis')\r\n ```\r\n\r\n## Best Practices\r\n\r\n### Always Use Pipelines\r\nPipelines prevent data leakage and ensure consistency:\r\n```python\r\n# Good: Preprocessing in pipeline\r\npipeline = Pipeline([\r\n ('scaler', StandardScaler()),\r\n ('model', LogisticRegression())\r\n])\r\n\r\n# Bad: Preprocessing outside (can leak information)\r\nX_scaled = StandardScaler().fit_transform(X)\r\n```\r\n\r\n### Fit on Training Data Only\r\nNever fit on test data:\r\n```python\r\n# Good\r\nscaler = StandardScaler()\r\nX_train_scaled = scaler.fit_transform(X_train)\r\nX_test_scaled = scaler.transform(X_test) # Only transform\r\n\r\n# Bad\r\nscaler = StandardScaler()\r\nX_all_scaled = scaler.fit_transform(np.vstack([X_train, X_test]))\r\n```\r\n\r\n### Use Stratified Splitting for Classification\r\nPreserve class distribution:\r\n```python\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n)\r\n```\r\n\r\n### Set Random State for Reproducibility\r\n```python\r\nmodel = RandomForestClassifier(n_estimators=100, random_state=42)\r\n```\r\n\r\n### Choose Appropriate Metrics\r\n- Balanced data: Accuracy, F1-score\r\n- Imbalanced data: Precision, Recall, ROC AUC, Balanced Accuracy\r\n- Cost-sensitive: Define custom scorer\r\n\r\n### Scale Features When Required\r\nAlgorithms requiring feature scaling:\r\n- SVM, KNN, Neural Networks\r\n- PCA, Linear/Logistic Regression with regularization\r\n- K-Means clustering\r\n\r\nAlgorithms not requiring scaling:\r\n- Tree-based models (Decision Trees, Random Forest, Gradient Boosting)\r\n- Naive Bayes\r\n\r\n## Troubleshooting Common Issues\r\n\r\n### ConvergenceWarning\r\n**Issue:** Model didn't converge\r\n**Solution:** Increase `max_iter` or scale features\r\n```python\r\nmodel = LogisticRegression(max_iter=1000)\r\n```\r\n\r\n### Poor Performance on Test Set\r\n**Issue:** Overfitting\r\n**Solution:** Use regularization, cross-validation, or simpler model\r\n```python\r\n# Add regularization\r\nmodel = Ridge(alpha=1.0)\r\n\r\n# Use cross-validation\r\nscores = cross_val_score(model, X, y, cv=5)\r\n```\r\n\r\n### Memory Error with Large Datasets\r\n**Solution:** Use algorithms designed for large data\r\n```python\r\n# Use SGD for large datasets\r\nfrom sklearn.linear_model import SGDClassifier\r\nmodel = SGDClassifier()\r\n\r\n# Or MiniBatchKMeans for clustering\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nmodel = MiniBatchKMeans(n_clusters=8, batch_size=100)\r\n```\r\n\r\n## Additional Resources\r\n\r\n- Official Documentation: https://scikit-learn.org/stable/\r\n- User Guide: https://scikit-learn.org/stable/user_guide.html\r\n- API Reference: https://scikit-learn.org/stable/api/index.html\r\n- Examples Gallery: https://scikit-learn.org/stable/auto_examples/index.html",
"user_template": ""
},
"variables": [],
"install": {
"steps": [
{
"title": "Download & unzip",
"detail": "Download the .zip package from SkillVault and unzip it. The scikit-learn/ folder contains SKILL.md plus any companion scripts, references and assets."
},
{
"title": "Copy into your agent skills directory",
"detail": "Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session."
},
{
"title": "Use it",
"detail": "Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description."
}
]
},
"usage": {
"steps": []
},
"metadata": {
"author": "SkillVault",
"source": "https://skillvault.top/skills/scikit-learn",
"exported_at": "2026-11-03T07:41:23.829Z"
}
} format: aiskill/v1
skill:
name: scikit-learn
slug: scikit-learn
version: 1.0.0
description: >-
Machine learning in Python with scikit-learn. Use when working with supervised learning
(classification, regression), unsupervised learning (clustering, dimensionality reduction),
model evaluation, hyperparameter tuning, preprocessing, or building ML pipelines. Provides
comprehensive reference documentation for algorithms, preprocessing techniques, pipelines, and
best practices.
category: Research
tags:
- research-science
- python
platforms:
- chatgpt
- claude-code
- cursor
tested_environment: >-
Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and
compatible agents
license: BSD-3-CLAUSE LICENSE
prompts:
system: "# Scikit-learn\r\n\r\n## Overview\r\n\r\nThis 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.\r\n\r\n## Installation\r\n\r\n```bash\r\n# Install scikit-learn using uv\r\nuv uv pip install scikit-learn\r\n\r\n# Optional: Install visualization dependencies\r\nuv uv pip install matplotlib seaborn\r\n\r\n# Commonly used with\r\nuv uv pip install pandas numpy\r\n```\r\n\r\n## When to Use This Skill\r\n\r\nUse the scikit-learn skill when:\r\n\r\n- Building classification or regression models\r\n- Performing clustering or dimensionality reduction\r\n- Preprocessing and transforming data for machine learning\r\n- Evaluating model performance with cross-validation\r\n- Tuning hyperparameters with grid or random search\r\n- Creating ML pipelines for production workflows\r\n- Comparing different algorithms for a task\r\n- Working with both structured (tabular) and text data\r\n- Need interpretable, classical machine learning approaches\r\n\r\n## Quick Start\r\n\r\n### Classification Example\r\n\r\n```python\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import classification_report\r\n\r\n# Split data\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n)\r\n\r\n# Preprocess\r\nscaler = StandardScaler()\r\nX_train_scaled = scaler.fit_transform(X_train)\r\nX_test_scaled = scaler.transform(X_test)\r\n\r\n# Train model\r\nmodel = RandomForestClassifier(n_estimators=100, random_state=42)\r\nmodel.fit(X_train_scaled, y_train)\r\n\r\n# Evaluate\r\ny_pred = model.predict(X_test_scaled)\r\nprint(classification_report(y_test, y_pred))\r\n```\r\n\r\n### Complete Pipeline with Mixed Data\r\n\r\n```python\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n\r\n# Define feature types\r\nnumeric_features = ['age', 'income']\r\ncategorical_features = ['gender', 'occupation']\r\n\r\n# Create preprocessing pipelines\r\nnumeric_transformer = Pipeline([\r\n ('imputer', SimpleImputer(strategy='median')),\r\n ('scaler', StandardScaler())\r\n])\r\n\r\ncategorical_transformer = Pipeline([\r\n ('imputer', SimpleImputer(strategy='most_frequent')),\r\n ('onehot', OneHotEncoder(handle_unknown='ignore'))\r\n])\r\n\r\n# Combine transformers\r\npreprocessor = ColumnTransformer([\r\n ('num', numeric_transformer, numeric_features),\r\n ('cat', categorical_transformer, categorical_features)\r\n])\r\n\r\n# Full pipeline\r\nmodel = Pipeline([\r\n ('preprocessor', preprocessor),\r\n ('classifier', GradientBoostingClassifier(random_state=42))\r\n])\r\n\r\n# Fit and predict\r\nmodel.fit(X_train, y_train)\r\ny_pred = model.predict(X_test)\r\n```\r\n\r\n## Core Capabilities\r\n\r\n### 1. Supervised Learning\r\n\r\nComprehensive algorithms for classification and regression tasks.\r\n\r\n**Key algorithms:**\r\n- **Linear models**: Logistic Regression, Linear Regression, Ridge, Lasso, ElasticNet\r\n- **Tree-based**: Decision Trees, Random Forest, Gradient Boosting\r\n- **Support Vector Machines**: SVC, SVR with various kernels\r\n- **Ensemble methods**: AdaBoost, Voting, Stacking\r\n- **Neural Networks**: MLPClassifier, MLPRegressor\r\n- **Others**: Naive Bayes, K-Nearest Neighbors\r\n\r\n**When to use:**\r\n- Classification: Predicting discrete categories (spam detection, image classification, fraud detection)\r\n- Regression: Predicting continuous values (price prediction, demand forecasting)\r\n\r\n**See:** `references/supervised_learning.md` for detailed algorithm documentation, parameters, and usage examples.\r\n\r\n### 2. Unsupervised Learning\r\n\r\nDiscover patterns in unlabeled data through clustering and dimensionality reduction.\r\n\r\n**Clustering algorithms:**\r\n- **Partition-based**: K-Means, MiniBatchKMeans\r\n- **Density-based**: DBSCAN, HDBSCAN, OPTICS\r\n- **Hierarchical**: AgglomerativeClustering\r\n- **Probabilistic**: Gaussian Mixture Models\r\n- **Others**: MeanShift, SpectralClustering, BIRCH\r\n\r\n**Dimensionality reduction:**\r\n- **Linear**: PCA, TruncatedSVD, NMF\r\n- **Manifold learning**: t-SNE, UMAP, Isomap, LLE\r\n- **Feature extraction**: FastICA, LatentDirichletAllocation\r\n\r\n**When to use:**\r\n- Customer segmentation, anomaly detection, data visualization\r\n- Reducing feature dimensions, exploratory data analysis\r\n- Topic modeling, image compression\r\n\r\n**See:** `references/unsupervised_learning.md` for detailed documentation.\r\n\r\n### 3. Model Evaluation and Selection\r\n\r\nTools for robust model evaluation, cross-validation, and hyperparameter tuning.\r\n\r\n**Cross-validation strategies:**\r\n- KFold, StratifiedKFold (classification)\r\n- TimeSeriesSplit (temporal data)\r\n- GroupKFold (grouped samples)\r\n\r\n**Hyperparameter tuning:**\r\n- GridSearchCV (exhaustive search)\r\n- RandomizedSearchCV (random sampling)\r\n- HalvingGridSearchCV (successive halving)\r\n\r\n**Metrics:**\r\n- **Classification**: accuracy, precision, recall, F1-score, ROC AUC, confusion matrix\r\n- **Regression**: MSE, RMSE, MAE, R², MAPE\r\n- **Clustering**: silhouette score, Calinski-Harabasz, Davies-Bouldin\r\n\r\n**When to use:**\r\n- Comparing model performance objectively\r\n- Finding optimal hyperparameters\r\n- Preventing overfitting through cross-validation\r\n- Understanding model behavior with learning curves\r\n\r\n**See:** `references/model_evaluation.md` for comprehensive metrics and tuning strategies.\r\n\r\n### 4. Data Preprocessing\r\n\r\nTransform raw data into formats suitable for machine learning.\r\n\r\n**Scaling and normalization:**\r\n- StandardScaler (zero mean, unit variance)\r\n- MinMaxScaler (bounded range)\r\n- RobustScaler (robust to outliers)\r\n- Normalizer (sample-wise normalization)\r\n\r\n**Encoding categorical variables:**\r\n- OneHotEncoder (nominal categories)\r\n- OrdinalEncoder (ordered categories)\r\n- LabelEncoder (target encoding)\r\n\r\n**Handling missing values:**\r\n- SimpleImputer (mean, median, most frequent)\r\n- KNNImputer (k-nearest neighbors)\r\n- IterativeImputer (multivariate imputation)\r\n\r\n**Feature engineering:**\r\n- PolynomialFeatures (interaction terms)\r\n- KBinsDiscretizer (binning)\r\n- Feature selection (RFE, SelectKBest, SelectFromModel)\r\n\r\n**When to use:**\r\n- Before training any algorithm that requires scaled features (SVM, KNN, Neural Networks)\r\n- Converting categorical variables to numeric format\r\n- Handling missing data systematically\r\n- Creating non-linear features for linear models\r\n\r\n**See:** `references/preprocessing.md` for detailed preprocessing techniques.\r\n\r\n### 5. Pipelines and Composition\r\n\r\nBuild reproducible, production-ready ML workflows.\r\n\r\n**Key components:**\r\n- **Pipeline**: Chain transformers and estimators sequentially\r\n- **ColumnTransformer**: Apply different preprocessing to different columns\r\n- **FeatureUnion**: Combine multiple transformers in parallel\r\n- **TransformedTargetRegressor**: Transform target variable\r\n\r\n**Benefits:**\r\n- Prevents data leakage in cross-validation\r\n- Simplifies code and improves maintainability\r\n- Enables joint hyperparameter tuning\r\n- Ensures consistency between training and prediction\r\n\r\n**When to use:**\r\n- Always use Pipelines for production workflows\r\n- When mixing numerical and categorical features (use ColumnTransformer)\r\n- When performing cross-validation with preprocessing steps\r\n- When hyperparameter tuning includes preprocessing parameters\r\n\r\n**See:** `references/pipelines_and_composition.md` for comprehensive pipeline patterns.\r\n\r\n## Example Scripts\r\n\r\n### Classification Pipeline\r\n\r\nRun a complete classification workflow with preprocessing, model comparison, hyperparameter tuning, and evaluation:\r\n\r\n```bash\r\npython scripts/classification_pipeline.py\r\n```\r\n\r\nThis script demonstrates:\r\n- Handling mixed data types (numeric and categorical)\r\n- Model comparison using cross-validation\r\n- Hyperparameter tuning with GridSearchCV\r\n- Comprehensive evaluation with multiple metrics\r\n- Feature importance analysis\r\n\r\n### Clustering Analysis\r\n\r\nPerform clustering analysis with algorithm comparison and visualization:\r\n\r\n```bash\r\npython scripts/clustering_analysis.py\r\n```\r\n\r\nThis script demonstrates:\r\n- Finding optimal number of clusters (elbow method, silhouette analysis)\r\n- Comparing multiple clustering algorithms (K-Means, DBSCAN, Agglomerative, Gaussian Mixture)\r\n- Evaluating clustering quality without ground truth\r\n- Visualizing results with PCA projection\r\n\r\n## Reference Documentation\r\n\r\nThis skill includes comprehensive reference files for deep dives into specific topics:\r\n\r\n### Quick Reference\r\n**File:** `references/quick_reference.md`\r\n- Common import patterns and installation instructions\r\n- Quick workflow templates for common tasks\r\n- Algorithm selection cheat sheets\r\n- Common patterns and gotchas\r\n- Performance optimization tips\r\n\r\n### Supervised Learning\r\n**File:** `references/supervised_learning.md`\r\n- Linear models (regression and classification)\r\n- Support Vector Machines\r\n- Decision Trees and ensemble methods\r\n- K-Nearest Neighbors, Naive Bayes, Neural Networks\r\n- Algorithm selection guide\r\n\r\n### Unsupervised Learning\r\n**File:** `references/unsupervised_learning.md`\r\n- All clustering algorithms with parameters and use cases\r\n- Dimensionality reduction techniques\r\n- Outlier and novelty detection\r\n- Gaussian Mixture Models\r\n- Method selection guide\r\n\r\n### Model Evaluation\r\n**File:** `references/model_evaluation.md`\r\n- Cross-validation strategies\r\n- Hyperparameter tuning methods\r\n- Classification, regression, and clustering metrics\r\n- Learning and validation curves\r\n- Best practices for model selection\r\n\r\n### Preprocessing\r\n**File:** `references/preprocessing.md`\r\n- Feature scaling and normalization\r\n- Encoding categorical variables\r\n- Missing value imputation\r\n- Feature engineering techniques\r\n- Custom transformers\r\n\r\n### Pipelines and Composition\r\n**File:** `references/pipelines_and_composition.md`\r\n- Pipeline construction and usage\r\n- ColumnTransformer for mixed data types\r\n- FeatureUnion for parallel transformations\r\n- Complete end-to-end examples\r\n- Best practices\r\n\r\n## Common Workflows\r\n\r\n### Building a Classification Model\r\n\r\n1. **Load and explore data**\r\n ```python\r\n import pandas as pd\r\n df = pd.read_csv('data.csv')\r\n X = df.drop('target', axis=1)\r\n y = df['target']\r\n ```\r\n\r\n2. **Split data with stratification**\r\n ```python\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n )\r\n ```\r\n\r\n3. **Create preprocessing pipeline**\r\n ```python\r\n from sklearn.pipeline import Pipeline\r\n from sklearn.preprocessing import StandardScaler\r\n from sklearn.compose import ColumnTransformer\r\n\r\n # Handle numeric and categorical features separately\r\n preprocessor = ColumnTransformer([\r\n ('num', StandardScaler(), numeric_features),\r\n ('cat', OneHotEncoder(), categorical_features)\r\n ])\r\n ```\r\n\r\n4. **Build complete pipeline**\r\n ```python\r\n model = Pipeline([\r\n ('preprocessor', preprocessor),\r\n ('classifier', RandomForestClassifier(random_state=42))\r\n ])\r\n ```\r\n\r\n5. **Tune hyperparameters**\r\n ```python\r\n from sklearn.model_selection import GridSearchCV\r\n\r\n param_grid = {\r\n 'classifier__n_estimators': [100, 200],\r\n 'classifier__max_depth': [10, 20, None]\r\n }\r\n\r\n grid_search = GridSearchCV(model, param_grid, cv=5)\r\n grid_search.fit(X_train, y_train)\r\n ```\r\n\r\n6. **Evaluate on test set**\r\n ```python\r\n from sklearn.metrics import classification_report\r\n\r\n best_model = grid_search.best_estimator_\r\n y_pred = best_model.predict(X_test)\r\n print(classification_report(y_test, y_pred))\r\n ```\r\n\r\n### Performing Clustering Analysis\r\n\r\n1. **Preprocess data**\r\n ```python\r\n from sklearn.preprocessing import StandardScaler\r\n\r\n scaler = StandardScaler()\r\n X_scaled = scaler.fit_transform(X)\r\n ```\r\n\r\n2. **Find optimal number of clusters**\r\n ```python\r\n from sklearn.cluster import KMeans\r\n from sklearn.metrics import silhouette_score\r\n\r\n scores = []\r\n for k in range(2, 11):\r\n kmeans = KMeans(n_clusters=k, random_state=42)\r\n labels = kmeans.fit_predict(X_scaled)\r\n scores.append(silhouette_score(X_scaled, labels))\r\n\r\n optimal_k = range(2, 11)[np.argmax(scores)]\r\n ```\r\n\r\n3. **Apply clustering**\r\n ```python\r\n model = KMeans(n_clusters=optimal_k, random_state=42)\r\n labels = model.fit_predict(X_scaled)\r\n ```\r\n\r\n4. **Visualize with dimensionality reduction**\r\n ```python\r\n from sklearn.decomposition import PCA\r\n\r\n pca = PCA(n_components=2)\r\n X_2d = pca.fit_transform(X_scaled)\r\n\r\n plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis')\r\n ```\r\n\r\n## Best Practices\r\n\r\n### Always Use Pipelines\r\nPipelines prevent data leakage and ensure consistency:\r\n```python\r\n# Good: Preprocessing in pipeline\r\npipeline = Pipeline([\r\n ('scaler', StandardScaler()),\r\n ('model', LogisticRegression())\r\n])\r\n\r\n# Bad: Preprocessing outside (can leak information)\r\nX_scaled = StandardScaler().fit_transform(X)\r\n```\r\n\r\n### Fit on Training Data Only\r\nNever fit on test data:\r\n```python\r\n# Good\r\nscaler = StandardScaler()\r\nX_train_scaled = scaler.fit_transform(X_train)\r\nX_test_scaled = scaler.transform(X_test) # Only transform\r\n\r\n# Bad\r\nscaler = StandardScaler()\r\nX_all_scaled = scaler.fit_transform(np.vstack([X_train, X_test]))\r\n```\r\n\r\n### Use Stratified Splitting for Classification\r\nPreserve class distribution:\r\n```python\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.2, stratify=y, random_state=42\r\n)\r\n```\r\n\r\n### Set Random State for Reproducibility\r\n```python\r\nmodel = RandomForestClassifier(n_estimators=100, random_state=42)\r\n```\r\n\r\n### Choose Appropriate Metrics\r\n- Balanced data: Accuracy, F1-score\r\n- Imbalanced data: Precision, Recall, ROC AUC, Balanced Accuracy\r\n- Cost-sensitive: Define custom scorer\r\n\r\n### Scale Features When Required\r\nAlgorithms requiring feature scaling:\r\n- SVM, KNN, Neural Networks\r\n- PCA, Linear/Logistic Regression with regularization\r\n- K-Means clustering\r\n\r\nAlgorithms not requiring scaling:\r\n- Tree-based models (Decision Trees, Random Forest, Gradient Boosting)\r\n- Naive Bayes\r\n\r\n## Troubleshooting Common Issues\r\n\r\n### ConvergenceWarning\r\n**Issue:** Model didn't converge\r\n**Solution:** Increase `max_iter` or scale features\r\n```python\r\nmodel = LogisticRegression(max_iter=1000)\r\n```\r\n\r\n### Poor Performance on Test Set\r\n**Issue:** Overfitting\r\n**Solution:** Use regularization, cross-validation, or simpler model\r\n```python\r\n# Add regularization\r\nmodel = Ridge(alpha=1.0)\r\n\r\n# Use cross-validation\r\nscores = cross_val_score(model, X, y, cv=5)\r\n```\r\n\r\n### Memory Error with Large Datasets\r\n**Solution:** Use algorithms designed for large data\r\n```python\r\n# Use SGD for large datasets\r\nfrom sklearn.linear_model import SGDClassifier\r\nmodel = SGDClassifier()\r\n\r\n# Or MiniBatchKMeans for clustering\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nmodel = MiniBatchKMeans(n_clusters=8, batch_size=100)\r\n```\r\n\r\n## Additional Resources\r\n\r\n- Official Documentation: https://scikit-learn.org/stable/\r\n- User Guide: https://scikit-learn.org/stable/user_guide.html\r\n- API Reference: https://scikit-learn.org/stable/api/index.html\r\n- Examples Gallery: https://scikit-learn.org/stable/auto_examples/index.html"
user_template: ""
variables: []
install:
steps:
- title: Download & unzip
detail: >-
Download the .zip package from SkillVault and unzip it. The scikit-learn/ folder contains
SKILL.md plus any companion scripts, references and assets.
- title: Copy into your agent skills directory
detail: >-
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code),
.codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or
reload the session.
- title: Use it
detail: >-
Describe the task in natural language; the agent loads the skill automatically when the
request matches the skill description.
usage:
steps: []
metadata:
author: SkillVault
source: https://skillvault.top/skills/scikit-learn
exported_at: "2026-11-03T07:41:23.829Z"
Installation guide
- 1
Download & unzip
Download the .zip package from SkillVault and unzip it. The scikit-learn/ folder contains SKILL.md plus any companion scripts, references and assets.
- 2
Copy into your agent skills directory
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session.
- 3
Use it
Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description.
How to use
Platform compatibility
ChatGPT GPTs
OpenAI
Paste the system prompt into the GPT "Instructions" field and keep the user template as your starter message.
Official docsClaude Code
Anthropic
Save the exported .aiskill JSON as a skill file in your project or paste the system prompt into CLAUDE.md / a slash-command markdown file.
Official docsCursor
Anysphere
Copy the system prompt into .cursor/rules/*.mdc (or Project Rules in Settings) and reference the user template in your agent prompts.
Official docsRelated skills
astropy
Comprehensive Python library for astronomy and astrophysics. This skill should be used when working with astronomical data including celestial coordinates, physical units, FITS files, cosmological calculations, time systems, tables, world coordinate systems (WCS), and astronomical data analysis. Use when tasks involve coordinate transformations, unit conversions, FITS file manipulation, cosmological distance calculations, time scale conversions, or astronomical data processing.
fluidsim
Framework for computational fluid dynamics simulations using Python. Use when running fluid dynamics simulations including Navier-Stokes equations (2D/3D), shallow water equations, stratified flows, or when analyzing turbulence, vortex dynamics, or geophysical flows. Provides pseudospectral methods with FFT, HPC support, and comprehensive output analysis.
geomaster
Comprehensive geospatial science skill covering remote sensing, GIS, spatial analysis, machine learning for earth observation, and 30+ scientific domains. Supports satellite imagery processing (Sentinel, Landsat, MODIS, SAR, hyperspectral), vector and raster data operations, spatial statistics, point cloud processing, network analysis, cloud-native workflows (STAC, COG, Planetary Computer), and 8 programming languages (Python, R, Julia, JavaScript, C++, Java, Go, Rust) with 500+ code examples. Use for remote sensing workflows, GIS analysis, spatial ML, Earth observation data processing, terrain analysis, hydrological modeling, marine spatial analysis, atmospheric science, and any geospatial computation task.