Skip to content
Back to skills

Data Scientist

ASecurity

Experiment design and A/B readouts (sample size, sample-ratio and contamination checks, tests with intervals), feature screening for leakage, model evaluation against a no-skill baseline, and fair experiment comparison. Use when sizing or reading out an A/B test, choosing features, judging a model from its predictions, or picking between training runs.

  • 1,271 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added May 27, 2026
data-aipythonrustgobashtesting

Works with

  • cli

Security analysis

A100/100

Pro scans all 4 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add borghei/Claude-Skills --skill data-scientist --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Data Scientist?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Data Scientist
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/borghei-data-scientist/badge)](https://www.skillsdirectory.com/skills/borghei-data-scientist)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: data-scientist
description: >
  Experiment design and A/B readouts (sample size, sample-ratio and contamination
  checks, tests with intervals), feature screening for leakage, model evaluation
  against a no-skill baseline, and fair experiment comparison. Use when sizing or
  reading out an A/B test, choosing features, judging a model from its
  predictions, or picking between training runs.
license: MIT + Commons Clause
metadata:
  version: 2.0.0
  author: borghei
  category: data-analytics
  domain: data-science
  updated: 2026-12-03
  tags: [data-science, machine-learning, statistics, modeling, analytics]
---
# Data Scientist

## What you get

Point it at your per-user A/B export; get told whether the result can be trusted before you read the lift.

**Before** (`assets/flawed_ab_test.csv`, 3,795 rows, planned 50/50 split):

```
user_id,variant,converted,revenue
u10400,control,0,0
u13925,treatment,0,0
```

**After running `hypothesis_tester.py abtest`** (exit 1):

```
FIX 3 issue(s) before using this result
Sample ratio check: observed {'control': 2000, 'treatment': 1795}, expected [1897.5, 1897.5], chi-square 11.074, p=0.0009
- treatment vs control: UNRELIABLE until the findings below are fixed. Significant: difference 0.03939 (95% CI 0.018589 to 0.060191) …

1. [high] CROSS_ARM_UNITS
   Problem:  35 user_id(s) appear in more than one arm, e.g. 'u11468' in control (line 54), treatment (line 2290)
   Fix:      Assignment leaked. Drop these 35 units from every arm (or keep only their first exposure) and find the bucketing bug before trusting any result.
```

The "significant" lift is not believable until the bucketing bug is fixed. On the clean `assets/sound_ab_test.csv` the same command prints `PASS: test ran; treatment vs control: significant at alpha 0.05 (p=0.0084)`, exit 0.

**Quick start** (from this skill folder):

```bash
python3 scripts/hypothesis_tester.py abtest --file assets/flawed_ab_test.csv --group-col variant --metric-col converted --unit-col user_id
python3 scripts/hypothesis_tester.py sample-size --baseline 0.08 --mde 0.10 --daily-traffic 4000
python3 scripts/model_evaluator.py --file assets/flawed_predictions.csv
```

For the whole job end to end, use the `cs-data-scientist` agent (installed with the plugin, or `npx @borghei/claude-skills add-agent cs-data-scientist`).

---

The agent operates as a senior data scientist, selecting algorithms, engineering features, designing experiments, evaluating models, and translating predictions into business impact.

## Clarify First

Before modeling, settle the inputs below. When one is missing or vague and would change the result, ask about it; when it wouldn't, use a sensible default and say which one you used.

- **ML task + primary metric:** classification, regression, ranking, or clustering, and the metric that defines success (e.g., F1, RMSE) (drives algorithm selection and evaluation).
- **Constraints:** latency, interpretability, and data volume (decides where on the simple→complex model ladder to land).
- **Target variable and label quality:** what is being predicted and how clean/balanced the labels are (drives feature engineering and imbalance handling).
- **For an A/B test: baseline rate + MDE:** current conversion and the smallest lift worth detecting (drives the required sample size).

Ask about the two or three inputs that matter most for this request, not the whole list. If the user wants a result straight away, produce it and state your assumptions at the top.

## Workflow

1. **Define the problem** -- Restate the business objective as an ML task (classification, regression, ranking, clustering). Define the primary evaluation metric (e.g., F1 for imbalanced classification, RMSE for regression). Document constraints (latency, interpretability, data volume).
2. **Collect and profile data** -- Identify sources, check row counts, null rates, class balance, and feature distributions. Flag data-quality issues before modeling.
3. **Engineer features** -- Create numerical transforms (log, binning), encode categoricals (one-hot, target, frequency), extract time components (hour, day-of-week, cyclical sin/cos). Select top features via importance, mutual information, or RFE.
4. **Select and train models** -- Use the algorithm selection matrix below. Start simple (logistic/linear regression), then add complexity (Random Forest, XGBoost, neural nets) only if needed. Use cross-validation.
5. **Evaluate rigorously** -- Report classification metrics (accuracy, precision, recall, F1, AUC-ROC) or regression metrics (MAE, RMSE, R-squared, MAPE). Compare against a baseline. Check for overfitting (train vs. test gap).
6. **Communicate results** -- Present business impact (e.g., "cuts false positives by X%, worth $Y per year at current volume", with X and Y computed from the evaluation). Recommend deployment path or next experiment.

## Algorithm Selection Matrix

| Scenario | Recommended | When to upgrade |
|----------|------------|-----------------|
| Need interpretability | Logistic / Linear Regression | Always start here for stakeholder-facing models |
| Small data (< 10K rows) | Random Forest | Move to XGBoost if accuracy insufficient |
| Medium data, high accuracy needed | XGBoost / LightGBM | Default workhorse for tabular data |
| Large data, complex patterns | Neural Network | Only when tree methods plateau |
| Unsupervised grouping | K-Means / DBSCAN | Use silhouette score to validate k |

## Feature Engineering Examples

**Numerical transforms:**
```python
import numpy as np, pandas as pd

def engineer_numerical(df: pd.DataFrame, col: str) -> pd.DataFrame:
    return pd.DataFrame({
        f'{col}_log':     np.log1p(df[col]),
        f'{col}_sqrt':    np.sqrt(df[col].clip(lower=0)),
        f'{col}_squared': df[col] ** 2,
        f'{col}_binned':  pd.cut(df[col], bins=5, labels=False),
    })
```

**Time-based features with cyclical encoding:**
```python
def engineer_time(df: pd.DataFrame, col: str) -> pd.DataFrame:
    dt = pd.to_datetime(df[col])
    return pd.DataFrame({
        f'{col}_hour':      dt.dt.hour,
        f'{col}_dayofweek': dt.dt.dayofweek,
        f'{col}_month':     dt.dt.month,
        f'{col}_is_weekend': dt.dt.dayofweek.isin([5, 6]).astype(int),
        f'{col}_hour_sin':  np.sin(2 * np.pi * dt.dt.hour / 24),
        f'{col}_hour_cos':  np.cos(2 * np.pi * dt.dt.hour / 24),
    })
```

**Feature selection (importance-based):**
```python
from sklearn.ensemble import RandomForestClassifier

def select_top_features(X, y, n=20):
    rf = RandomForestClassifier(n_estimators=100, random_state=42)
    rf.fit(X, y)
    importance = pd.Series(rf.feature_importances_, index=X.columns)
    return importance.nlargest(n).index.tolist()
```

## Model Evaluation

**Classification:**
```python
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score

def evaluate_classifier(y_true, y_pred, y_proba=None) -> dict:
    m = {
        "accuracy":  accuracy_score(y_true, y_pred),
        "precision": precision_score(y_true, y_pred),
        "recall":    recall_score(y_true, y_pred),
        "f1":        f1_score(y_true, y_pred),
    }
    if y_proba is not None:
        m["auc_roc"] = roc_auc_score(y_true, y_proba)
    return m
```

**Regression:**
```python
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np

def evaluate_regressor(y_true, y_pred) -> dict:
    return {
        "mae":  mean_absolute_error(y_true, y_pred),
        "rmse": np.sqrt(mean_squared_error(y_true, y_pred)),
        "r2":   r2_score(y_true, y_pred),
    }
```

## A/B Test Design and Analysis

Size the test before it starts, then read it out from the per-user export, not from a dashboard:

```bash
# Design: units per arm for an 8% baseline and a +10% relative lift, and how many days at 4,000 users/day
python3 scripts/hypothesis_tester.py sample-size --baseline 0.08 --mde 0.10 --daily-traffic 4000
# -> 18872 per group (37744 total), 10 days

# Readout: one row per user with the variant and the outcome
python3 scripts/hypothesis_tester.py abtest --file assets/sound_ab_test.csv \
  --group-col variant --metric-col converted --unit-col user_id
```

The readout checks the experiment before the result: sample-ratio mismatch (chi-square against the planned split, alarm at p < 0.001), users in more than one arm, users with several rows. Any of those makes the verdict `FIX` and marks the result *UNRELIABLE*. It then runs a two-proportion z test (0/1 outcome) or Welch's t test (numeric outcome) per variant, Bonferroni-adjusted when there are several variants, and reports the difference with its 95% interval and an effect size. A result is called significant only from that run; a non-significant result is reported as inconclusive with its interval, never as "no effect".

## Project Template

```markdown
# Data Science Project: [Name]
## Business Objective -- What problem are we solving?
## Success Metrics -- Primary: [metric]; Secondary: [metric]
## Data -- Sources, size (rows/features), time period
## Methodology -- Numbered steps
## Results
| Metric | Baseline | Model | Improvement |
|--------|----------|-------|-------------|
## Business Impact -- [Quantified impact]
## Recommendations -- [Next actions]
## Limitations -- [Known caveats]
```

## Scripts

Standard library only; each reads the user's file or arguments. `scripts/stats_lib.py` (shared, not a command) holds exact t and chi-square distributions (regularized incomplete beta and gamma), so small samples get correct p-values.

```bash
python3 scripts/hypothesis_tester.py abtest --file assets/sound_ab_test.csv --group-col variant --metric-col converted --unit-col user_id
python3 scripts/hypothesis_tester.py proportion --successes-a 412 --trials-a 5000 --successes-b 471 --trials-b 5000
python3 scripts/hypothesis_tester.py ttest --file assets/sample_paired.csv --col-a before --col-b after --paired
python3 scripts/hypothesis_tester.py chi-square --file assets/sound_contingency.csv --format json
python3 scripts/hypothesis_tester.py sample-size --baseline 0.08 --mde 0.10 --available-per-group 4000
python3 scripts/feature_selector.py assets/flawed_churn.csv --target churned
python3 scripts/model_evaluator.py assets/sound_predictions.csv --label-col y_true --score-col y_score --threshold 0.5
python3 scripts/experiment_tracker.py log --log-file runs.json --name gbm_v2 --params '{"max_depth": 4}' --metrics '{"val_auc": 0.82}'
python3 scripts/experiment_tracker.py compare --log-file assets/flawed_experiments.json --format json
```

| Tool | What it does | Findings it raises |
|------|--------------|--------------------|
| `hypothesis_tester.py` | `abtest` readout from a per-unit export; `proportion`, `ttest` (Welch or `--paired`), `chi-square` on a count table; `sample-size` for binary (`--baseline --mde`) or numeric (`--sd --mde-abs`) outcomes, with `--variants`, `--daily-traffic`, `--available-per-group`. All take `--alpha`, `--comparisons`, `--format`. | SAMPLE_RATIO_MISMATCH, CROSS_ARM_UNITS, REPEATED_UNITS, UNUSABLE_OUTCOME, SMALL_COUNTS, SMALL_SAMPLE, SMALL_EXPECTED_COUNTS (Cochran, 1954), INCOMPLETE_PAIRS, UNDERPOWERED (with the effect the available sample can detect) |
| `feature_selector.py` | Ranks features by mutual information with the target (share of target entropy, Miller-Madow corrected), \|Pearson r\|, and single-feature accuracy vs the majority baseline | LEAKAGE, MISSINGNESS_LEAK, ID_LIKE, CONSTANT, HIGH_NULL, TARGET_MISSING; notes NEAR_CONSTANT, HIGH_CARDINALITY, WEAK_SIGNAL, IMBALANCED_TARGET |
| `model_evaluator.py` | Classification: confusion matrix, accuracy vs majority baseline, precision/recall/F1, ROC-AUC with 95% CI (Hanley & McNeil, 1982), average precision, Brier vs base rate, calibration by quintile, F1-best threshold. Regression (`--task regression`): MAE, RMSE, R^2, bias, MAPE, mean-predictor MAE | BELOW_BASELINE, NO_SKILL, INVERTED_SCORES, SUSPICIOUSLY_PERFECT, WORSE_THAN_BASE_RATE, MISCALIBRATED, FEW_POSITIVES, WORSE_THAN_MEAN, BIASED; notes THRESHOLD, MAPE_ZEROS |
| `experiment_tracker.py` | `log`, `list`, `compare` runs in a JSON file (`--log-file`, default `./experiments.json`); best per metric respects direction (loss/error/rmse lower is better, `--lower-better` for others) | NOT_COMPARABLE (different data/split), MISSING_METRIC, NON_NUMERIC_METRIC, TRAIN_ONLY_METRIC; notes WITHIN_NOISE, DIFFERENT_SEEDS |

Samples in `assets/` come as sound / flawed / malformed sets: `*_ab_test.csv`, `*_contingency.csv`, `*_churn.csv`, `*_predictions.csv`, `*_experiments.json`, plus `sample_paired.csv` for the paired t test. `assets/contract.json` lists the expected exit code of every run.

### Exit codes

| Code | Meaning |
|------|---------|
| 0 | The test or evaluation ran and nothing undermines it (notes may remain); `log`/`list` succeeded |
| 1 | It ran, but a finding must be fixed before the result is used (SRM, leakage, below-baseline model, unfair comparison, underpowered plan) |
| 2 | Unusable input: missing file or column, one group only, non-numeric counts, invalid JSON. One `BLOCKED:` line on stderr, never a traceback |

### Real output

```text
$ python3 scripts/hypothesis_tester.py abtest --file assets/flawed_ab_test.csv --group-col variant --metric-col converted --unit-col user_id
FIX 3 issue(s) before using this result
Read: rows=3795, groups={'control': 2000, 'treatment': 1795}, control=control, outcome=binary (0/1), comparisons=1, alpha=0.05, adjusted_alpha=0.05
Sample ratio check: observed {'control': 2000, 'treatment': 1795}, expected [1897.5, 1897.5], chi-square 11.074, p=0.0009

| Comparison | A | B | Difference | 95% CI | p-value | Significant | Effect |
|---|---|---|---|---|---|---|---|
| treatment vs control | 0.101 | 0.14039 | 0.03939 | 0.018589 to 0.060191 | 0.0002 | yes (alpha 0.05) | Cohen's h 0.1213 (negligible) |

- treatment vs control: UNRELIABLE until the findings below are fixed. Significant: difference 0.03939 ...
```

## Troubleshooting

| Problem | Likely cause | Resolution |
|---------|-------------|------------|
| SAMPLE_RATIO_MISMATCH on a test that "looks fine" | Units lost or duplicated in one arm (redirects, bot filters, late assignment) | Do not read the result; find the leak, re-run on a clean window. Pass `--expected-split` if the plan was not equal |
| REPEATED_UNITS | The export is per session or per event, not per user | Aggregate to one row per user (MAX for conversion, SUM for revenue) and re-run |
| Significant result, negligible effect | Large samples make tiny differences significant | Decide on whether the whole 95% interval clears the smallest effect worth shipping |
| LEAKAGE on a feature you trust | It is recorded after the outcome (refunds, cancellation fields) | Check when the field is written; if after the prediction moment, drop it |
| BELOW_BASELINE with a good AUC | Imbalanced classes and a 0.5 threshold | Pick the threshold on validation data from error costs; report recall/precision, not accuracy |
| NOT_COMPARABLE | Runs evaluated on different data versions or splits | Re-run on one split, or compare only within a split |
| p-value differs slightly from another tool | Different interval method or continuity correction | The t and chi-square tails here are exact; the proportion interval is Wald (stated in the output) |

## Success Criteria

- Every ML project follows the Define-Collect-Engineer-Train-Evaluate-Communicate workflow before deployment.
- `feature_selector.py` runs on the training table before any model is trained, and every LEAKAGE finding is resolved.
- Runs are compared with `experiment_tracker.py compare` only when it exits 0 (same data and split, same metrics).
- Model evaluation reports include at least 3 metrics (e.g., F1, AUC-ROC, precision) and comparison against a baseline.
- A/B tests pre-register the hypothesis, sample size calculation, and primary metric before data collection begins.
- Statistical tests report effect size and confidence intervals, not just p-values.
- Business impact is quantified in dollar terms or user-metric terms (computed from the evaluation, not estimated).

## Scope & Limitations

**In scope:** experiment design and sizing, A/B readouts from raw exports, significance tests with intervals, feature screening, model evaluation from predictions, experiment comparison.

**Out of scope:** training models (the snippets above show the shape; the tools evaluate their output), deployment and drift monitoring (`ml-ops-engineer`), test selection for unusual designs and multiplicity beyond Bonferroni (`statistical-analyst`), data-quality profiling (`data-analyst`).

**Limitations:** standard library only and in-memory CSV/JSON. Sequential (always-valid) testing is not implemented: if the test was peeked at, say so and treat the readout as exploratory. Mutual information on numeric features uses 10 equal-frequency bins, an approximation. Thresholds marked *heuristic* in the output (SRM alarm p < 0.001, leakage shares, calibration gap 0.10, 30 rows per class) are this skill's defaults, not published standards.

## Integration Points

- **MLOps Engineer** (`data-analytics/ml-ops-engineer`): Trained models are handed off for production deployment, monitoring, and registry management.
- **Data Analyst** (`data-analytics/data-analyst`): Complex analytical questions requiring predictive modeling are escalated from the analyst to the data scientist.
- **Analytics Engineer** (`data-analytics/analytics-engineer`): Feature engineering pipelines may depend on mart models as upstream data sources.
- **Product Team** (`product-team/`): Experiment results inform product decisions; A/B test designs are co-created with product managers.
- **Engineering** (`engineering/senior-ml-engineer`): Algorithm implementation details and model architecture decisions bridge data science and ML engineering.

Files in this skill

  • SKILL.md12.3 KB
  • scripts/experiment_tracker.py7.3 KB
  • scripts/feature_selector.py9.2 KB
  • scripts/hypothesis_tester.py12.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in data-ai →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.