working-with-notebooks
БесплатноБез исполняемых скриптовНе проверенFixing and validating Jupyter notebooks in pymc-marketing. Use when notebooks fail CI, need arviz_plots 2.x migration fixes, or when source code changes…
от pymc-labs★ 1 317 звёзд на GitHubОб этом скилле
Working with Notebooks
How to efficiently debug, fix, and validate notebooks in pymc-marketing.
1. The Mock Runner (fast local testing)
The mock runner injects mocked PyMC sampling into notebooks, letting you check for runtime errors without real MCMC. See scripts/run_notebooks/README.md.
Run a single notebook locally
uv run python scripts/run_notebooks/runner.py --notebooks docs/source/notebooks/mmm/mmm_example.ipynb
Run multiple notebooks
uv run python scripts/run_notebooks/runner.py --notebooks docs/source/notebooks/clv/sbg.ipynb docs/source/notebooks/mmm/mmm_example.ipynb
Run by category (CI-like)
uv run python scripts/run_notebooks/runner.py --exclude-dirs mmm # non-MMM only
uv run python scripts/run_notebooks/runner.py --exclude-dirs clv bass customer_choice general # MMM only
2. Real Notebook Execution (for functional code changes)
When source code changes affect model outputs, notebooks must be re-executed with real sampling to generate updated output cells.
Recommended: jupyter execute --inplace
# Clear stale outputs first
uv run jupyter nbconvert --clear-output docs/source/notebooks/mmm/mmm_example.ipynb
# Real execution with full MCMC
uv run jupyter execute docs/source/notebooks/mmm/mmm_example.ipynb --inplace
# Clean up auto-generated checkpoint dirs
find docs/source/notebooks/mmm -name .ipynb_checkpoints -type d -exec rm -rf {} +
Alternative: jupyter nbconvert
jupyter nbconvert --to notebook --execute --inplace docs/source/notebooks/mmm/mmm_example.ipynb
When to execute vs mock
| Scenario | Tool |
|---|---|
| Notebook API migration (plot_dist, DataTree, kwarg changes) | Mock runner |
| Source code changes (model fixes, new return types) | Real execution |
| Before pushing ANY notebook change | Mock runner (minimum) |
| Before pushing functional model changes | Both: real execution + mock runner |
3. Core Workflow (Iteration Loop)
CRITICAL: Never push until all targeted notebooks pass locally.
1. Identify failing notebooks (from CI or initial mock run)
2. FOR EACH notebook (one at a time):
a. Run mock runner: python scripts/run_notebooks/runner.py --notebooks <path>
b. Read the error (Cell In[X], exception type, traceback)
c. Identify the pattern (see §4 below)
d. Fix the notebook cell
e. Repeat a-d until mock runner passes
3. Run ruff on changed files:
ruff check --fix <files>
ruff format <files>
4. Run pre-commit (or at minimum: ruff check + ruff format + mypy)
5. Push ONCE when all notebooks pass
4. Common Notebook Failure Patterns
B10: Bare DataArray/ndarray passed to plot_dist/plot_forest
# ❌ BROKEN — KeyError: 'posterior' or IndexError
azp.plot_dist(my_dataarray)
azp.plot_dist(my_numpy_array)
# ✅ FIXED — wrap in Dataset
azp.plot_dist(my_dataarray.to_dataset(name="var_name"))
azp.plot_dist(xr.Dataset({"x": xr.DataArray(data, dims=["sample"])}))
B11: figsize → figure_kwargs
# ❌ — ValueError: extra keywords
azp.plot_forest(idata, figsize=(8, 8))
# ✅
azp.plot_forest(idata, figure_kwargs={"figsize": (8, 8)})
B12: rug=True removed
# ❌ — ValueError: extra keywords
azp.plot_dist(idata, rug=True)
# ✅ — just remove rug=True
azp.plot_dist(idata)
B13: sample_dims mismatch
# ❌ — ValueError: sample_dims not found
azp.plot_dist(xr.Dataset({"x": data}), sample_dims=["sample"]) # data has chain/draw
# ✅ — remove sample_dims (auto-detect) or match data dims
azp.plot_dist(xr.Dataset({"x": data})) # auto-detect for chain/draw data
azp.plot_dist(xr.Dataset({"x": data}), sample_dims=["sample"]) # for pre-stacked data
B14: List-based plot_forest with model_names
# ❌ — TypeError: list indices must be integers
azp.plot_forest([idata1, idata2], model_names=["A", "B"], ...)
# ✅ — combine into single DataTree with model dim
combined = xr.concat([ds1, ds2], dim="model").assign_coords(model=["A", "B"])
dt = xr.DataTree.from_dict({"/posterior": xr.DataTree(combined)})
azp.plot_forest(dt, ...)
B15/B16: Return type — PlotCollection, not axes
# ❌ — TypeError: 'PlotCollection' object is not subscriptable
ax = azp.plot_forest(idata, ...); ax[0].set_title("...")
# ✅ — extract axes from PlotCollection
pc = azp.plot_forest(idata, ...)
ax = pc.viz["/"]["figure"].values.item().axes[0]
ax.set_title("...")
B17: compact=True removed
# ❌ — ValueError: extra keywords
azp.plot_trace(idata, compact=True)
# ✅ — remove
azp.plot_trace(idata)
B18: group parameter for posterior_predictive
# ❌ — KeyError: 'posterior'
azp.plot_dist(pp_idata) # pm.sample_posterior_predictive result
# ✅
azp.plot_dist(pp_idata, group="posterior_predictive")
B20: Missing xarray import
# ❌ — NameError: name 'xr' is not defined
# ✅ — add to imports cell:
import xarray as xr
B22: hdi_prob → prob, ci_
Установить working-with-notebooks в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл working-with-notebooks?
Fixing and validating Jupyter notebooks in pymc-marketing. Use when notebooks fail CI, need arviz_plots 2.x migration fixes, or when source code changes require notebook output updates.
Как установить скилл working-with-notebooks?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл working-with-notebooks запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic