Skill Tracer
Skills › Scientific Agent Skills › scikit-learn › quick_reference.md

quick_reference.md

446 lines · skills/scikit-learn/references/quick_reference.md at 5f2bc03

Open on GitHub
1# Scikit-learn Quick Reference
2
3Targets scikit-learn 1.9.1. Snippets with caller-supplied data/columns are illustrative; fit all learned preprocessing inside the training folds when estimating predictive performance.
4

Scikit-learn Quick Reference

Targets scikit-learn 1.9.1. Snippets with caller-supplied data/columns are illustrative; fit all learned preprocessing inside the training folds when estimating predictive performance.

Raw lines 1 to 4
5## Common Import Patterns
6
7```python
8# Core scikit-learn
9import sklearn
11# Data splitting and cross-validation
12from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
14# Preprocessing
15from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
16from sklearn.impute import SimpleImputer
18# Feature selection
19from sklearn.feature_selection import SelectKBest, RFE
21# Supervised learning
22from sklearn.linear_model import LogisticRegression, Ridge, Lasso
23from sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor
24from sklearn.svm import SVC, SVR
25from sklearn.tree import DecisionTreeClassifier
27# Unsupervised learning
28from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
29from sklearn.decomposition import PCA, NMF
31# Metrics
32from sklearn.metrics import (
33 accuracy_score, precision_score, recall_score, f1_score,
34 mean_squared_error, root_mean_squared_error, r2_score,
35 confusion_matrix, classification_report
38# Pipeline
39from sklearn.pipeline import Pipeline, make_pipeline
40from sklearn.compose import ColumnTransformer, make_column_transformer
42# Utilities
43import numpy as np
44import pandas as pd
45import matplotlib.pyplot as plt
46```

Common Import Patterns

# Core scikit-learn
import sklearn

# Data splitting and cross-validation
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV

# Preprocessing
from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

# Feature selection
from sklearn.feature_selection import SelectKBest, RFE

# Supervised learning
from sklearn.linear_model import LogisticRegression, Ridge, Lasso
from sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor
from sklearn.svm import SVC, SVR
from sklearn.tree import DecisionTreeClassifier

# Unsupervised learning
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.decomposition import PCA, NMF

# Metrics
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    mean_squared_error, root_mean_squared_error, r2_score,
    confusion_matrix, classification_report
)

# Pipeline
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.compose import ColumnTransformer, make_column_transformer

# Utilities
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Raw lines 5 to 47
48## Installation
50Targets scikit-learn **1.9.1** (tested on Python 3.13; requires Python 3.11+). Install the PyPI package `scikit-learn` (import as `sklearn`).
52```bash
53# Using uv (recommended)
54uv pip install "scikit-learn==1.9.1"
56# Optional dependencies
57uv pip install "scikit-learn[plots]==1.9.1" # For plotting utilities
58uv pip install pandas numpy matplotlib seaborn # Common companions
59```

Installation

Targets scikit-learn 1.9.1 (tested on Python 3.13; requires Python 3.11+). Install the PyPI package scikit-learn (import as sklearn).

# Using uv (recommended)
uv pip install "scikit-learn==1.9.1"

# Optional dependencies
uv pip install "scikit-learn[plots]==1.9.1"  # For plotting utilities
uv pip install pandas numpy matplotlib seaborn  # Common companions
Raw lines 48 to 60
61## Quick Workflow Templates

Quick Workflow Templates

Raw lines 61 to 62
63### Classification Pipeline
65```python
66from sklearn.model_selection import train_test_split
67from sklearn.preprocessing import StandardScaler
68from sklearn.ensemble import RandomForestClassifier
69from sklearn.metrics import classification_report, confusion_matrix
71# Split data
72X_train, X_test, y_train, y_test = train_test_split(
73 X, y, test_size=0.2, stratify=y, random_state=42
76# Preprocess
77scaler = StandardScaler()
78X_train_scaled = scaler.fit_transform(X_train)
79X_test_scaled = scaler.transform(X_test)
81# Train
82model = RandomForestClassifier(n_estimators=100, random_state=42)
83model.fit(X_train_scaled, y_train)
85# Evaluate
86y_pred = model.predict(X_test_scaled)
87print(classification_report(y_test, y_pred))
88print(confusion_matrix(y_test, y_pred))
89```

