code-best-practice
БесплатноБез исполняемых скриптовНе проверенPyMC-Marketing coding conventions, preferred implementations, and style guidelines.
от pymc-labs★ 1 317 звёзд на GitHubОб этом скилле
PyMC-Marketing Best Practices Guide
This document outlines the coding conventions, preferred implementations, and style guidelines for contributing to pymc-marketing.
1. Coding Style & Standards
We follow strict linting and formatting rules enforced by Ruff and MyPy.
Python Conventions
- Type Hints: All function arguments and return types must be typed.
# Good def calculate_metric(data: pd.DataFrame, col: str) -> xarray.DataArray: ... # Bad def calculate_metric(data, col): ... - Line Length: Maximum 120 characters.
- Imports: Sorted automatically by Ruff.
- Validation: Use
pydanticfor runtime validation of user inputs in__init__methods. - Names: Model variable, dimension, fixed column, InferenceData group,
idata.attrskey and serialization key (__type__) names that more than one place in the library has to agree on areFinalattributes of plain classes in thepymc_marketing/names/package (__init__.pyfor the shared names,mmm.py,clv.py,customer_choice.py,bass.py). Use the constant instead of the string literal and add new names there.CONTRIBUTING.mdlists the cases that stay literal, for example a name that a single place uses, a user-chosen name and its default, amodel_configkey, and the MMM dims where a typo raises. Thevalidate-namespre-commit hook checks the rule. Do not useStrEnumfor names: PyMC keeps the enum member as the variable name. Tests keep the literal strings, andtests/test_names.pypins every value.# Good from pymc_marketing.names.mmm import Var if Var.CHANNEL_CONTRIBUTION in idata.posterior: ... # Bad: a typo returns False instead of raising if "channel_contribution" in idata.posterior: ...
Docstrings (NumPy Style)
All public classes and functions must have docstrings following the NumPy style.
- Sections: Summary, Parameters, Returns, References (if applicable), Examples.
- Math: Include citations to relevant papers for statistical models.
- Examples: Use
.. code-block:: pythondirective for code examples.
def expected_purchases(self, future_t: int) -> xarray.DataArray:
"""
Compute expected number of future purchases.
Parameters
----------
future_t : int
Number of time periods to predict.
Returns
-------
xarray.DataArray
The expected number of purchases.
Examples
--------
.. code-block:: python
model = MyModel(data)
model.fit()
model.expected_purchases(future_t=12)
References
----------
.. [1] Fader, P. S., et al. (2005). "Counting Your Customers..."
"""
2. Preferred Implementations for Speed & Scalability
Vectorization over Loops
Avoid Python loops for mathematical operations. Use numpy, xarray, or pytensor (via pymc) broadcasting.
- Why: Python loops are slow; vectorized operations in C/Fortran backends are orders of magnitude faster.
# Bad: Iterating over customers
results = []
for customer in customers:
results.append(calculate_val(customer))
# Good: Vectorized operation
results = alpha * np.exp(-beta * data)
Efficient PyMC Modeling
Use
pm.Datafor Mutable Inputs: Allows you to change data (e.g., for out-of-sample predictions) without rebuilding the model graph.# In build_model self.model_coords = {"customer_id": unique_ids} with pm.Model(coords=self.model_coords) as self.model: # Mutable data container x_data = pm.Data("x_data", data[cols], dims="customer_id") ...Batch Dimensions (Coords): Use named dimensions (
dims) instead of raw shapes. This integrates withxarrayfor post-processing.# Good alpha = pm.Normal("alpha", mu=0, sigma=1, dims="channel")HSGP for Gaussian Processes: For time-varying parameters (like in MMM), prefer Hilbert Space Gaussian Processes (HSGP) over standard GPs. HSGP approximates the GP using basis functions, reducing complexity from $O(n^3)$ to $O(n \cdot m)$.
PyTensor for Optimization & Analysis
When implementing functionality like sensitivity analysis, optimization routines, or complex transformations, prefer pytensor operations over pure Python/NumPy.
- Backend Capabilities: PyTensor graphs can be compiled to C, JAX, or MLX (Apple Silicon), enabling hardware acceleration and automatic differentiation.
- Automatic Differentiation: Essential for gradient-based optimization and sensitivity analysis.
import pytensor.tensor as pt
# Good: PyTensor implementation
def saturation(x, alpha):
return 1 - pt.exp(-alpha * x)
# This graph can now be differentiated with respect to alpha
3. Class Structure & Design Patterns
Model Class Architecture
Models should inherit from base classes (MMM, CLVModel) and implement specific lifecycle methods:
__init__:
Установить code-best-practice в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл code-best-practice?
PyMC-Marketing coding conventions, preferred implementations, and style guidelines.
Как установить скилл code-best-practice?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл code-best-practice запускает скрипты?
Нет, скилл состоит только из инструкций (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