mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
---
|
||||
description: This rule outlines best practices for using the pandas library in Python, covering code style, performance, data handling, and testing. It aims to promote maintainable, efficient, and robust data analysis workflows.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Pandas Best Practices
|
||||
|
||||
This document provides guidelines for writing high-quality pandas code, covering various aspects from code style to performance optimization.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- Organize your project with a clear directory structure.
|
||||
- Use separate directories for data, scripts, modules, tests, and documentation.
|
||||
- Example:
|
||||
|
||||
project_root/
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ └── processed/
|
||||
├── src/
|
||||
│ ├── modules/
|
||||
│ │ ├── data_cleaning.py
|
||||
│ │ ├── feature_engineering.py
|
||||
│ │ └── ...
|
||||
│ ├── main.py
|
||||
├── tests/
|
||||
│ ├── unit/
|
||||
│ ├── integration/
|
||||
│ └── ...
|
||||
├── docs/
|
||||
├── notebooks/
|
||||
├── requirements.txt
|
||||
└── ...
|
||||
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent file names.
|
||||
- Use snake_case for Python files and variables.
|
||||
- Example: `data_processing.py`, `load_data.py`
|
||||
|
||||
- **Module Organization:**
|
||||
- Break down your code into reusable modules.
|
||||
- Each module should focus on a specific task or functionality.
|
||||
- Use clear and concise function and class names within modules.
|
||||
- Follow the Single Responsibility Principle (SRP).
|
||||
|
||||
- **Component Architecture:**
|
||||
- Design your pandas-based applications with a clear component architecture.
|
||||
- Separate data loading, preprocessing, analysis, and visualization into distinct components.
|
||||
- Use classes to encapsulate related functionality and data.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Split large pandas operations into smaller, more manageable steps.
|
||||
- Use functions or methods to encapsulate these steps.
|
||||
- This improves readability and makes debugging easier.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns Specific to Pandas:**
|
||||
- **Chain of Responsibility:** Use method chaining to perform a sequence of operations on a DataFrame.
|
||||
- **Strategy Pattern:** Implement different data processing strategies based on input parameters.
|
||||
- **Factory Pattern:** Use factory functions to create DataFrames or Series from various sources.
|
||||
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Data Loading:** Use `pd.read_csv()`, `pd.read_excel()`, `pd.read_sql()` to load data from different sources.
|
||||
- **Data Cleaning:** Use `dropna()`, `fillna()`, `replace()` to clean missing or incorrect data.
|
||||
- **Data Transformation:** Use `apply()`, `map()`, `groupby()`, `pivot_table()` to transform data.
|
||||
- **Data Aggregation:** Use `groupby()`, `agg()`, `transform()` to aggregate data.
|
||||
- **Data Visualization:** Use `matplotlib`, `seaborn`, or `plotly` to visualize data.
|
||||
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Iterating over DataFrames with `iterrows()` or `itertuples()`:** These are slow; prefer vectorized operations.
|
||||
- **Chained Indexing:** Avoid using chained indexing (e.g., `df['A']['B']`) as it can lead to unexpected behavior. Use `.loc` or `.iloc` instead.
|
||||
- **Ignoring Data Types:** Always be aware of your data types and convert them appropriately using `astype()`.
|
||||
- **Writing loops to filter/process the data:** Vectorize these operations to avoid performance issues.
|
||||
- **Modifying DataFrame inplace:** Creating copies is a safer approach.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Avoid modifying DataFrames in place unless absolutely necessary.
|
||||
- Make copies of DataFrames using `.copy()` to avoid unintended side effects.
|
||||
- Use functional programming principles where possible to minimize state changes.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try-except` blocks to handle potential errors during data loading, processing, or analysis.
|
||||
- Log errors and warnings using the `logging` module.
|
||||
- Raise exceptions when necessary to signal errors to the calling code.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Vectorization:** Use vectorized operations instead of loops whenever possible. Pandas is optimized for vectorized operations.
|
||||
- **Cython:** Consider using Cython to optimize performance-critical parts of your code.
|
||||
- **Numba:** Use Numba to JIT-compile NumPy and pandas code for improved performance.
|
||||
- **Dask:** Use Dask for parallel processing of large datasets that don't fit in memory.
|
||||
- **Parquet or Feather:** Use Parquet or Feather file formats for efficient data storage and retrieval.
|
||||
- **Categorical Data:** Use categorical data types for columns with a limited number of unique values.
|
||||
|
||||
- **Memory Management:**
|
||||
- **Data Types:** Choose appropriate data types to minimize memory usage (e.g., `int8`, `float32` instead of `int64`, `float64`).
|
||||
- **Chunking:** Load large datasets in chunks to avoid memory errors.
|
||||
- **Garbage Collection:** Use `gc.collect()` to explicitly release memory.
|
||||
- **Sparse Data:** Use sparse data structures for data with many missing values.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **SQL Injection:** When reading data from SQL databases, use parameterized queries or ORM frameworks to prevent SQL injection attacks.
|
||||
- **CSV Injection:** Be cautious when loading CSV files from untrusted sources, as they may contain malicious formulas that can execute arbitrary code.
|
||||
- **Arbitrary Code Execution:** Avoid using `eval()` or `exec()` on data loaded from untrusted sources, as this can lead to arbitrary code execution.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate user inputs to prevent malicious data from entering your pandas workflows.
|
||||
- Use regular expressions or custom validation functions to check the format and content of inputs.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use access control mechanisms to restrict access to sensitive data.
|
||||
- Anonymize or pseudonymize data when possible to protect privacy.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual functions and classes.
|
||||
- Use `pytest` or `unittest` for writing and running tests.
|
||||
- Test edge cases and boundary conditions.
|
||||
- Use assert statements to verify the correctness of your code.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different modules or components.
|
||||
- Test the end-to-end functionality of your pandas-based applications.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize your tests in a separate `tests` directory.
|
||||
- Use a clear naming convention for your test files and functions.
|
||||
- Example: `test_data_cleaning.py`, `test_load_data()`
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units of code during testing.
|
||||
- Use the `unittest.mock` module or third-party libraries like `pytest-mock`.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Forgetting to set the index properly:** This can lead to performance issues when joining or merging DataFrames.
|
||||
- **Incorrectly handling missing data:** Be aware of how missing data is represented in your DataFrames and handle it appropriately.
|
||||
- **Not understanding the difference between `.loc` and `.iloc`:** These methods are used for different types of indexing and can lead to unexpected results if used incorrectly.
|
||||
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Empty DataFrames:** Handle the case where a DataFrame is empty.
|
||||
- **DataFrames with duplicate indices:** Be aware of how pandas handles DataFrames with duplicate indices.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use the `print()` function or the `logging` module to debug your code.
|
||||
- Use a debugger to step through your code and inspect variables.
|
||||
- Use the `pdb` module for interactive debugging.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **Jupyter Notebook/Lab:** For interactive data exploration and analysis.
|
||||
- **VS Code with Python extension:** For code editing, debugging, and testing.
|
||||
- **PyCharm:** A full-featured IDE for Python development.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use `flake8` to lint your code and identify potential issues.
|
||||
- Use `black` to automatically format your code according to PEP 8.
|
||||
- Use `isort` to automatically sort your imports.
|
||||
- Integrate these tools into your pre-commit hooks to ensure consistent code style.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Use CI/CD pipelines to automate the testing and deployment of your pandas-based applications.
|
||||
- Integrate your CI/CD pipelines with your version control system (e.g., GitHub, GitLab, Bitbucket).
|
||||
- Use Docker to containerize your applications for consistent deployment.
|
||||
|
||||
This comprehensive guide covers the key aspects of pandas best practices and coding standards. By following these guidelines, you can write more maintainable, efficient, and robust pandas code.
|
||||
@@ -0,0 +1,381 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for PyTorch development, covering code organization, performance optimization, security, testing, and common pitfalls. It aims to ensure readable, maintainable, and efficient PyTorch code.
|
||||
globs: **/*.py
|
||||
---
|
||||
# PyTorch Best Practices and Coding Standards
|
||||
|
||||
This document provides comprehensive guidelines for developing PyTorch projects, encompassing code organization, performance optimization, security, testing methodologies, and common pitfalls. Adhering to these best practices will result in more readable, maintainable, and efficient PyTorch code.
|
||||
|
||||
**Library Information:**
|
||||
- Name: PyTorch
|
||||
- Category: ai_ml
|
||||
- Subcategory: machine_learning
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
A well-organized directory structure enhances code maintainability and collaboration. Here's a recommended structure for PyTorch projects:
|
||||
|
||||
|
||||
project_root/
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ ├── processed/
|
||||
│ └── ...
|
||||
├── models/
|
||||
│ ├── layers.py
|
||||
│ ├── networks.py
|
||||
│ ├── losses.py
|
||||
│ ├── ops.py
|
||||
│ └── model_name.py
|
||||
├── src/
|
||||
│ ├── data/
|
||||
│ │ ├── datasets.py
|
||||
│ │ ├── dataloaders.py
|
||||
│ │ └── transforms.py
|
||||
│ ├── models/
|
||||
│ │ └── ... (model-related code)
|
||||
│ ├── utils/
|
||||
│ │ └── ... (utility functions)
|
||||
│ └── visualization/
|
||||
│ └── ...
|
||||
├── notebooks/
|
||||
│ └── ... (Jupyter notebooks for experimentation)
|
||||
├── tests/
|
||||
│ ├── unit/
|
||||
│ ├── integration/
|
||||
│ └── ...
|
||||
├── scripts/
|
||||
│ └── train.py
|
||||
│ └── eval.py
|
||||
├── configs/
|
||||
│ └── ... (Configuration files, e.g., YAML)
|
||||
├── README.md
|
||||
├── requirements.txt
|
||||
├── .gitignore
|
||||
└── ...
|
||||
|
||||
|
||||
- `data/`: Stores raw and processed datasets.
|
||||
- `models/`: Contains PyTorch model definitions, layers, and custom loss functions. Separate network architectures, individual layers/blocks, and operations into different files.
|
||||
- `src/`: Holds the main source code, including data loading, model definitions, utility functions, and visualization tools. It's common to split the `src/` folder further based on responsibilities.
|
||||
- `notebooks/`: Jupyter notebooks for experimentation and exploration. Use notebooks for initial exploration and prototyping but transition finalized code to Python scripts.
|
||||
- `tests/`: Unit, integration, and end-to-end tests.
|
||||
- `scripts/`: Training, evaluation, and deployment scripts. The main training script should import model definitions.
|
||||
- `configs/`: Configuration files for hyperparameter settings and other parameters.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
- Use descriptive and consistent file names.
|
||||
- Python files: `lower_with_under.py` (e.g., `data_loader.py`, `model_utils.py`).
|
||||
- Model files: `model_name.py` (e.g., `resnet.py`, `transformer.py`).
|
||||
- Configuration files: `config_name.yaml` (e.g., `train_config.yaml`).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
- Group related functions and classes into modules.
|
||||
- Use clear and concise module names.
|
||||
- Include a docstring at the beginning of each module to describe its purpose.
|
||||
- Follow a consistent import style:
|
||||
python
|
||||
# Standard library imports
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Third-party library imports
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchvision
|
||||
|
||||
# Local application/library imports
|
||||
from src.data import data_loader
|
||||
from src.models import resnet
|
||||
from src.utils import helper_functions
|
||||
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- **`nn.Module`:** The fundamental building block for creating neural networks in PyTorch. Always subclass `nn.Module` for defining models, layers, and custom operations.
|
||||
- **`forward()` method:** Implement the forward pass of your module within the `forward()` method. PyTorch uses the `__call__` method, which executes `forward()`, to pass data through the model.
|
||||
- **Separation of Concerns:** Design models as compositions of smaller, reusable modules. This promotes modularity and simplifies debugging.
|
||||
|
||||
Example:
|
||||
|
||||
python
|
||||
import torch.nn as nn
|
||||
|
||||
class ConvBlock(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
|
||||
super().__init__()
|
||||
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
|
||||
self.relu = nn.ReLU()
|
||||
self.bn = nn.BatchNorm2d(out_channels)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
x = self.relu(x)
|
||||
x = self.bn(x)
|
||||
return x
|
||||
|
||||
class SimpleCNN(nn.Module):
|
||||
def __init__(self, num_classes=10):
|
||||
super().__init__()
|
||||
self.conv1 = ConvBlock(3, 32)
|
||||
self.conv2 = ConvBlock(32, 64)
|
||||
self.pool = nn.MaxPool2d(2, 2)
|
||||
self.fc = nn.Linear(64 * 8 * 8, num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.pool(x)
|
||||
x = self.conv2(x)
|
||||
x = self.pool(x)
|
||||
x = x.view(x.size(0), -1)
|
||||
x = self.fc(x)
|
||||
return x
|
||||
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
- **Vertical Splitting (Feature-based):** Divide code based on features or functionalities (e.g., data loading, model definition, training loop). This approach aligns well with module organization.
|
||||
- **Horizontal Splitting (Layer-based):** Split code based on layers or components of a neural network. This is suitable for complex models with distinct layers (e.g., encoder, decoder). The `models/` directory structure supports this.
|
||||
- **Microservices (for large projects):** For very large and complex machine learning deployments, consider breaking the workload into microservices - one for training, one for inference, another for data preprocessing, etc. This can improve scalability and fault tolerance.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to PyTorch
|
||||
|
||||
- **`nn.Sequential`:** A container for chaining layers in a sequential manner. Suitable for simple, linear models.
|
||||
- **Custom `nn.Module`:** Create custom modules for encapsulating reusable blocks of layers or operations. This promotes modularity and code reuse.
|
||||
- **Hooks:** Utilize forward and backward hooks for inspecting and modifying activations and gradients during training. Useful for debugging and research.
|
||||
- **DataParallel/DistributedDataParallel:** Wrap models with `DataParallel` or `DistributedDataParallel` to leverage multiple GPUs for training. `DistributedDataParallel` is generally preferred for multi-node training and offers better performance.
|
||||
- **Transfer Learning:** Reuse pretrained models from `torchvision.models` as a starting point for new tasks. Fine-tune the pretrained weights or add custom layers.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **Data Loading:** Use `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` for efficient data loading and batching. Use custom Datasets to control data transformation.
|
||||
- **Model Definition:** Define models as classes that inherit from `nn.Module`. Use the layers defined in `torch.nn` to build the model.
|
||||
- **Training Loop:** Implement a structured training loop that iterates over epochs and batches. Include forward pass, loss calculation, backward pass, and optimization steps.
|
||||
- **Validation:** Evaluate model performance on a validation set during training to monitor overfitting and tune hyperparameters.
|
||||
- **Checkpointing:** Save model weights and optimizer state during training to resume training or load the best model.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **Hardcoding shapes:** Avoid hardcoding input or output shapes. Use dynamic shapes or calculate shapes based on input data.
|
||||
- **Global Variables:** Minimize the use of global variables. Pass data and configurations as function arguments.
|
||||
- **Magic Numbers:** Avoid using magic numbers without explanation. Define constants with descriptive names.
|
||||
- **Deeply Nested Loops:** Optimize performance-critical sections of code. Consider using vectorized operations or optimized data structures to avoid nested loops where possible.
|
||||
- **Ignoring Warnings:** Address all warnings. They often indicate potential problems or inefficiencies in your code. Use a debugger and logging to diagnose runtime behavior.
|
||||
- **Over-commenting:** Avoid redundant comments that simply reiterate the code. Focus on explaining the *why* rather than the *what*.
|
||||
- **Not using GPU when Available:** Always check if cuda is available and moves tensors and models to cuda for faster training and inference.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- **Model Parameters:** Model parameters are automatically managed by PyTorch. Use `nn.Parameter` to register tensors as model parameters.
|
||||
- **Buffers:** Use `nn.Buffer` to store non-trainable tensors that are part of the model state (e.g., running statistics in BatchNorm).
|
||||
- **Optimizer State:** The optimizer maintains its own state, such as learning rate and momentum. Access and modify optimizer state through the `optimizer.state_dict()` and `optimizer.load_state_dict()` methods.
|
||||
- **Random Seeds:** Set random seeds for reproducibility:
|
||||
|
||||
python
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
def set_seed(seed):
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed) # if using multiple GPUs
|
||||
torch.backends.cudnn.deterministic = True #Ensures that CUDA uses deterministic algorithms.
|
||||
torch.backends.cudnn.benchmark = False #Prevents CUDA from benchmarking multiple convolution algorithms.
|
||||
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- **Specific Exception Handling:** Catch specific exceptions rather than using bare `except` clauses. This allows you to handle different error scenarios appropriately.
|
||||
- **Logging:** Use the `logging` module to log errors and warnings. Include relevant information, such as timestamps, file names, and line numbers.
|
||||
- **Assertion Statements:** Use `assert` statements to check for unexpected conditions. This can help catch errors early in development.
|
||||
- **Custom Exceptions:** Define custom exception classes for specific error conditions in your application. This improves code readability and maintainability.
|
||||
- **Graceful Degradation:** Implement mechanisms to handle errors gracefully, such as providing default values or skipping problematic data points. Avoid crashing the application.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **GPU Utilization:** Use a GPU for training and inference. Move models and tensors to the GPU using `.to('cuda')`.
|
||||
- **Batch Size:** Tune the batch size to maximize GPU utilization without running out of memory. Larger batch sizes generally lead to better performance.
|
||||
- **Data Loading:** Optimize data loading by using multiple workers in the `DataLoader`. Consider using asynchronous data loading techniques.
|
||||
- **Mixed Precision Training:** Use mixed precision training (`torch.cuda.amp`) to reduce memory usage and accelerate training on NVIDIA GPUs with Tensor Cores.
|
||||
- **Gradient Accumulation:** Accumulate gradients over multiple batches to simulate a larger batch size when memory is limited.
|
||||
- **Operator Fusion:** Utilize PyTorch's JIT compiler (`torch.jit.script` or `torch.jit.trace`) to fuse multiple operations into a single kernel, reducing overhead and improving performance.
|
||||
- **Memory Usage:** When using `DataParallel`, ensure that the input data is evenly distributed across the available GPUs. Uneven data distribution can result in memory imbalances and slow down training.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- **Tensor Deletion:** Delete unnecessary tensors using `del` to free up memory.
|
||||
- **`torch.no_grad()`:** Use `torch.no_grad()` during inference to disable gradient calculation and reduce memory usage.
|
||||
- **In-place Operations:** Use in-place operations (e.g., `x.add_(1)`) to modify tensors directly without creating new tensors. Be cautious with in-place operations as they can sometimes cause issues with autograd.
|
||||
- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- **Garbage Collection:** Explicitly call `gc.collect()` to force garbage collection. This can be useful in situations where memory is not being released promptly.
|
||||
|
||||
### 3.3 Rendering Optimization (if applicable)
|
||||
|
||||
- This section applies if PyTorch is used for rendering tasks (e.g., neural rendering).
|
||||
- **Optimize Mesh Data Structures:** Use efficient mesh data structures to reduce memory usage and improve rendering performance.
|
||||
- **Level of Detail (LOD):** Implement LOD techniques to reduce the complexity of rendered objects at a distance.
|
||||
- **Caching:** Cache frequently accessed data to reduce rendering time.
|
||||
|
||||
### 3.4 Bundle Size Optimization (if applicable)
|
||||
|
||||
- This section applies if PyTorch models are deployed in web applications or other size-sensitive environments.
|
||||
- **Model Quantization:** Quantize models to reduce their size. Use `torch.quantization` to quantize models to 8-bit integers.
|
||||
- **Model Pruning:** Prune unimportant weights from models to reduce their size. Use `torch.nn.utils.prune` to prune models.
|
||||
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- **Lazy Initialization:** Defer the initialization of expensive resources until they are needed.
|
||||
- **Data Streaming:** Load data in smaller chunks instead of loading the entire dataset into memory at once.
|
||||
- **Just-In-Time (JIT) Compilation:** Use `torch.jit.script` or `torch.jit.trace` to compile models just before they are used. This can improve performance and reduce memory usage.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Implement techniques like adversarial training and input sanitization.
|
||||
- **Data Poisoning:** Protect against data poisoning attacks by validating input data and using robust training techniques.
|
||||
- **Model Extraction:** Prevent model extraction by limiting access to model weights and predictions.
|
||||
- **Integer Overflow:** Be aware of integer overflow issues in user-provided data.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- **Data Type Validation:** Ensure that input data has the correct data type.
|
||||
- **Range Validation:** Check that input values are within a valid range.
|
||||
- **Format Validation:** Validate the format of input strings (e.g., URLs, email addresses).
|
||||
- **Sanitization:** Sanitize input data to remove potentially malicious characters or code.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- **API Keys:** Use API keys to authenticate clients accessing your models.
|
||||
- **OAuth 2.0:** Implement OAuth 2.0 for secure authorization of user access.
|
||||
- **Role-Based Access Control (RBAC):** Use RBAC to restrict access to specific models or functionalities based on user roles.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Anonymization:** Anonymize data to protect user privacy.
|
||||
- **Differential Privacy:** Use differential privacy techniques to protect the privacy of training data.
|
||||
- **Access Control:** Implement strict access control policies to limit access to sensitive data.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- **HTTPS:** Use HTTPS to encrypt communication between clients and your API.
|
||||
- **TLS/SSL:** Use TLS/SSL certificates to secure your API endpoints.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
|
||||
- **Input Validation:** Always validate and sanitize input data to prevent injection attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- **Test Individual Modules:** Write unit tests for individual modules to ensure they function correctly.
|
||||
- **Test Edge Cases:** Test edge cases and boundary conditions to identify potential errors.
|
||||
- **Use Assertions:** Use assertions to verify expected outcomes.
|
||||
- **Test Model Outputs:** Verify that model outputs have the correct shape and data type.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- **Test Interactions Between Modules:** Write integration tests to ensure that different modules work together correctly.
|
||||
- **Test Data Pipelines:** Test the entire data pipeline, from data loading to model output.
|
||||
- **Test End-to-End Functionality:** Test the entire application to ensure that it meets the requirements.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
- **Simulate User Interactions:** Write end-to-end tests that simulate user interactions with the application.
|
||||
- **Test the Entire System:** Test the entire system, including the user interface, API, and database.
|
||||
- **Verify Expected Outcomes:** Verify that the application produces the expected outcomes.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- **Separate Test Files:** Create separate test files for each module or component.
|
||||
- **Use a Test Runner:** Use a test runner (e.g., `pytest`, `unittest`) to discover and run tests.
|
||||
- **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- **Use Mocks to Isolate Units:** Use mocks to isolate units of code from their dependencies.
|
||||
- **Use Stubs to Provide Test Data:** Use stubs to provide test data to units of code.
|
||||
- **Verify Interactions with Dependencies:** Verify that units of code interact with their dependencies as expected.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Incorrect Tensor Shapes:** Pay close attention to tensor shapes when performing operations. Use `torch.Size()` to check tensor shapes.
|
||||
- **Gradient Issues:** Be mindful of gradient flow. Ensure that gradients are properly calculated and propagated through the network. Use `torch.autograd.set_detect_anomaly(True)` for debugging autograd issues.
|
||||
- **Memory Leaks:** Be careful to deallocate tensors when they are no longer needed. Use memory profiling tools to identify memory leaks.
|
||||
- **Data Type Mismatches:** Ensure that tensors have the correct data type (e.g., `torch.float32`, `torch.int64`).
|
||||
- **Device Mismatches:** Ensure that tensors and models are on the same device (CPU or GPU).
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
- **Empty Datasets:** Handle cases where datasets are empty or contain missing data.
|
||||
- **Out-of-Memory Errors:** Handle out-of-memory errors gracefully by reducing batch size or using gradient accumulation.
|
||||
- **Numerical Instability:** Be aware of numerical instability issues, such as vanishing or exploding gradients. Use techniques like gradient clipping and batch normalization.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- **Compatibility with Libraries:** Be aware of compatibility issues between different versions of PyTorch and other libraries.
|
||||
- **API Changes:** Track API changes in PyTorch releases and update your code accordingly.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- **Hardware Compatibility:** Ensure that your code is compatible with different hardware configurations (e.g., different GPUs).
|
||||
- **Operating System Compatibility:** Ensure that your code is compatible with different operating systems (e.g., Linux, Windows, macOS).
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- **Print Statements:** Use print statements to inspect the values of tensors and variables.
|
||||
- **Debuggers:** Use a debugger (e.g., `pdb`) to step through your code and inspect the state of your application.
|
||||
- **TensorBoard:** Use TensorBoard to visualize model training progress, including loss curves, metrics, and model architecture.
|
||||
- **`torch.autograd.set_detect_anomaly(True)`:** A powerful tool for debugging autograd issues. It will raise an error when a NaN gradient is detected, helping you pinpoint the source of the problem.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **IDEs:** Visual Studio Code (with Python extension), PyCharm.
|
||||
- **Virtual Environments:** `venv`, `conda`.
|
||||
- **Debugging Tools:** `pdb`, `ipdb`.
|
||||
- **Profiling Tools:** `torch.profiler`, `memory_profiler`.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- **`requirements.txt`:** Specify project dependencies in a `requirements.txt` file. Use `pip freeze > requirements.txt` to generate the file.
|
||||
|
||||
Example `requirements.txt`:
|
||||
|
||||
torch==1.13.1
|
||||
torchvision==0.14.1
|
||||
numpy==1.24.1
|
||||
|
||||
- **`setup.py` (for libraries):** Use `setup.py` to define your library's metadata and dependencies.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- **Linters:** `flake8`, `pylint`.
|
||||
- **Formatters:** `black`, `autopep8`.
|
||||
- **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- **Model Serialization:** Use `torch.save` to serialize models for deployment. Use `torch.load` to load models.
|
||||
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
|
||||
- **Serving Frameworks:** Use serving frameworks like TorchServe, FastAPI, or Flask to deploy PyTorch models as REST APIs.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- **Continuous Integration (CI):** Use CI tools like Jenkins, GitHub Actions, or GitLab CI to automatically build and test your code.
|
||||
- **Continuous Deployment (CD):** Use CD tools to automatically deploy your code to production environments.
|
||||
- **Automated Testing:** Integrate automated testing into your CI/CD pipeline to ensure code quality and prevent regressions. Run unit, integration, and end-to-end tests.
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
description: Enforces best practices and coding standards for scikit-learn projects, promoting maintainability, performance, and security. This rule provides guidelines on code organization, common patterns, performance optimization, testing, and common pitfalls.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Scikit-learn Best Practices and Coding Standards
|
||||
|
||||
This document outlines best practices and coding standards for developing with scikit-learn, aiming to improve code quality, maintainability, performance, and security.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- Organize your project into logical modules or components. A typical structure might include:
|
||||
- `src/`: Source code for your project.
|
||||
- `models/`: Contains the implementation of machine learning models.
|
||||
- `features/`: Feature engineering and processing logic.
|
||||
- `utils/`: Utility functions and helper modules.
|
||||
- `data/`: Datasets used for training and testing.
|
||||
- `raw/`: Original, unprocessed data.
|
||||
- `processed/`: Cleaned and preprocessed data.
|
||||
- `notebooks/`: Jupyter notebooks for experimentation and analysis.
|
||||
- `tests/`: Unit and integration tests.
|
||||
- `scripts/`: Scripts for training, evaluation, and deployment.
|
||||
- `config/`: Configuration files (e.g., YAML, JSON).
|
||||
- Example:
|
||||
|
||||
|
||||
project_root/
|
||||
├── src/
|
||||
│ ├── models/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── model_1.py
|
||||
│ │ └── model_2.py
|
||||
│ ├── features/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── feature_engineering.py
|
||||
│ │ └── feature_selection.py
|
||||
│ ├── utils/
|
||||
│ │ ├── __init__.py
|
||||
│ │ └── helpers.py
|
||||
│ ├── __init__.py
|
||||
│ └── main.py
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ │ └── data.csv
|
||||
│ └── processed/
|
||||
│ └── processed_data.csv
|
||||
├── notebooks/
|
||||
│ └── exploratory_data_analysis.ipynb
|
||||
├── tests/
|
||||
│ ├── __init__.py
|
||||
│ ├── test_models.py
|
||||
│ └── test_features.py
|
||||
├── scripts/
|
||||
│ ├── train.py
|
||||
│ └── evaluate.py
|
||||
├── config/
|
||||
│ └── config.yaml
|
||||
├── README.md
|
||||
└── requirements.txt
|
||||
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent names for files and modules.
|
||||
- Prefer snake_case for Python files and variables (e.g., `model_training.py`, `n_samples`).
|
||||
|
||||
- **Module Organization:**
|
||||
- Each module should have a clear and specific purpose.
|
||||
- Use `__init__.py` files to define packages and modules within directories.
|
||||
- Minimize dependencies between modules to improve maintainability.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Design your application with loosely coupled components.
|
||||
- Implement interfaces or abstract classes to define contracts between components.
|
||||
- Use dependency injection to manage dependencies and promote testability.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Split large files into smaller, more manageable modules.
|
||||
- Group related functions and classes into modules based on functionality.
|
||||
- Consider splitting code based on layers (e.g., data access, business logic, presentation).
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Pipeline:** Use scikit-learn's `Pipeline` class to chain together multiple data preprocessing and modeling steps. This helps prevent data leakage and ensures consistent data transformations.
|
||||
- **Model Selection:** Employ techniques like cross-validation and grid search to select the best model and hyperparameters for your data. Use `GridSearchCV` or `RandomizedSearchCV`.
|
||||
- **Ensemble Methods:** Leverage ensemble methods like Random Forests, Gradient Boosting, and Voting Classifiers to improve model accuracy and robustness.
|
||||
- **Custom Transformers:** Create custom transformers using `BaseEstimator` and `TransformerMixin` to encapsulate complex feature engineering logic.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Data Preprocessing:** Always split your data into training and testing sets *before* any preprocessing steps.
|
||||
- **Feature Scaling:** Apply appropriate feature scaling techniques (e.g., StandardScaler, MinMaxScaler) to numerical features before training models.
|
||||
- **Categorical Encoding:** Use one-hot encoding or ordinal encoding for categorical features.
|
||||
- **Missing Value Imputation:** Handle missing values using imputation techniques like mean, median, or k-NN imputation.
|
||||
- **Model Persistence:** Save trained models to disk using `joblib` or `pickle` for later use.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Data Leakage:** Avoid data leakage by preprocessing the entire dataset before splitting into training and testing sets.
|
||||
- **Overfitting:** Be cautious of overfitting by using regularization techniques and cross-validation.
|
||||
- **Ignoring Data Distributions:** Always visualize and understand data distributions before applying transformations or choosing models.
|
||||
- **Hardcoding Parameters:** Avoid hardcoding parameters directly in the code. Use configuration files or command-line arguments instead.
|
||||
- **Ignoring Warnings:** Pay attention to scikit-learn warnings, as they often indicate potential problems with your code or data.
|
||||
|
||||
- **State Management:**
|
||||
- Use classes to encapsulate state and behavior related to models or data processing steps.
|
||||
- Avoid global variables and mutable state whenever possible.
|
||||
- Use immutable data structures where appropriate to prevent unintended side effects.
|
||||
|
||||
- **Error Handling:**
|
||||
- Use try-except blocks to handle exceptions and prevent your application from crashing.
|
||||
- Log errors and warnings to a file or logging service.
|
||||
- Provide informative error messages to users.
|
||||
- Implement retry mechanisms for transient errors.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Vectorization:** Utilize NumPy's vectorized operations to perform calculations on entire arrays instead of looping through individual elements. Use `.values` from pandas DataFrames when passing to scikit-learn.
|
||||
- **Memory Optimization:** Minimize memory usage by using appropriate data types (e.g., `int8`, `float32`) and avoiding unnecessary copies of data.
|
||||
- **Algorithm Selection:** Choose efficient algorithms that are well-suited for your data and task. For example, use `MiniBatchKMeans` for large datasets.
|
||||
- **Parallelization:** Use scikit-learn's built-in support for parallel processing to speed up training and prediction.
|
||||
|
||||
- **Memory Management:**
|
||||
- Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- Release unused memory by deleting variables or using the `gc` module.
|
||||
- Use data streaming techniques for large datasets that don't fit into memory.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Load data and models only when they are needed.
|
||||
- Use generators or iterators to process large datasets in chunks.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Model Poisoning:** Protect against model poisoning attacks by validating input data and sanitizing user-provided data.
|
||||
- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Consider using techniques like adversarial training to improve model robustness.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all input data to ensure it conforms to the expected format and range.
|
||||
- Sanitize user-provided data to prevent injection attacks.
|
||||
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use access control mechanisms to restrict access to data and models.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing:**
|
||||
- Write unit tests for individual functions and classes.
|
||||
- Use mocking to isolate components and test them in isolation.
|
||||
- Assert that your code produces the expected output for different inputs.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify that different components work together correctly.
|
||||
- Test the interaction between your code and external dependencies.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize your tests into a separate directory (e.g., `tests`).
|
||||
- Use descriptive names for your test files and functions.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries like `unittest.mock` or `pytest-mock` to create mock objects for testing.
|
||||
- Use stubs to replace complex dependencies with simpler implementations.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Data Type Mismatches:** Ensure that the data types of your input features are compatible with the model you are using.
|
||||
- **Feature Scaling Issues:** Use the correct scaling method for your features, understanding how each scaler behaves.
|
||||
- **Improper Cross-Validation:** Make sure the cross-validation strategy you choose is appropriate for your dataset and model.
|
||||
- **Version Compatibility:** Be aware of compatibility issues between different versions of scikit-learn and its dependencies.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **IDE:** Use an IDE like VS Code, PyCharm, or JupyterLab.
|
||||
- **Version Control:** Use Git for version control.
|
||||
- **Package Manager:** Use pip or Conda for managing dependencies.
|
||||
- **Virtual Environments:** Create virtual environments for each project to isolate dependencies.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use linters like pylint or flake8 to enforce code style and identify potential errors.
|
||||
- Use formatters like black or autopep8 to automatically format your code.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your code with a CI/CD system like Jenkins, Travis CI, or CircleCI.
|
||||
- Automatically run tests and linters on every commit.
|
||||
- Deploy your application to a production environment automatically.
|
||||
|
||||
## General Coding Style
|
||||
- Use underscores to separate words in non-class names: `n_samples` rather than `nsamples`.
|
||||
- Avoid multiple statements on one line.
|
||||
- Use relative imports for references inside scikit-learn (except for unit tests, which should use absolute imports).
|
||||
|
||||
By following these best practices, you can write cleaner, more maintainable, and more efficient scikit-learn code.
|
||||
@@ -0,0 +1,185 @@
|
||||
---
|
||||
description: Comprehensive guide to TensorFlow best practices, covering code organization, performance, testing, and security for robust and maintainable machine learning projects.
|
||||
globs: **/*.{py,tf,keras}
|
||||
---
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Structure your project into logical directories. For example:
|
||||
|
||||
project_root/
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ └── processed/
|
||||
├── models/
|
||||
│ ├── training/
|
||||
│ └── saved_models/
|
||||
├── src/
|
||||
│ ├── utils/
|
||||
│ ├── layers/
|
||||
│ ├── models/
|
||||
│ ├── training/
|
||||
│ └── evaluation/
|
||||
├── notebooks/ #Jupyter notebooks for experimentation
|
||||
├── tests/
|
||||
├── configs/
|
||||
└── README.md
|
||||
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent names. For example:
|
||||
- `model_name.py`
|
||||
- `data_processing.py`
|
||||
- `train.py`
|
||||
- `evaluate.py`
|
||||
- `layer_name.py`
|
||||
|
||||
- **Module Organization:**
|
||||
- Break down code into reusable modules and functions.
|
||||
- Use `tf.Module` and Keras layers to manage variables. This enables encapsulation and avoids global variable pollution.
|
||||
- Import modules using explicit relative or absolute paths, such as `from src.models import MyModel`.
|
||||
- Group related functionality into modules/packages.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Employ modular design principles.
|
||||
- Keras `Layers` and `Models` promote a component-based architecture. Custom layers should inherit from `tf.keras.layers.Layer`. Custom models inherit from `tf.keras.Model`.
|
||||
- Use dependency injection to decouple components and facilitate testing.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Refactor code into smaller, manageable modules.
|
||||
- Separate data loading, preprocessing, model definition, training, and evaluation into distinct modules.
|
||||
- Implement generator functions or `tf.data.Dataset` pipelines for large datasets to avoid loading all data into memory at once.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Strategy Pattern:** Use different strategies for optimization or regularization.
|
||||
- **Factory Pattern:** Create model architectures dynamically based on configuration.
|
||||
- **Observer Pattern:** Monitor training progress and trigger actions based on metrics.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- Use Keras layers and models to manage variables. Keras handles the underlying TensorFlow operations.
|
||||
- Leverage `tf.data.Dataset` for efficient data loading and preprocessing.
|
||||
- Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **God Classes:** Avoid monolithic classes that perform too many tasks. Break them into smaller, more focused classes or functions.
|
||||
- **Copy-Pasted Code:** Refactor duplicated code into reusable functions or modules.
|
||||
- **Magic Numbers:** Use named constants instead of hardcoded values.
|
||||
- **Global Variables:** Minimize the use of global variables, especially for model parameters.
|
||||
|
||||
- **State Management:**
|
||||
- Use Keras layers and models for managing model state (weights, biases).
|
||||
- Use `tf.Variable` objects for persistent state that needs to be tracked during training.
|
||||
- When creating a model subclass, define trainable weights as tf.Variable objects within the `build()` method.
|
||||
- Consider using `tf.saved_model` to save and load the entire model state, including the computation graph and variable values.
|
||||
|
||||
- **Error Handling:**
|
||||
- Use `tf.debugging.assert_*` functions to check tensor values during development and debugging.
|
||||
- Implement try-except blocks to handle potential exceptions, such as `tf.errors.InvalidArgumentError` or `tf.errors.OutOfRangeError`.
|
||||
- Log errors and warnings using `tf.compat.v1.logging` or the standard `logging` module.
|
||||
- Ensure error messages are informative and actionable.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance. Use autograph (automatic graph construction).
|
||||
- Optimize data input pipelines using `tf.data.Dataset.prefetch` and `tf.data.Dataset.cache`.
|
||||
- Experiment with different optimizers (e.g., Adam, SGD) and learning rates.
|
||||
- Adjust the default learning rate for some `tf.keras.*` optimizers.
|
||||
- Use mixed precision training with `tf.keras.mixed_precision.Policy` to reduce memory usage and improve performance on GPUs.
|
||||
|
||||
- **Memory Management:**
|
||||
- Use `tf.data.Dataset` to stream data from disk instead of loading it all into memory.
|
||||
- Release unnecessary tensors using `del` to free up memory.
|
||||
- Use `tf.GradientTape` to compute gradients efficiently, and avoid keeping unnecessary tensors alive within the tape.
|
||||
|
||||
- **GPU Utilization:**
|
||||
- Ensure that TensorFlow is using the GPU by checking `tf.config.list_physical_devices('GPU')`.
|
||||
- Use larger batch sizes to maximize GPU utilization.
|
||||
- Profile your code using TensorFlow Profiler to identify bottlenecks and optimize GPU usage.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **Untrusted Input:** Validate all user-provided input to prevent malicious code injection or data poisoning attacks.
|
||||
- **Model Poisoning:** Protect against adversarial attacks that can manipulate the training data and degrade model performance.
|
||||
- **Model Inversion:** Implement techniques to protect sensitive data from being extracted from the model.
|
||||
|
||||
- **Input Validation:**
|
||||
- Sanitize and validate all input data to prevent SQL injection, cross-site scripting (XSS), and other security vulnerabilities.
|
||||
- Use `tf.io.decode_image` to decode images safely and prevent potential vulnerabilities related to malformed image files.
|
||||
- Input validation for image and text data is critical.
|
||||
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use differential privacy techniques to protect the privacy of training data.
|
||||
- Regularly audit your code and infrastructure for security vulnerabilities.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt communication between the client and the server.
|
||||
- Implement authentication and authorization mechanisms to restrict access to sensitive data and functionality.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests for individual functions and classes using `unittest` or `pytest`.
|
||||
- Use `tf.test.TestCase` for testing TensorFlow-specific code.
|
||||
- Mock external dependencies to isolate the code being tested.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the integration of different modules and components.
|
||||
- Verify that the data pipeline is working correctly.
|
||||
- Ensure that the model is producing accurate predictions on real-world data.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire workflow from data loading to model deployment.
|
||||
- Use tools like Selenium or Cypress to automate end-to-end tests.
|
||||
- Test for performance and scalability.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into logical directories and modules.
|
||||
- Use clear and descriptive test names.
|
||||
- Follow the Arrange-Act-Assert pattern for writing tests.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking frameworks like `unittest.mock` or `pytest-mock` to replace external dependencies with mock objects.
|
||||
- Use stubs to provide controlled responses from external dependencies.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Version Compatibility:**
|
||||
- Be aware of version-specific issues and compatibility concerns when upgrading TensorFlow versions.
|
||||
- Use `tf.compat.v1` or `tf.compat.v2` to maintain compatibility with older versions of TensorFlow.
|
||||
|
||||
- **Eager Execution:**
|
||||
- Understand the differences between eager execution and graph execution.
|
||||
- Use `tf.function` to compile functions into graphs for improved performance in production.
|
||||
|
||||
- **Tensor Shapes and Data Types:**
|
||||
- Pay attention to tensor shapes and data types to avoid errors.
|
||||
- Use `tf.debugging.assert_shapes` and `tf.debugging.assert_type` to check tensor shapes and data types during development.
|
||||
|
||||
- **Variable Scope:**
|
||||
- Be aware of variable scope when using `tf.Variable` objects.
|
||||
- Use `tf.compat.v1.get_variable` to create or reuse variables within a specific scope.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- Jupyter Notebooks or Google Colab for interactive development and experimentation.
|
||||
- TensorBoard for visualizing training progress and model graphs.
|
||||
- TensorFlow Profiler for identifying performance bottlenecks.
|
||||
- Debuggers such as the Python Debugger (pdb) for stepping through code and inspecting variables.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use linters like pylint or flake8 to enforce code style guidelines.
|
||||
- Use formatters like black or autopep8 to automatically format your code.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use TensorFlow Serving to deploy models in production.
|
||||
- Use Docker to containerize your application and ensure consistent deployments.
|
||||
- Use a platform like Vertex AI for scalable model training and deployment.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your code with a continuous integration/continuous delivery (CI/CD) pipeline.
|
||||
- Use tools like Jenkins, Travis CI, or CircleCI to automate testing and deployment.
|
||||
|
||||
- **References:**
|
||||
- [TensorFlow Core](https://www.tensorflow.org/guide/effective_tf2)
|
||||
- [TensorFlow testing best practices](https://www.tensorflow.org/community/contribute/tests)
|
||||
- [Medium - 10 tips to improve your machine learning models with tensorflow](https://medium.com/decathlondigital/10-tips-to-improve-your-machine-learning-models-with-tensorflow-ba7c724761e2)
|
||||
- [Quora - What are the best practices with TensorFlow](https://www.quora.com/What-are-the-best-practices-with-TensorFlow)
|
||||
Reference in New Issue
Block a user