Classification Pipeline

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

# 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 = 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))
print(confusion_matrix(y_test, y_pred))
Raw lines 63 to 90
91### Regression Pipeline
93```python
94from sklearn.model_selection import train_test_split
95from sklearn.preprocessing import StandardScaler
96from sklearn.ensemble import GradientBoostingRegressor
97from sklearn.metrics import mean_squared_error, root_mean_squared_error, r2_score
99# Split
100X_train, X_test, y_train, y_test = train_test_split(
101 X, y, test_size=0.2, random_state=42
104# Preprocess and train
105scaler = StandardScaler()
106X_train_scaled = scaler.fit_transform(X_train)
107X_test_scaled = scaler.transform(X_test)
109model = GradientBoostingRegressor(n_estimators=100, random_state=42)
110model.fit(X_train_scaled, y_train)
112# Evaluate
113y_pred = model.predict(X_test_scaled)
114print(f"RMSE: {root_mean_squared_error(y_test, y_pred):.3f}")
115print(f"R² Score: {r2_score(y_test, y_pred):.3f}")
116```

Regression Pipeline

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, root_mean_squared_error, r2_score

# Split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Preprocess and train
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

model = GradientBoostingRegressor(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

# Evaluate
y_pred = model.predict(X_test_scaled)
print(f"RMSE: {root_mean_squared_error(y_test, y_pred):.3f}")
print(f"R² Score: {r2_score(y_test, y_pred):.3f}")
Raw lines 91 to 117
118### Cross-Validation
120```python
121from sklearn.model_selection import cross_val_score
122from sklearn.ensemble import RandomForestClassifier
124model = RandomForestClassifier(n_estimators=100, random_state=42)
125scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
126print(f"CV Accuracy: {scores.mean():.3f} (fold SD {scores.std():.3f})")
127```

Cross-Validation

from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(n_estimators=100, random_state=42)
scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
print(f"CV Accuracy: {scores.mean():.3f} (fold SD {scores.std():.3f})")
Raw lines 118 to 128
129### Complete Pipeline with Mixed Data Types
131```python
132from sklearn.pipeline import Pipeline
133from sklearn.compose import ColumnTransformer
134from sklearn.preprocessing import StandardScaler, OneHotEncoder
135from sklearn.impute import SimpleImputer
136from sklearn.ensemble import RandomForestClassifier
138# Define feature types
139numeric_features = ['age', 'income']
140categorical_features = ['gender', 'occupation']
142# Create preprocessing pipelines
143numeric_transformer = Pipeline([
144 ('imputer', SimpleImputer(strategy='median')),
145 ('scaler', StandardScaler())
146])
148categorical_transformer = Pipeline([
149 ('imputer', SimpleImputer(strategy='most_frequent')),
150 ('onehot', OneHotEncoder(handle_unknown='ignore'))
151])
153# Combine transformers
154preprocessor = ColumnTransformer([
155 ('num', numeric_transformer, numeric_features),
156 ('cat', categorical_transformer, categorical_features)
157])
159# Full pipeline
160model = Pipeline([
161 ('preprocessor', preprocessor),
162 ('classifier', RandomForestClassifier(n_estimators=100, random_state=42))
163])
165# Fit and predict
166model.fit(X_train, y_train)
167y_pred = model.predict(X_test)
168```

Complete Pipeline with Mixed Data Types

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 RandomForestClassifier

# 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', RandomForestClassifier(n_estimators=100, random_state=42))
])

# Fit and predict
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Raw lines 129 to 169
170### Hyperparameter Tuning
172```python
173from sklearn.model_selection import GridSearchCV
174from sklearn.ensemble import RandomForestClassifier
176param_grid = {
177 'n_estimators': [100, 200, 300],
178 'max_depth': [10, 20, None],
179 'min_samples_split': [2, 5, 10]
182model = RandomForestClassifier(random_state=42)
183grid_search = GridSearchCV(
184 model, param_grid, cv=5, scoring='accuracy', n_jobs=-1
187grid_search.fit(X_train, y_train)
188print(f"Best params: {grid_search.best_params_}")
189print(f"Best score: {grid_search.best_score_:.3f}")
191# Use best model
192best_model = grid_search.best_estimator_
193```

Hyperparameter Tuning

from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier

param_grid = {
    'n_estimators': [100, 200, 300],
    'max_depth': [10, 20, None],
    'min_samples_split': [2, 5, 10]
}

model = RandomForestClassifier(random_state=42)
grid_search = GridSearchCV(
    model, param_grid, cv=5, scoring='accuracy', n_jobs=-1
)

grid_search.fit(X_train, y_train)
print(f"Best params: {grid_search.best_params_}")
print(f"Best score: {grid_search.best_score_:.3f}")

# Use best model
best_model = grid_search.best_estimator_
Raw lines 170 to 194
195## Common Patterns

Common Patterns

Raw lines 195 to 196
197### Loading Data
199```python
200# From scikit-learn datasets
201from sklearn.datasets import load_iris, load_digits, make_classification
203# Built-in datasets
204iris = load_iris()
205X, y = iris.data, iris.target
207# Synthetic data
208X, y = make_classification(
209 n_samples=1000, n_features=20, n_classes=2, random_state=42
212# From pandas
213import pandas as pd
214df = pd.read_csv('data.csv')
215X = df.drop('target', axis=1)
216y = df['target']
217```

Loading Data

# From scikit-learn datasets
from sklearn.datasets import load_iris, load_digits, make_classification

# Built-in datasets
iris = load_iris()
X, y = iris.data, iris.target

# Synthetic data
X, y = make_classification(
    n_samples=1000, n_features=20, n_classes=2, random_state=42
)

# From pandas
import pandas as pd
df = pd.read_csv('data.csv')
X = df.drop('target', axis=1)
y = df['target']
Raw lines 197 to 218
219### Handling Imbalanced Data
221```python
222from sklearn.ensemble import RandomForestClassifier
224# Use class_weight parameter
225model = RandomForestClassifier(class_weight='balanced', random_state=42)
226model.fit(X_train, y_train)
228# Or use appropriate metrics
229from sklearn.metrics import balanced_accuracy_score, f1_score
230print(f"Balanced Accuracy: {balanced_accuracy_score(y_test, y_pred):.3f}")
231print(f"F1 Score: {f1_score(y_test, y_pred):.3f}")
232```

Handling Imbalanced Data

from sklearn.ensemble import RandomForestClassifier

# Use class_weight parameter
model = RandomForestClassifier(class_weight='balanced', random_state=42)
model.fit(X_train, y_train)

# Or use appropriate metrics
from sklearn.metrics import balanced_accuracy_score, f1_score
print(f"Balanced Accuracy: {balanced_accuracy_score(y_test, y_pred):.3f}")
print(f"F1 Score: {f1_score(y_test, y_pred):.3f}")
Raw lines 219 to 233
234### Feature Importance
236```python
237from sklearn.ensemble import RandomForestClassifier
238import pandas as pd
240model = RandomForestClassifier(n_estimators=100, random_state=42)
241model.fit(X_train, y_train)
243# Get feature importances
244importances = pd.DataFrame({
245 'feature': feature_names,
246 'importance': model.feature_importances_
247}).sort_values('importance', ascending=False)
249print(importances.head(10))
250```

Feature Importance

from sklearn.ensemble import RandomForestClassifier
import pandas as pd

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Get feature importances
importances = pd.DataFrame({
    'feature': feature_names,
    'importance': model.feature_importances_
}).sort_values('importance', ascending=False)

print(importances.head(10))
Raw lines 234 to 251
252### Clustering
254```python
255from sklearn.cluster import KMeans
256from sklearn.preprocessing import StandardScaler
258# Scale data first
259scaler = StandardScaler()
260X_scaled = scaler.fit_transform(X)
262# Fit K-Means
263kmeans = KMeans(n_clusters=3, random_state=42)
264labels = kmeans.fit_predict(X_scaled)
266# Evaluate
267from sklearn.metrics import silhouette_score
268score = silhouette_score(X_scaled, labels)
269print(f"Silhouette Score: {score:.3f}")
270```

Clustering

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# Scale data first
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Fit K-Means
kmeans = KMeans(n_clusters=3, random_state=42)
labels = kmeans.fit_predict(X_scaled)

# Evaluate
from sklearn.metrics import silhouette_score
score = silhouette_score(X_scaled, labels)
print(f"Silhouette Score: {score:.3f}")
Raw lines 252 to 271
272### Dimensionality Reduction
274```python
275from sklearn.decomposition import PCA
276import matplotlib.pyplot as plt
278# Fit PCA
279pca = PCA(n_components=2)
280X_reduced = pca.fit_transform(X)
282# Plot
283plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='viridis')
284plt.xlabel('PC1')
285plt.ylabel('PC2')
286plt.title(f'PCA (explained variance: {pca.explained_variance_ratio_.sum():.2%})')
287```

Dimensionality Reduction

from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# Fit PCA
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)

# Plot
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='viridis')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.title(f'PCA (explained variance: {pca.explained_variance_ratio_.sum():.2%})')
Raw lines 272 to 288
289### Model Persistence
291Load pickle/joblib artifacts only from a trusted source: loading can execute code. Persist the fitted pipeline and training schema, package versions, and evaluation provenance. Loading across different scikit-learn versions is unsupported.
293```python
294import joblib
296# Save model
297joblib.dump(model, 'model.pkl')
299# Load model
300loaded_model = joblib.load('model.pkl')
301predictions = loaded_model.predict(X_new)
302```

Model Persistence

Load pickle/joblib artifacts only from a trusted source: loading can execute code. Persist the fitted pipeline and training schema, package versions, and evaluation provenance. Loading across different scikit-learn versions is unsupported.

import joblib

# Save model
joblib.dump(model, 'model.pkl')

# Load model
loaded_model = joblib.load('model.pkl')
predictions = loaded_model.predict(X_new)
Raw lines 289 to 303
304## Common Gotchas and Solutions

Common Gotchas and Solutions

Raw lines 304 to 305
306### Data Leakage
307```python
308# WRONG: Fitting scaler on all data
309scaler = StandardScaler()
310X_scaled = scaler.fit_transform(X)
311X_train, X_test = train_test_split(X_scaled)
313# RIGHT: Fit on training data only
314X_train, X_test = train_test_split(X)
315scaler = StandardScaler()
316X_train_scaled = scaler.fit_transform(X_train)
317X_test_scaled = scaler.transform(X_test)
319# BEST: Use Pipeline
320from sklearn.pipeline import Pipeline
321pipeline = Pipeline([
322 ('scaler', StandardScaler()),
323 ('model', LogisticRegression())
324])
325pipeline.fit(X_train, y_train) # Then pass this entire pipeline to CV/search
326```

Data Leakage

# WRONG: Fitting scaler on all data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test = train_test_split(X_scaled)

