numpy-best-practices — скилл для Claude Code: правила работы с NumPy
Скилл задаёт агенту правила по массивам NumPy: векторизация вместо циклов, типы данных, память, линейная алгебра. Пригодится, когда код на Python считает числа.
npx skills add Mindrally/skills --skill numpy-best-practices -a claude-codeЧто делает numpy-best-practices
Скилл — это набор инструкций, которые агент подхватывает, когда пишет или правит код на NumPy. Внутри разделы по стилю, созданию массивов, индексации, типам данных, производительности, обработке ошибок, генерации случайных чисел, линейной алгебре и тестам. Никаких скриптов и внешних инструментов: только текстовые правила.
Что он реально меняет в поведении агента. Вместо циклов по элементам тот станет писать векторизованные операции и ufuncs, для известного размера массива возьмёт np.zeros() или np.empty(), для систем уравнений — np.linalg.solve() вместо обращения матрицы. Отдельно оговорены dtype, переполнение целых, разница между view и копией, np.errstate() для контроля ошибок плавающей точки. Случайные числа — через np.random.default_rng(), а не через старый np.random.
Скилл ничего не устанавливает в проект: NumPy должен быть в вашем окружении сам, иначе примеры агента просто не запустятся. Тесты он советует писать на pytest с проверками из np.testing. Если вы намеренно пишете цикл по массиву — например, для наглядности в учебном коде — агент будет тянуть вас к векторизации, и это придётся оговорить отдельно.
Какие задачи решает
- переписать цикл по элементам массива на векторизованную операцию
- выбрать dtype и не поймать переполнение целых
- сократить копирование массивов и сэкономить память
- решить систему линейных уравнений без обращения матрицы
- получить воспроизводимые случайные числа через Generator API
Примеры запросов агенту
- Перепиши этот цикл по массиву на векторизацию с NumPy
- Проверь мой код на NumPy: где тут лишние копии массивов и неверные dtype?
- Напиши тесты для этой функции на pytest с np.testing
Как установить numpy-best-practices
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill numpy-best-practices -a claude-code2Вручную: положить файлы
~/.claude/skills/numpy-best-practices/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/numpy-best-practices/
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill numpy-best-practices -a codex2Вручную: положить файлы
.agents/skills/numpy-best-practices/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill numpy-best-practices -a cursor2Вручную: положить файлы
.cursor/skills/numpy-best-practices/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install Mindrally/skills numpy-best-practices2Вручную: положить файлы
.github/skills/numpy-best-practices/SKILL.md1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill numpy-best-practices -a gemini-cli2Командой платформы
gemini skills install https://github.com/Mindrally/skills --path numpy-best-practicesВручную: положить файлы
.devin/skills/numpy-best-practices/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill numpy-best-practices -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о numpy-best-practices
Как установить numpy-best-practices в Claude?
Выполните npx skills add Mindrally/skills --skill numpy-best-practices -a claude-code. После этого файл скилла появится по пути ~/.claude/skills/numpy-best-practices/SKILL.md.
Что делает numpy-best-practices?
Даёт агенту свод правил по программированию на NumPy: векторизация, работа с памятью, типы данных, линейная алгебра, генерация случайных чисел и тесты. Агент применяет их, когда пишет или правит такой код.
Нужно ли что-то ставить в проект заранее?
Сам скилл — только инструкции. Чтобы примеры агента запускались, NumPy должен быть установлен в вашем окружении.
Исходный текст
SKILL.md · Apache-2.0
--- name: numpy-best-practices description: Best practices for NumPy array programming, numerical computing, and performance optimization in Python metadata: maintainer: Mindrally source: https://github.com/Mindrally/skills --- # NumPy Best Practices Expert guidelines for NumPy development, focusing on array programming, numerical computing, and performance optimization. ## Code Style and Structure - Write concise, technical Python code with accurate NumPy examples - Prefer vectorized operations over explicit loops for performance - Use descriptive variable names reflecting data content (e.g., `weights`, `gradients`, `input_array`) - Follow PEP 8 style guidelines for Python code - Use functional programming patterns when appropriate ## Array Creation and Manipulation - Use appropriate array creation functions: `np.array()`, `np.zeros()`, `np.ones()`, `np.empty()`, `np.arange()`, `np.linspace()` - Prefer `np.zeros()` or `np.empty()` for pre-allocation when array size is known - Use `np.concatenate()`, `np.vstack()`, `np.hstack()` for combining arrays - Leverage broadcasting for operations on arrays with different shapes ## Indexing and Slicing - Use advanced indexing with boolean arrays for conditional selection - Prefer views over copies when possible to save memory - Use `np.where()` for conditional element selection - Understand the difference between fancy indexing (creates copy) and basic slicing (creates view) ## Data Types - Specify appropriate data types explicitly using `dtype` parameter - Use `np.float32` for memory-efficient computations when full precision is not needed - Be aware of integer overflow with fixed-size integer types - Use `np.asarray()` for type conversion without unnecessary copies ## Performance Optimization ### Vectorization - Always prefer vectorized operations over Python loops - Use NumPy universal functions (ufuncs) for element-wise operations - Leverage `np.einsum()` for complex tensor operations - Use `np.dot()` or `@` operator for matrix multiplication ### Memory Management - Use `np.ndarray.flags` to check memory layout (C-contiguous vs Fortran-contiguous) - Prefer in-place operations with `out` parameter when possible - Use memory-mapped arrays (`np.memmap`) for large datasets - Be mindful of array copies vs views ### Computation Efficiency - Use `np.sum()`, `np.mean()`, `np.std()` with `axis` parameter for aggregations - Leverage `np.cumsum()`, `np.cumprod()` for cumulative operations - Use `np.searchsorted()` for efficient sorted array operations ## Error Handling and Validation - Validate input shapes and data types before computations - Use assertions for dimension checking with informative messages - Handle NaN and Inf values appropriately with `np.isnan()`, `np.isinf()` - Use `np.errstate()` context manager for controlling floating-point error handling ## Random Number Generation - Use `np.random.default_rng()` for modern random number generation - Set seeds for reproducibility: `rng = np.random.default_rng(seed=42)` - Prefer the new Generator API over legacy `np.random` functions - Use appropriate distributions: `rng.normal()`, `rng.uniform()`, `rng.choice()` ## Linear Algebra - Use `np.linalg` for linear algebra operations - Leverage `np.linalg.solve()` instead of computing inverse for linear systems - Use `np.linalg.eig()`, `np.linalg.svd()` for decompositions - Check matrix condition with `np.linalg.cond()` before inversion ## Testing and Documentation - Write unit tests using `pytest` with `np.testing` assertions - Use `np.testing.assert_array_equal()` for exact comparisons - Use `np.testing.assert_array_almost_equal()` for floating-point comparisons - Include comprehensive docstrings following NumPy docstring format ## Key Conventions - Import as `import numpy as np` - Use `snake_case` for variables and functions - Document array shapes in docstrings - Profile code with `%timeit` to identify bottlenecks
© Mindrally · Apache-2.0 · Mindrally/skills