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

common_workflows.md

125 lines · skills/scikit-learn/references/common_workflows.md at 5f2bc03

Open on GitHub
1# Common Workflows
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
5Two worked end-to-end workflows: building a classification model and performing a
6clustering analysis.
7

Common Workflows

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.

Two worked end-to-end workflows: building a classification model and performing a clustering analysis.

Raw lines 1 to 7
8## Common Workflows
9

Common Workflows

Raw lines 8 to 9
10### Building a Classification Model
121. **Load and explore data**
13 ```python
14 import pandas as pd
15 df = pd.read_csv('data.csv')
16 X = df.drop('target', axis=1)
17 y = df['target']
18 ```
202. **Split data with stratification**
21 ```python
22 from sklearn.model_selection import train_test_split
23 X_train, X_test, y_train, y_test = train_test_split(
24 X, y, test_size=0.2, stratify=y, random_state=42
25 )
26 ```
283. **Create preprocessing pipeline**
29 ```python
30 from sklearn.pipeline import Pipeline
31 from sklearn.preprocessing import StandardScaler, OneHotEncoder
32 from sklearn.ensemble import RandomForestClassifier
33 from sklearn.compose import ColumnTransformer
35 # Choose these using the training schema; exclude target/identifiers.
36 numeric_features = X_train.select_dtypes(include='number').columns.tolist()
37 categorical_features = X_train.columns.difference(numeric_features).tolist()
38 # This minimal example assumes no missing values.
39 # Handle numeric and categorical features separately
40 preprocessor = ColumnTransformer([
41 ('num', StandardScaler(), numeric_features),
42 ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)
43 ])
44 ```
464. **Build complete pipeline**
47 ```python
48 model = Pipeline([
49 ('preprocessor', preprocessor),
50 ('classifier', RandomForestClassifier(random_state=42))
51 ])
52 ```
545. **Tune hyperparameters**
55 ```python
56 from sklearn.model_selection import GridSearchCV
58 param_grid = {
59 'classifier__n_estimators': [100, 200],
60 'classifier__max_depth': [10, 20, None]
61 }
63 grid_search = GridSearchCV(model, param_grid, cv=5)
64 grid_search.fit(X_train, y_train)
65 ```
676. **Evaluate on test set**
68 ```python
69 from sklearn.metrics import classification_report
71 best_model = grid_search.best_estimator_
72 y_pred = best_model.predict(X_test)
73 print(classification_report(y_test, y_pred))
74 ```

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']
  1. 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 )
  1. Create preprocessing pipeline ```python from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer

# Choose these using the training schema; exclude target/identifiers. numeric_features = X_train.select_dtypes(include='number').columns.tolist() categorical_features = X_train.columns.difference(numeric_features).tolist() # This minimal example assumes no missing values. # Handle numeric and categorical features separately preprocessor = ColumnTransformer([ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features) ]) ```

  1. Build complete pipeline ``python model = Pipeline([ ('preprocessor', preprocessor), ('classifier', RandomForestClassifier(random_state=42)) ])
  1. 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) ```

  1. 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)) ```

Raw lines 10 to 75
76### Performing Clustering Analysis
781. **Preprocess data**
79 ```python
80 from sklearn.preprocessing import StandardScaler
82 scaler = StandardScaler()
83 X_scaled = scaler.fit_transform(X)
84 ```
862. **Explore candidate cluster counts**
87 ```python
88 from sklearn.cluster import KMeans
89 from sklearn.metrics import silhouette_score
91 import numpy as np
92 scores = []
93 candidates = range(2, min(11, len(X_scaled)))
94 for k in candidates:
95 kmeans = KMeans(n_clusters=k, n_init=10, random_state=42)
96 labels = kmeans.fit_predict(X_scaled)
97 scores.append(silhouette_score(X_scaled, labels)
98 if 2 <= len(np.unique(labels)) < len(labels) else np.nan)
100 if not scores or not np.isfinite(scores).any():
101 raise ValueError("No valid silhouette candidate")
102 optimal_k = candidates[int(np.nanargmax(scores))] # Exploratory candidate only
103 ```
1053. **Apply clustering**
106 ```python
107 model = KMeans(n_clusters=optimal_k, random_state=42)
108 labels = model.fit_predict(X_scaled)
109 ```
1114. **Visualize with dimensionality reduction**
112 ```python
113 from sklearn.decomposition import PCA
114 import matplotlib.pyplot as plt
116 pca = PCA(n_components=2)
117 X_2d = pca.fit_transform(X_scaled)
119 plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis')
120 ```

Performing Clustering Analysis

  1. Preprocess data ```python from sklearn.preprocessing import StandardScaler

scaler = StandardScaler() X_scaled = scaler.fit_transform(X) ```

  1. Explore candidate cluster counts ```python from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score

import numpy as np scores = [] candidates = range(2, min(11, len(X_scaled))) for k in candidates: kmeans = KMeans(n_clusters=k, n_init=10, random_state=42) labels = kmeans.fit_predict(X_scaled) scores.append(silhouette_score(X_scaled, labels) if 2 <= len(np.unique(labels)) < len(labels) else np.nan)

if not scores or not np.isfinite(scores).any(): raise ValueError("No valid silhouette candidate") optimal_k = candidates[int(np.nanargmax(scores))] # Exploratory candidate only ```

  1. Apply clustering ``python model = KMeans(n_clusters=optimal_k, random_state=42) labels = model.fit_predict(X_scaled)
  1. Visualize with dimensionality reduction ```python from sklearn.decomposition import PCA import matplotlib.pyplot as plt

pca = PCA(n_components=2) X_2d = pca.fit_transform(X_scaled)

plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='viridis') ```

Raw lines 76 to 121
122## Upstream references
124- https://scikit-learn.org/stable/common_pitfalls.html
125- https://scikit-learn.org/stable/modules/clustering.html

Upstream references

  • https://scikit-learn.org/stable/common_pitfalls.html
  • https://scikit-learn.org/stable/modules/clustering.html
Raw lines 122 to 125