Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

code-best-practice

БесплатноБез исполняемых скриптовНе проверен

PyMC-Marketing coding conventions, preferred implementations, and style guidelines.

pymc-labsот 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 pydantic for runtime validation of user inputs in __init__ methods.
  • Names: Model variable, dimension, fixed column, InferenceData group, idata.attrs key and serialization key (__type__) names that more than one place in the library has to agree on are Final attributes of plain classes in the pymc_marketing/names/ package (__init__.py for 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.md lists the cases that stay literal, for example a name that a single place uses, a user-chosen name and its default, a model_config key, and the MMM dims where a typo raises. The validate-names pre-commit hook checks the rule. Do not use StrEnum for names: PyMC keeps the enum member as the variable name. Tests keep the literal strings, and tests/test_names.py pins 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:: python directive 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

  1. Use pm.Data for 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")
        ...
    
  2. Batch Dimensions (Coords): Use named dimensions (dims) instead of raw shapes. This integrates with xarray for post-processing.

    # Good
    alpha = pm.Normal("alpha", mu=0, sigma=1, dims="channel")
    
  3. 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:

  1. __init__:

Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить code-best-practice с