Senior Data Scientist
Overview
Build end-to-end data science workflows from data exploration through model deployment. This skill covers data preprocessing, feature engineering, model selection, hyperparameter tuning, cross-validation, experiment tracking with MLflow/W&B, statistical testing, visualization with matplotlib/seaborn/plotly, and Jupyter notebook best practices.
Announce at start: "I'm using the senior-data-scientist skill for data science workflow."
Phase 1: Data Understanding
Goal: Profile the dataset and establish a baseline before any modeling.
Actions
- Load and profile the dataset (shape, types, distributions)
- Identify missing values, outliers, and data quality issues
- Perform exploratory data analysis (EDA)
- Define the target variable and success metrics
- Establish baseline performance
Baseline Models (Always Start Here)
| Task |
Baseline Model |
Why |
| Classification |
Majority class classifier |
Lower bound for accuracy |
| Classification |
Logistic regression |
Simple, interpretable |
| Regression |
Mean predictor |
Lower bound for RMSE |
| Regression |
Linear regression |
Simple, interpretable |
| Time series |
Naive forecast (previous value) |
Lower bound for MAE |
| Time series |
Seasonal naive |
Captures basic seasonality |
STOP — Do NOT proceed to Phase 2 until:
Phase 2: Feature Engineering
Goal: Transform raw data into features that improve model performance.
Actions
- Handle missing values (imputation strategy)
- Encode categorical variables
- Scale/normalize numerical features
- Create derived features
- Feature selection (remove redundant/irrelevant)
Missing Value Strategy Decision Table
| Strategy |
When to Use |
Implementation |
| Drop rows |
< 5% missing, MCAR |
df.dropna() |
| Mean/Median |
Numerical, no outliers |
SimpleImputer(strategy='median') |
| Mode |
Categorical |
SimpleImputer(strategy='most_frequent') |
| KNN Imputer |
Structured missing patterns |
KNNImputer(n_neighbors=5) |
| Iterative |
Complex relationships |
IterativeImputer() |
| Flag + Impute |
Missingness is informative |
Add is_missing column + impute |
Categorical Encoding Decision Table
| Method |
When |
Cardinality |
| One-Hot |
Nominal, low cardinality |
< 10 categories |
| Label/Ordinal |
Ordinal features |
Any |
| Target Encoding |
High cardinality nominal |
> 10 categories |
| Frequency Encoding |
When frequency matters |
Any |
| Binary Encoding |
Very high cardinality |
> 50 categories |
Scaling Decision Table
| Scaler |
When |
Robust to Outliers? |
| StandardScaler |
Default choice (mean=0, std=1) |
No |
| RobustScaler |
Outliers present (median/IQR) |
Yes |
| MinMaxScaler |
Neural networks, distance-based [0,1] |
No |
Feature Types and Engineering
| Feature Type |
Techniques |
| Numerical |
Log transform, polynomial, binning, interactions (A*B, A/B) |
| Temporal |
Hour, day-of-week, is_weekend, time_since_event, cyclical (sin/cos), lags |
| Text |
TF-IDF, word count, sentiment scores, named entities, embeddings |
| Categorical |
Encoding (above), interaction with numerical features |
Feature Selection Decision Table
| Method |
Type |
Use When |
| Correlation matrix |
Filter |
Initial exploration |
| Mutual information |
Filter |
Non-linear relationships |
| Recursive Feature Elimination |
Wrapper |
Model-specific selection |
| L1 Regularization |
Embedded |
Linear models |
| Feature importance |
Embedded |
Tree-based models |
| Permutation importance |
Model-agnostic |
Final validation |
STOP — Do NOT proceed to Phase 3 until:
Phase 3: Modeling
Goal: Select, train, and evaluate candidate models.
Actions
- Select candidate algorithms
- Set up cross-validation strategy
- Train and evaluate candidates
- Hyperparameter tuning
- Final model selection and evaluation
Algorithm Decision Table
| Data Characteristics |
Try First |
Also Consider |
| Tabular, < 10K rows |
Random Forest, XGBoost |
Logistic/Linear Regression |
| Tabular, > 10K rows |
XGBoost, LightGBM |
CatBoost, Neural Network |
| High dimensionality |
Lasso/Ridge, SVM |
Random Forest with selection |
| Time series |
Prophet, ARIMA |
LSTM, XGBoost with lag features |
| Text classification |
Fine-tuned transformer |
TF-IDF + Logistic Regression |
| Image classification |
Pre-trained CNN (ResNet, EfficientNet) |
Vision Transformer |
| Regression |
XGBoost, Random Forest |
Linear Regression, Neural Network |
| Anomaly detection |
Isolation Forest |
LOF, Autoencoder |
Cross-Validation Strategy Decision Table
| Strategy |
When |
Code |
| K-Fold (k=5) |
Default, balanced data |
KFold(n_splits=5) |
| Stratified K-Fold |
Classification, imbalanced |
StratifiedKFold(n_splits=5) |
| Time Series Split |
Temporal data |
TimeSeriesSplit(n_splits=5) |
| Group K-Fold |
Grouped observations |
GroupKFold(n_splits=5) |
| Leave-One-Out |
Very small datasets |
LeaveOneOut() |
Evaluation Metrics Decision Table
| Task |
Primary Metric |
Secondary Metrics |
| Binary Classification |
AUC-ROC |
F1, Precision, Recall, AP |
| Multiclass |
Macro F1 |
Accuracy, Confusion Matrix |
| Regression |
RMSE |
MAE, R-squared, MAPE |
| Ranking |
NDCG |
MAP, MRR |
| Anomaly Detection |
F1, AP |
Precision@K, Recall@K |
Hyperparameter Tuning Decision Table
| Method |
Compute Budget |
Search Space |
Implementation |
| Grid Search |
Low (< 100 combos) |
Small, known ranges |
GridSearchCV |
| Random Search |
Medium |
Large, uncertain |
RandomizedSearchCV |
| Bayesian (Optuna) |
Any |
Large, expensive |
optuna.create_study() |
| Successive Halving |
Large |
Many candidates |
HalvingRandomSearchCV |
Common Hyperparameters (XGBoost/LightGBM)
param_space = {
'n_estimators': [100, 300, 500, 1000],
'max_depth': [3, 5, 7, 9],
'learning_rate': [0.01, 0.05, 0.1],
'subsample': [0.7, 0.8, 0.9],
'colsample_bytree': [0.7, 0.8, 0.9],
'min_child_weight': [1, 3, 5],
}
STOP — Do NOT proceed to Phase 4 until:
Phase 4: Deployment
Goal: Serialize, serve, and monitor the model in production.
Actions
- Serialize model and preprocessing pipeline
- Create prediction API or batch pipeline
- Set up monitoring for data drift and model degradation
- Document model card (inputs, outputs, limitations, biases)
STOP — Deployment complete when:
Experiment Tracking
MLflow Pattern
import mlflow
mlflow.set_experiment("customer-churn-prediction")
with mlflow.start_run(run_name="xgboost-v2"):
mlflow.log_params(params)
mlflow.log_metrics({"auc": auc_score, "f1": f1_score})
mlflow.log_artifact("confusion_matrix.png")
mlflow.sklearn.log_model(pipeline, "model")
mlflow.set_tag("version", "2.1")
What to Track
| Category |
Items |
| Parameters |
All hyperparameters, random seed |
| Metrics |
Train and validation metrics |
| Data |
Data version/hash, feature list |
| Artifacts |
Plots, reports, model files |
| Metadata |
Training duration, model size |
Statistical Tests Decision Table
| Question |
Test |
Assumption |
| Two group means different? |
t-test (independent) |
Normal distribution |
| Two groups (non-normal)? |
Mann-Whitney U |
None |
| Paired measurements? |
Paired t-test |
Normal differences |
| 3+ group means? |
ANOVA |
Normal, equal variance |
| Categorical association? |
Chi-squared |
Expected freq > 5 |
| Distribution normal? |
Shapiro-Wilk |
n < 5000 |
| Two distributions different? |
Kolmogorov-Smirnov |
Continuous data |
P-Value Guidelines
- p < 0.05: statistically significant (conventional)
- Always report effect size alongside p-value
- Adjust for multiple comparisons (Bonferroni, FDR)
- Statistical significance is not practical significance
Visualization Decision Table
| Data Type |
Plot |
Library |
| Distribution |
Histogram, KDE, Box plot |
seaborn |
| Comparison |
Bar chart, Grouped bar |
matplotlib |
| Correlation |
Scatter, Heatmap |
seaborn |
| Trend |
Line chart |
matplotlib/plotly |
| Composition |
Stacked bar, Pie (max 5 slices) |
matplotlib |
| Interactive |
Scatter, Line, Dashboard |
plotly |
Visualization Rules
- Title every plot descriptively
- Label axes with units
- Use colorblind-safe palettes (
seaborn: colorblind)
- Start y-axis at 0 for bar charts
- Annotate key findings directly on plots
Jupyter Notebook Structure
1. ## Setup (imports, configuration)
2. ## Data Loading
3. ## Exploratory Data Analysis
4. ## Data Preprocessing
5. ## Feature Engineering
6. ## Modeling
7. ## Evaluation
8. ## Conclusions
Notebook Best Practices
- Restart and run all before sharing
- Keep cells focused and sequential
- Use markdown cells for explanations
- Extract reusable code to
.py modules
- Version control with
nbstripout
- Pin all dependency versions
Anti-Patterns / Common Mistakes
| Anti-Pattern |
Why It Is Wrong |
Correct Approach |
| Training on test data |
Data leakage, inflated metrics |
Strict train/test separation |
| Feature engineering before split |
Leaks test information into features |
Engineer on training data only |
| Reporting training metrics |
Not generalizable |
Report validation/test metrics |
| Accuracy on imbalanced data |
Misleading (majority class wins) |
Use F1, AUC-ROC, or AP |
| Tuning on test set |
Overfitting to test data |
Use validation set for tuning |
| No baseline comparison |
Cannot measure improvement |
Always establish baseline first |
| Cherry-picking evaluation examples |
Selection bias |
Report on full evaluation set |
| Deploying without drift monitoring |
Silent model degradation |
Monitor input distributions |
Integration Points
| Skill |
Relationship |
senior-prompt-engineer |
Prompt evaluation uses statistical testing methods |
testing-strategy |
ML testing follows the evaluation methodology |
performance-optimization |
Model inference optimization follows measurement cycle |
acceptance-testing |
Model performance thresholds become acceptance criteria |
llm-as-judge |
Subjective output evaluation uses LLM-as-judge |
code-review |
Notebook and pipeline code reviewed for quality |
Skill Type
FLEXIBLE — Adapt preprocessing, modeling, and evaluation approaches to the specific data characteristics, business requirements, and compute constraints. The four-phase process and experiment tracking are strongly recommended. Always establish a baseline before modeling.
1---2name: senior-data-scientist3description: Use when the user needs ML pipelines, statistical analysis, data preprocessing, feature engineering, model selection, experiment tracking, or data visualization. Triggers: dataset exploration, model training, feature engineering, hyperparameter tuning, experiment tracking setup, statistical hypothesis testing, visualization creation.4---5
6# Senior Data Scientist
7
8## Overview
9
10Build end-to-end data science workflows from data exploration through model deployment. This skill covers data preprocessing, feature engineering, model selection, hyperparameter tuning, cross-validation, experiment tracking with MLflow/W&B, statistical testing, visualization with matplotlib/seaborn/plotly, and Jupyter notebook best practices.
11
12**Announce at start:** "I'm using the senior-data-scientist skill for data science workflow."
13
14---
15
16## Phase 1: Data Understanding
17
18**Goal:** Profile the dataset and establish a baseline before any modeling.
19
20### Actions
21
221. Load and profile the dataset (shape, types, distributions)
232. Identify missing values, outliers, and data quality issues
243. Perform exploratory data analysis (EDA)
254. Define the target variable and success metrics
265. Establish baseline performance
27
28### Baseline Models (Always Start Here)
29
30| Task | Baseline Model | Why |
31|------|---------------|-----|
32| Classification | Majority class classifier | Lower bound for accuracy |
33| Classification | Logistic regression | Simple, interpretable |
34| Regression | Mean predictor | Lower bound for RMSE |
35| Regression | Linear regression | Simple, interpretable |
36| Time series | Naive forecast (previous value) | Lower bound for MAE |
37| Time series | Seasonal naive | Captures basic seasonality |
38
39### STOP — Do NOT proceed to Phase 2 until:
40- [ ] Dataset is profiled (shape, types, distributions)
41- [ ] Missing values and outliers are documented
42- [ ] Target variable is defined
43- [ ] Success metrics are chosen
44- [ ] Baseline performance is established
45
46---
47
48## Phase 2: Feature Engineering
49
50**Goal:** Transform raw data into features that improve model performance.
51
52### Actions
53
541. Handle missing values (imputation strategy)
552. Encode categorical variables
563. Scale/normalize numerical features
574. Create derived features
585. Feature selection (remove redundant/irrelevant)
59
60### Missing Value Strategy Decision Table
61
62| Strategy | When to Use | Implementation |
63|----------|-------------|---------------|
64| Drop rows | < 5% missing, MCAR | `df.dropna()` |
65| Mean/Median | Numerical, no outliers | `SimpleImputer(strategy='median')` |
66| Mode | Categorical | `SimpleImputer(strategy='most_frequent')` |
67| KNN Imputer | Structured missing patterns | `KNNImputer(n_neighbors=5)` |
68| Iterative | Complex relationships | `IterativeImputer()` |
69| Flag + Impute | Missingness is informative | Add `is_missing` column + impute |
70
71### Categorical Encoding Decision Table
72
73| Method | When | Cardinality |
74|--------|------|-------------|
75| One-Hot | Nominal, low cardinality | < 10 categories |
76| Label/Ordinal | Ordinal features | Any |
77| Target Encoding | High cardinality nominal | > 10 categories |
78| Frequency Encoding | When frequency matters | Any |
79| Binary Encoding | Very high cardinality | > 50 categories |
80
81### Scaling Decision Table
82
83| Scaler | When | Robust to Outliers? |
84|--------|------|-------------------|
85| StandardScaler | Default choice (mean=0, std=1) | No |
86| RobustScaler | Outliers present (median/IQR) | Yes |
87| MinMaxScaler | Neural networks, distance-based [0,1] | No |
88
89### Feature Types and Engineering
90
91| Feature Type | Techniques |
92|-------------|-----------|
93| Numerical | Log transform, polynomial, binning, interactions (A*B, A/B) |
94| Temporal | Hour, day-of-week, is_weekend, time_since_event, cyclical (sin/cos), lags |
95| Text | TF-IDF, word count, sentiment scores, named entities, embeddings |
96| Categorical | Encoding (above), interaction with numerical features |
97
98### Feature Selection Decision Table
99
100| Method | Type | Use When |
101|--------|------|----------|
102| Correlation matrix | Filter | Initial exploration |
103| Mutual information | Filter | Non-linear relationships |
104| Recursive Feature Elimination | Wrapper | Model-specific selection |
105| L1 Regularization | Embedded | Linear models |
106| Feature importance | Embedded | Tree-based models |
107| Permutation importance | Model-agnostic | Final validation |
108
109### STOP — Do NOT proceed to Phase 3 until:
110- [ ] Missing values are handled with justified strategy
111- [ ] Categorical variables are encoded appropriately
112- [ ] Numerical features are scaled
113- [ ] Feature engineering is done BEFORE train/test split on training data only
114- [ ] Feature selection has reduced dimensionality if needed
115
116---
117
118## Phase 3: Modeling
119
120**Goal:** Select, train, and evaluate candidate models.
121
122### Actions
123
1241. Select candidate algorithms
1252. Set up cross-validation strategy
1263. Train and evaluate candidates
1274. Hyperparameter tuning
1285. Final model selection and evaluation
129
130### Algorithm Decision Table
131
132| Data Characteristics | Try First | Also Consider |
133|---------------------|-----------|---------------|
134| Tabular, < 10K rows | Random Forest, XGBoost | Logistic/Linear Regression |
135| Tabular, > 10K rows | XGBoost, LightGBM | CatBoost, Neural Network |
136| High dimensionality | Lasso/Ridge, SVM | Random Forest with selection |
137| Time series | Prophet, ARIMA | LSTM, XGBoost with lag features |
138| Text classification | Fine-tuned transformer | TF-IDF + Logistic Regression |
139| Image classification | Pre-trained CNN (ResNet, EfficientNet) | Vision Transformer |
140| Regression | XGBoost, Random Forest | Linear Regression, Neural Network |
141| Anomaly detection | Isolation Forest | LOF, Autoencoder |
142
143### Cross-Validation Strategy Decision Table
144
145| Strategy | When | Code |
146|----------|------|------|
147| K-Fold (k=5) | Default, balanced data | `KFold(n_splits=5)` |
148| Stratified K-Fold | Classification, imbalanced | `StratifiedKFold(n_splits=5)` |
149| Time Series Split | Temporal data | `TimeSeriesSplit(n_splits=5)` |
150| Group K-Fold | Grouped observations | `GroupKFold(n_splits=5)` |
151| Leave-One-Out | Very small datasets | `LeaveOneOut()` |
152
153### Evaluation Metrics Decision Table
154
155| Task | Primary Metric | Secondary Metrics |
156|------|---------------|-------------------|
157| Binary Classification | AUC-ROC | F1, Precision, Recall, AP |
158| Multiclass | Macro F1 | Accuracy, Confusion Matrix |
159| Regression | RMSE | MAE, R-squared, MAPE |
160| Ranking | NDCG | MAP, MRR |
161| Anomaly Detection | F1, AP | Precision@K, Recall@K |
162
163### Hyperparameter Tuning Decision Table
164
165| Method | Compute Budget | Search Space | Implementation |
166|--------|---------------|-------------|----------------|
167| Grid Search | Low (< 100 combos) | Small, known ranges | `GridSearchCV` |
168| Random Search | Medium | Large, uncertain | `RandomizedSearchCV` |
169| Bayesian (Optuna) | Any | Large, expensive | `optuna.create_study()` |
170| Successive Halving | Large | Many candidates | `HalvingRandomSearchCV` |
171
172### Common Hyperparameters (XGBoost/LightGBM)
173
174```python
175param_space = {
176 'n_estimators': [100, 300, 500, 1000],
177 'max_depth': [3, 5, 7, 9],
178 'learning_rate': [0.01, 0.05, 0.1],
179 'subsample': [0.7, 0.8, 0.9],
180 'colsample_bytree': [0.7, 0.8, 0.9],
181 'min_child_weight': [1, 3, 5],
182}
183```
184
185### STOP — Do NOT proceed to Phase 4 until:
186- [ ] At least 2 candidate models are evaluated
187- [ ] Cross-validation is used (not just train/test split)
188- [ ] Results beat the baseline from Phase 1
189- [ ] Best model is selected with justification
190- [ ] Overfitting is checked (train vs validation gap)
191
192---
193
194## Phase 4: Deployment
195
196**Goal:** Serialize, serve, and monitor the model in production.
197
198### Actions
199
2001. Serialize model and preprocessing pipeline
2012. Create prediction API or batch pipeline
2023. Set up monitoring for data drift and model degradation
2034. Document model card (inputs, outputs, limitations, biases)
204
205### STOP — Deployment complete when:
206- [ ] Model is serialized with preprocessing pipeline
207- [ ] Prediction API or batch pipeline works end-to-end
208- [ ] Monitoring is configured for data drift
209- [ ] Model card is documented
210
211---
212
213## Experiment Tracking
214
215### MLflow Pattern
216
217```python
218import mlflow
219
220mlflow.set_experiment("customer-churn-prediction")
221
222with mlflow.start_run(run_name="xgboost-v2"):
223 mlflow.log_params(params)
224 mlflow.log_metrics({"auc": auc_score, "f1": f1_score})
225 mlflow.log_artifact("confusion_matrix.png")
226 mlflow.sklearn.log_model(pipeline, "model")
227 mlflow.set_tag("version", "2.1")
228```
229
230### What to Track
231
232| Category | Items |
233|----------|-------|
234| Parameters | All hyperparameters, random seed |
235| Metrics | Train and validation metrics |
236| Data | Data version/hash, feature list |
237| Artifacts | Plots, reports, model files |
238| Metadata | Training duration, model size |
239
240---
241
242## Statistical Tests Decision Table
243
244| Question | Test | Assumption |
245|----------|------|-----------|
246| Two group means different? | t-test (independent) | Normal distribution |
247| Two groups (non-normal)? | Mann-Whitney U | None |
248| Paired measurements? | Paired t-test | Normal differences |
249| 3+ group means? | ANOVA | Normal, equal variance |
250| Categorical association? | Chi-squared | Expected freq > 5 |
251| Distribution normal? | Shapiro-Wilk | n < 5000 |
252| Two distributions different? | Kolmogorov-Smirnov | Continuous data |
253
254### P-Value Guidelines
255
256- p < 0.05: statistically significant (conventional)
257- Always report effect size alongside p-value
258- Adjust for multiple comparisons (Bonferroni, FDR)
259- Statistical significance is not practical significance
260
261---
262
263## Visualization Decision Table
264
265| Data Type | Plot | Library |
266|-----------|------|---------|
267| Distribution | Histogram, KDE, Box plot | seaborn |
268| Comparison | Bar chart, Grouped bar | matplotlib |
269| Correlation | Scatter, Heatmap | seaborn |
270| Trend | Line chart | matplotlib/plotly |
271| Composition | Stacked bar, Pie (max 5 slices) | matplotlib |
272| Interactive | Scatter, Line, Dashboard | plotly |
273
274### Visualization Rules
275
276- Title every plot descriptively
277- Label axes with units
278- Use colorblind-safe palettes (`seaborn: colorblind`)
279- Start y-axis at 0 for bar charts
280- Annotate key findings directly on plots
281
282---
283
284## Jupyter Notebook Structure
285
286```
2871. ## Setup (imports, configuration)
2882. ## Data Loading
2893. ## Exploratory Data Analysis
2904. ## Data Preprocessing
2915. ## Feature Engineering
2926. ## Modeling
2937. ## Evaluation
2948. ## Conclusions
295```
296
297### Notebook Best Practices
298
299- Restart and run all before sharing
300- Keep cells focused and sequential
301- Use markdown cells for explanations
302- Extract reusable code to `.py` modules
303- Version control with `nbstripout`
304- Pin all dependency versions
305
306---
307
308## Anti-Patterns / Common Mistakes
309
310| Anti-Pattern | Why It Is Wrong | Correct Approach |
311|-------------|----------------|-----------------|
312| Training on test data | Data leakage, inflated metrics | Strict train/test separation |
313| Feature engineering before split | Leaks test information into features | Engineer on training data only |
314| Reporting training metrics | Not generalizable | Report validation/test metrics |
315| Accuracy on imbalanced data | Misleading (majority class wins) | Use F1, AUC-ROC, or AP |
316| Tuning on test set | Overfitting to test data | Use validation set for tuning |
317| No baseline comparison | Cannot measure improvement | Always establish baseline first |
318| Cherry-picking evaluation examples | Selection bias | Report on full evaluation set |
319| Deploying without drift monitoring | Silent model degradation | Monitor input distributions |
320
321---
322
323## Integration Points
324
325| Skill | Relationship |
326|-------|-------------|
327| `senior-prompt-engineer` | Prompt evaluation uses statistical testing methods |
328| `testing-strategy` | ML testing follows the evaluation methodology |
329| `performance-optimization` | Model inference optimization follows measurement cycle |
330| `acceptance-testing` | Model performance thresholds become acceptance criteria |
331| `llm-as-judge` | Subjective output evaluation uses LLM-as-judge |
332| `code-review` | Notebook and pipeline code reviewed for quality |
333
334---
335
336## Skill Type
337
338**FLEXIBLE** — Adapt preprocessing, modeling, and evaluation approaches to the specific data characteristics, business requirements, and compute constraints. The four-phase process and experiment tracking are strongly recommended. Always establish a baseline before modeling.