# RIGHT: Fit on training data only
X_train, X_test = train_test_split(X)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# BEST: Use Pipeline
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('model', LogisticRegression())
])
pipeline.fit(X_train, y_train)  # Then pass this entire pipeline to CV/search
Raw lines 306 to 327
328### Stratified Splitting for Classification
329```python
330# For independent classification rows; groups/time need appropriate splitters
331X_train, X_test, y_train, y_test = train_test_split(
332 X, y, test_size=0.2, stratify=y, random_state=42
334```

Stratified Splitting for Classification

# For independent classification rows; groups/time need appropriate splitters
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)
Raw lines 328 to 335
336### Random State for Reproducibility
337```python
338# Set random_state for reproducibility
339model = RandomForestClassifier(n_estimators=100, random_state=42)
340```

Random State for Reproducibility

# Set random_state for reproducibility
model = RandomForestClassifier(n_estimators=100, random_state=42)
Raw lines 336 to 341
342### Handling Unknown Categories
343```python
344# Use handle_unknown='ignore' for OneHotEncoder
345encoder = OneHotEncoder(handle_unknown='ignore')
346```

Handling Unknown Categories

# Use handle_unknown='ignore' for OneHotEncoder
encoder = OneHotEncoder(handle_unknown='ignore')
Raw lines 342 to 347
348### Feature Names with Pipelines
349```python
350# Get feature names after transformation
351preprocessor.fit(X_train)
352feature_names = preprocessor.get_feature_names_out()
353```

Feature Names with Pipelines

# Get feature names after transformation
preprocessor.fit(X_train)
feature_names = preprocessor.get_feature_names_out()
Raw lines 348 to 354
355## Cheat Sheet: Algorithm Selection

Cheat Sheet: Algorithm Selection

Raw lines 355 to 356
357### Classification
359| Problem | Algorithm | When to Use |
360|---------|-----------|-------------|
361| Binary/Multiclass | Logistic Regression | Fast baseline, interpretability |
362| Binary/Multiclass | Random Forest | Good default, robust |
363| Binary/Multiclass | Gradient Boosting | Strong candidate, validate and tune |
364| Binary/Multiclass | SVM | Small data, complex boundaries |
365| Binary/Multiclass | Naive Bayes | Text classification, fast |
366| High dimensions | Linear SVM or Logistic | Text, many features |

Classification

ProblemAlgorithmWhen to Use
Binary/MulticlassLogistic RegressionFast baseline, interpretability
Binary/MulticlassRandom ForestGood default, robust
Binary/MulticlassGradient BoostingStrong candidate, validate and tune
Binary/MulticlassSVMSmall data, complex boundaries
Binary/MulticlassNaive BayesText classification, fast
High dimensionsLinear SVM or LogisticText, many features
Raw lines 357 to 367
368### Regression
370| Problem | Algorithm | When to Use |
371|---------|-----------|-------------|
372| Continuous target | Linear Regression | Fast baseline, interpretability |
373| Continuous target | Ridge/Lasso | Regularization needed |
374| Continuous target | Random Forest | Good default, non-linear |
375| Continuous target | Gradient Boosting | Candidate to compare |
376| Continuous target | SVR | Small data, non-linear |

Regression

ProblemAlgorithmWhen to Use
Continuous targetLinear RegressionFast baseline, interpretability
Continuous targetRidge/LassoRegularization needed
Continuous targetRandom ForestGood default, non-linear
Continuous targetGradient BoostingCandidate to compare
Continuous targetSVRSmall data, non-linear
Raw lines 368 to 377
378### Clustering
380| Problem | Algorithm | When to Use |
381|---------|-----------|-------------|
382| Known K, spherical | K-Means | Fast, simple |
383| Unknown K, arbitrary shapes | DBSCAN | Noise/outliers present |
384| Hierarchical structure | Agglomerative | Need dendrogram |
385| Soft clustering | Gaussian Mixture | Probability estimates |

Clustering

ProblemAlgorithmWhen to Use
Known K, sphericalK-MeansFast, simple
Unknown K, arbitrary shapesDBSCANNoise/outliers present
Hierarchical structureAgglomerativeNeed dendrogram
Soft clusteringGaussian MixtureProbability estimates
Raw lines 378 to 386
387### Dimensionality Reduction
389| Problem | Algorithm | When to Use |
390|---------|-----------|-------------|
391| Linear reduction | PCA | Variance explanation |
392| Visualization | t-SNE | 2D/3D plots |
393| Non-negative data | NMF | Images, text |
394| Sparse data | TruncatedSVD | Text, recommender systems |

Dimensionality Reduction

ProblemAlgorithmWhen to Use
Linear reductionPCAVariance explanation
Visualizationt-SNE2D/3D plots
Non-negative dataNMFImages, text
Sparse dataTruncatedSVDText, recommender systems
Raw lines 387 to 395
396## Performance Tips

Performance Tips

Raw lines 396 to 397
398### Speed Up Training
399```python
400# Use n_jobs=-1 for parallel processing
401model = RandomForestClassifier(n_estimators=100, n_jobs=-1)
403# Grow the same fitted forest on the same training data; not online learning
404model = RandomForestClassifier(n_estimators=100, warm_start=True)
405model.fit(X, y)
406model.n_estimators += 50
407model.fit(X, y) # Adds 50 more trees
409# Use partial_fit for online learning
410from sklearn.linear_model import SGDClassifier
411model = SGDClassifier()
412for X_batch, y_batch in batches:
413 model.partial_fit(X_batch, y_batch, classes=np.unique(y))
414```

Speed Up Training

# Use n_jobs=-1 for parallel processing
model = RandomForestClassifier(n_estimators=100, n_jobs=-1)

# Grow the same fitted forest on the same training data; not online learning
model = RandomForestClassifier(n_estimators=100, warm_start=True)
model.fit(X, y)
model.n_estimators += 50
model.fit(X, y)  # Adds 50 more trees

# Use partial_fit for online learning
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
for X_batch, y_batch in batches:
    model.partial_fit(X_batch, y_batch, classes=np.unique(y))
Raw lines 398 to 415
416### Memory Efficiency
417```python
418# Use sparse matrices
419from scipy.sparse import csr_matrix
420X_sparse = csr_matrix(X)
422# Use MiniBatchKMeans for large data
423from sklearn.cluster import MiniBatchKMeans
424model = MiniBatchKMeans(n_clusters=8, batch_size=100)
425```

Memory Efficiency

# Use sparse matrices
from scipy.sparse import csr_matrix
X_sparse = csr_matrix(X)

# Use MiniBatchKMeans for large data
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=8, batch_size=100)
Raw lines 416 to 426
427## Version Check
429```python
430import sklearn
431print(f"scikit-learn version: {sklearn.__version__}")
432```

Version Check

import sklearn
print(f"scikit-learn version: {sklearn.__version__}")
Raw lines 427 to 433
434## Useful Resources
436- Official Documentation: https://scikit-learn.org/stable/
437- User Guide: https://scikit-learn.org/stable/user_guide.html
438- API Reference: https://scikit-learn.org/stable/api/index.html
439- Examples: https://scikit-learn.org/stable/auto_examples/index.html
440- Tutorials: https://scikit-learn.org/stable/getting_started.html

Useful 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: https://scikit-learn.org/stable/auto_examples/index.html
  • Tutorials: https://scikit-learn.org/stable/getting_started.html
Raw lines 434 to 441
442## Upstream references
444- https://scikit-learn.org/stable/whats_new/v1.9.html
445- https://scikit-learn.org/stable/common_pitfalls.html
446- https://scikit-learn.org/stable/model_persistence.html

Upstream references

  • https://scikit-learn.org/stable/whats_new/v1.9.html
  • https://scikit-learn.org/stable/common_pitfalls.html
  • https://scikit-learn.org/stable/model_persistence.html
Raw lines 442 to 446