mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+246
-251
@@ -1,323 +1,318 @@
|
||||
---
|
||||
description: This rule enforces Keras library best practices, focusing on code clarity, modularity, performance optimization, and security considerations. It provides actionable guidance for developers to improve the quality and maintainability of Keras-based machine learning projects.
|
||||
globs: *.py
|
||||
description: Definitive guidelines for writing robust, maintainable, and high-performance Keras 3 models, emphasizing the functional API, modern training patterns, and multi-backend compatibility.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Keras Development Best Practices
|
||||
# keras Best Practices
|
||||
|
||||
This document outlines best practices for developing Keras applications. It covers various aspects of software engineering, including code organization, common patterns, performance, security, testing, and tooling.
|
||||
|
||||
Library Information:
|
||||
- Name: keras
|
||||
- Tags: ai, ml, machine-learning, python, deep-learning
|
||||
Keras 3 is engineered for developer experience, emphasizing debugging speed, elegance, and deployability. Adhere to these rules for production-ready, multi-backend Keras projects.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure
|
||||
|
||||
Adopt a well-defined directory structure to enhance maintainability and collaboration.
|
||||
|
||||
|
||||
project_root/
|
||||
├── data/ # Contains datasets (raw, processed)
|
||||
├── models/ # Saved models (weights, architectures)
|
||||
├── src/ # Source code
|
||||
│ ├── layers/ # Custom Keras layers
|
||||
│ ├── models/ # Model definitions
|
||||
│ ├── utils/ # Utility functions
|
||||
│ ├── callbacks/ # Custom Keras Callbacks
|
||||
│ ├── preprocessing/ # Data preprocessing scripts
|
||||
│ └── __init__.py # Makes 'src' a Python package
|
||||
├── notebooks/ # Jupyter notebooks for experimentation
|
||||
├── tests/ # Unit and integration tests
|
||||
├── requirements.txt # Project dependencies
|
||||
├── README.md # Project overview
|
||||
└── .gitignore # Specifies intentionally untracked files that Git should ignore
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
Use descriptive and consistent file names.
|
||||
|
||||
- `model_name.py`: For defining Keras models.
|
||||
- `layer_name.py`: For custom Keras layers.
|
||||
- `utils.py`: For utility functions.
|
||||
- `data_preprocessing.py`: For data preprocessing scripts.
|
||||
- `training_script.py`: Main training script.
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
- **Single Responsibility Principle:** Each module should have a clear and specific purpose.
|
||||
- **Loose Coupling:** Minimize dependencies between modules.
|
||||
- **High Cohesion:** Keep related functions and classes within the same module.
|
||||
|
||||
python
|
||||
# src/models/my_model.py
|
||||
**Always separate concerns:** Model definition, data pipelines, and training logic must be distinct. This improves readability, testability, and reusability.
|
||||
|
||||
❌ BAD: Monolithic script
|
||||
```python
|
||||
# model, data, and training all in one file
|
||||
import keras
|
||||
from keras import layers
|
||||
import numpy as np
|
||||
|
||||
def create_model(input_shape, num_classes):
|
||||
inputs = keras.Input(shape=input_shape)
|
||||
x = layers.Conv2D(32, (3, 3), activation='relu')(inputs)
|
||||
x = layers.MaxPooling2D((2, 2))(x)
|
||||
x = layers.Flatten()(x)
|
||||
outputs = layers.Dense(num_classes, activation='softmax')(x)
|
||||
model = keras.Model(inputs, outputs)
|
||||
# Data generation
|
||||
x_train = np.random.rand(100, 10)
|
||||
y_train = np.random.randint(0, 2, (100, 1))
|
||||
|
||||
# Model definition
|
||||
inputs = keras.Input(shape=(10,))
|
||||
x = keras.layers.Dense(32, activation="relu")(inputs)
|
||||
outputs = keras.layers.Dense(1, activation="sigmoid")(x)
|
||||
model = keras.Model(inputs, outputs)
|
||||
|
||||
# Training
|
||||
model.compile(optimizer="adam", loss="binary_crossentropy")
|
||||
model.fit(x_train, y_train, epochs=10)
|
||||
```
|
||||
|
||||
✅ GOOD: Modular components
|
||||
```python
|
||||
# my_model.py
|
||||
import keras
|
||||
|
||||
def build_simple_model(input_shape=(10,)):
|
||||
inputs = keras.Input(shape=input_shape, name="input_layer")
|
||||
x = keras.layers.Dense(32, activation="relu", name="hidden_dense")(inputs)
|
||||
outputs = keras.layers.Dense(1, activation="sigmoid", name="output_dense")(x)
|
||||
model = keras.Model(inputs, outputs, name="simple_classifier")
|
||||
return model
|
||||
|
||||
# train_script.py
|
||||
import keras
|
||||
import numpy as np
|
||||
from my_model import build_simple_model
|
||||
|
||||
### 1.4. Component Architecture
|
||||
# 1. Data Loading (e.g., using tf.data or torch.utils.data for real projects)
|
||||
x_train = np.random.rand(100, 10)
|
||||
y_train = np.random.randint(0, 2, (100, 1))
|
||||
|
||||
- **Layers:** Encapsulate reusable blocks of computation (e.g., custom convolutional layers, attention mechanisms).
|
||||
- **Models:** Define the overall architecture by combining layers.
|
||||
- **Callbacks:** Implement custom training behaviors (e.g., early stopping, learning rate scheduling).
|
||||
- **Preprocessing:** Separate data loading, cleaning, and transformation logic.
|
||||
# 2. Model Instantiation
|
||||
model = build_simple_model()
|
||||
|
||||
### 1.5. Code Splitting
|
||||
# 3. Training Configuration
|
||||
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
|
||||
callbacks = [
|
||||
keras.callbacks.EarlyStopping(patience=3, monitor="val_loss"),
|
||||
keras.callbacks.ModelCheckpoint("best_model.keras", save_best_only=True)
|
||||
]
|
||||
|
||||
- **Functions:** Break down complex logic into smaller, well-named functions.
|
||||
- **Classes:** Use classes to represent stateful components (e.g., custom layers with trainable parameters).
|
||||
- **Packages:** Organize modules into packages for larger projects.
|
||||
# 4. Training Execution
|
||||
model.fit(x_train, y_train, epochs=50, validation_split=0.2, callbacks=callbacks)
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns
|
||||
### 2.1 Model Building: Functional API is King
|
||||
|
||||
- **Functional API:** Use the Keras Functional API for building complex, multi-input/output models.
|
||||
**Always use the Functional API** for most models. It's explicit, easy to inspect, and handles complex topologies (multi-input/output, shared layers) gracefully. Subclassing is reserved for highly custom, non-standard layers or models with dynamic graph execution.
|
||||
|
||||
python
|
||||
input_tensor = keras.Input(shape=(784,))
|
||||
hidden_layer = layers.Dense(units=64, activation='relu')(input_tensor)
|
||||
output_tensor = layers.Dense(units=10, activation='softmax')(hidden_layer)
|
||||
model = keras.Model(inputs=input_tensor, outputs=output_tensor)
|
||||
|
||||
❌ BAD: Subclassing for simple sequential models
|
||||
```python
|
||||
class MySequentialModel(keras.Model):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.dense1 = keras.layers.Dense(32, activation="relu")
|
||||
self.dense2 = keras.layers.Dense(1, activation="sigmoid")
|
||||
|
||||
- **Subclassing:** Subclass `keras.Model` or `keras.layers.Layer` for maximum customization.
|
||||
def call(self, inputs):
|
||||
x = self.dense1(inputs)
|
||||
return self.dense2(x)
|
||||
```
|
||||
|
||||
python
|
||||
class MyLayer(layers.Layer):
|
||||
def __init__(self, units=32, **kwargs):
|
||||
super(MyLayer, self).__init__(**kwargs)
|
||||
self.units = units
|
||||
✅ GOOD: Functional API for clarity and debuggability
|
||||
```python
|
||||
inputs = keras.Input(shape=(10,), name="input_features")
|
||||
x = keras.layers.Dense(32, activation="relu", name="hidden_layer")(inputs)
|
||||
outputs = keras.layers.Dense(1, activation="sigmoid", name="output_prediction")(x)
|
||||
model = keras.Model(inputs=inputs, outputs=outputs, name="simple_functional_model")
|
||||
|
||||
def build(self, input_shape):
|
||||
self.w = self.add_weight(shape=(input_shape[-1], self.units),
|
||||
initializer='random_normal',
|
||||
trainable=True)
|
||||
self.b = self.add_weight(shape=(self.units,),
|
||||
initializer='zeros',
|
||||
trainable=True)
|
||||
# Visualize the model for debugging
|
||||
keras.utils.plot_model(model, "simple_functional_model.png", show_shapes=True)
|
||||
```
|
||||
|
||||
def call(self, inputs):
|
||||
return keras.activations.relu(tf.matmul(inputs, self.w) + self.b)
|
||||
|
||||
### 2.2 Training Loops: Leverage `model.fit` and Callbacks
|
||||
|
||||
- **Callbacks:** Implement custom training behaviors (e.g., custom logging, model checkpointing).
|
||||
**Always use `model.fit()`** with Keras's powerful built-in `Callbacks`. This simplifies training, provides standard logging, and ensures best practices like early stopping and model saving are applied consistently. Only implement a custom training loop (via the "Trainer pattern") when `model.fit()` is insufficient for complex research or custom gradient logic.
|
||||
|
||||
python
|
||||
class CustomCallback(keras.callbacks.Callback):
|
||||
def on_epoch_end(self, epoch, logs=None):
|
||||
print(f'Epoch {epoch}: Loss = {logs['loss']}')
|
||||
|
||||
❌ BAD: Manual training loop without callbacks
|
||||
```python
|
||||
optimizer = keras.optimizers.Adam()
|
||||
loss_fn = keras.losses.BinaryCrossentropy()
|
||||
|
||||
### 2.2. Recommended Approaches
|
||||
for epoch in range(10):
|
||||
for step, (x_batch, y_batch) in enumerate(dataset):
|
||||
with tf.GradientTape() as tape: # Assuming TF backend
|
||||
logits = model(x_batch)
|
||||
loss_value = loss_fn(y_batch, logits)
|
||||
grads = tape.gradient(loss_value, model.trainable_weights)
|
||||
optimizer.apply_gradients(zip(grads, model.trainable_weights))
|
||||
print(f"Epoch {epoch}, Loss: {loss_value.numpy()}")
|
||||
```
|
||||
|
||||
- **Data Input Pipelines:** Use `tf.data.Dataset` for efficient data loading and preprocessing.
|
||||
- **Model Checkpointing:** Save model weights during training to prevent data loss and allow for resuming training.
|
||||
- **Early Stopping:** Monitor validation loss and stop training when it plateaus to prevent overfitting.
|
||||
- **Learning Rate Scheduling:** Adjust the learning rate during training to improve convergence.
|
||||
✅ GOOD: `model.fit()` with essential callbacks
|
||||
```python
|
||||
model.compile(
|
||||
optimizer=keras.optimizers.Adam(learning_rate=1e-3),
|
||||
loss=keras.losses.BinaryCrossentropy(),
|
||||
metrics=["accuracy"]
|
||||
)
|
||||
|
||||
### 2.3. Anti-Patterns
|
||||
|
||||
- **Hardcoding:** Avoid hardcoding values directly into your code. Use variables and configuration files instead.
|
||||
- **Global Variables:** Minimize the use of global variables to prevent namespace pollution and unexpected side effects.
|
||||
- **Over-Engineering:** Don't overcomplicate your code with unnecessary abstractions or complex patterns.
|
||||
- **Ignoring Warnings:** Pay attention to warnings and deprecation messages, as they often indicate potential problems.
|
||||
- **Training on the entire dataset without validation:** Always split your data into training, validation and testing sets to avoid overfitting.
|
||||
|
||||
### 2.4. State Management
|
||||
|
||||
- **Stateless Operations:** Prefer stateless operations whenever possible to simplify testing and debugging.
|
||||
- **Model Weights:** Store model weights separately from the model architecture.
|
||||
- **Configuration Files:** Use configuration files (e.g., JSON, YAML) to manage hyperparameters and other settings.
|
||||
|
||||
### 2.5. Error Handling
|
||||
|
||||
- **Exception Handling:** Use `try...except` blocks to handle potential exceptions gracefully.
|
||||
- **Logging:** Log errors and warnings to help diagnose problems.
|
||||
- **Validation:** Validate input data to prevent unexpected errors.
|
||||
- **Assertions:** Use `assert` statements to check for conditions that should always be true.
|
||||
|
||||
python
|
||||
try:
|
||||
model = keras.models.load_model('my_model.h5')
|
||||
except FileNotFoundError:
|
||||
logging.error('Model file not found.')
|
||||
raise
|
||||
callbacks = [
|
||||
keras.callbacks.EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True),
|
||||
keras.callbacks.ModelCheckpoint("best_model_epoch_{epoch:02d}.keras", save_best_only=True, monitor="val_loss"),
|
||||
keras.callbacks.TensorBoard(log_dir="./logs")
|
||||
]
|
||||
|
||||
# Use a proper Keras dataset or NumPy arrays
|
||||
model.fit(
|
||||
x_train, y_train,
|
||||
epochs=50,
|
||||
batch_size=32,
|
||||
validation_split=0.2,
|
||||
callbacks=callbacks,
|
||||
verbose=1
|
||||
)
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
### 3.1 Mixed Precision Training
|
||||
|
||||
- **GPU Acceleration:** Utilize GPUs for faster training and inference.
|
||||
- **Data Preprocessing:** Optimize data preprocessing pipelines to reduce overhead.
|
||||
- **Batch Size:** Adjust the batch size to maximize GPU utilization.
|
||||
- **Model Pruning:** Remove unnecessary weights from the model to reduce its size and improve its speed.
|
||||
- **Quantization:** Reduce the precision of model weights to reduce memory consumption and improve inference speed.
|
||||
- **Mixed Precision Training:** Use `tf.keras.mixed_precision.Policy` to enable mixed precision training for faster training on modern GPUs.
|
||||
**Always enable mixed precision** for modern GPUs/TPUs. It significantly speeds up training and reduces memory usage with minimal impact on accuracy.
|
||||
|
||||
### 3.2. Memory Management
|
||||
```python
|
||||
# At the very beginning of your script, before any model definition
|
||||
keras.mixed_precision.set_global_policy("mixed_float16")
|
||||
|
||||
- **Garbage Collection:** Be mindful of memory leaks and use garbage collection to reclaim unused memory.
|
||||
- **Data Types:** Use appropriate data types to minimize memory consumption (e.g., `tf.float16` instead of `tf.float32`).
|
||||
- **Generators:** Use generators to load data in batches, reducing memory usage.
|
||||
# Your model layers will automatically use float16 where appropriate
|
||||
inputs = keras.Input(shape=(224, 224, 3))
|
||||
x = keras.layers.Conv2D(32, 3, activation="relu")(inputs)
|
||||
outputs = keras.layers.Dense(10, activation="softmax", dtype="float32")(x) # Output layer should be float32 for stability
|
||||
model = keras.Model(inputs, outputs)
|
||||
```
|
||||
|
||||
### 3.3. Rendering Optimization (If applicable)
|
||||
### 3.2 Multi-Backend Execution
|
||||
|
||||
Not directly applicable to Keras itself, but relevant when visualizing model outputs or training progress. Use libraries like `matplotlib` or `seaborn` efficiently and consider downsampling large datasets before plotting.
|
||||
**Always configure your backend explicitly** using the `KERAS_BACKEND` environment variable. This ensures consistency and allows easy switching between TensorFlow, JAX, or PyTorch.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
❌ BAD: Relying on default or implicit backend
|
||||
```python
|
||||
import keras # Backend might be TF by default, but not guaranteed or explicit
|
||||
```
|
||||
|
||||
- **Model Pruning and Quantization:** as above.
|
||||
- **Selectively Import Keras Modules**: Only import the specific Keras modules needed to reduce the overall bundle size, e.g., `from keras.layers import Dense, Conv2D` instead of `import keras.layers`.
|
||||
✅ GOOD: Explicit backend configuration (before `import keras`)
|
||||
```python
|
||||
import os
|
||||
os.environ["KERAS_BACKEND"] = "jax" # Or "tensorflow", "torch"
|
||||
import keras
|
||||
# Now Keras will use JAX as its backend
|
||||
```
|
||||
|
||||
### 3.5. Lazy Loading
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
- **Lazy Initialization:** Defer the initialization of resources until they are actually needed.
|
||||
- **Data Loading:** Load data on demand rather than loading the entire dataset into memory.
|
||||
### 4.1 Reproducibility
|
||||
|
||||
## 4. Security Best Practices
|
||||
**Always set seeds** for NumPy, Python's random module, and the Keras backend for reproducible results, especially during development and experimentation.
|
||||
|
||||
### 4.1. Common Vulnerabilities
|
||||
```python
|
||||
import os
|
||||
import random
|
||||
import numpy as np
|
||||
import tensorflow as tf # Or jax, torch
|
||||
|
||||
- **Adversarial Attacks:** Protect against adversarial attacks that can fool models into making incorrect predictions.
|
||||
- **Data Poisoning:** Ensure the integrity of training data to prevent data poisoning attacks.
|
||||
- **Model Extraction:** Protect against model extraction attacks that can steal intellectual property.
|
||||
# 1. Python's random module
|
||||
random.seed(42)
|
||||
# 2. NumPy
|
||||
np.random.seed(42)
|
||||
# 3. Keras backend (TensorFlow example)
|
||||
tf.random.set_seed(42)
|
||||
# For JAX: jax.random.PRNGKey(42) and pass to ops
|
||||
# For PyTorch: torch.manual_seed(42)
|
||||
|
||||
### 4.2. Input Validation
|
||||
# Ensure deterministic operations if using TensorFlow
|
||||
os.environ['TF_DETERMINISTIC_OPS'] = '1'
|
||||
os.environ['TF_CUDNN_DETERMINISTIC'] = '1'
|
||||
|
||||
- **Sanitize Input:** Sanitize input data to prevent injection attacks.
|
||||
- **Validate Input:** Validate input data to ensure that it conforms to the expected format and range.
|
||||
import keras # Import Keras AFTER setting seeds
|
||||
```
|
||||
|
||||
python
|
||||
def predict(model, input_data):
|
||||
if not isinstance(input_data, np.ndarray):
|
||||
raise TypeError('Input data must be a NumPy array.')
|
||||
if input_data.shape != (1, 784):
|
||||
raise ValueError('Input data must have shape (1, 784).')
|
||||
return model.predict(input_data)
|
||||
### 4.2 Keras 2 vs. Keras 3
|
||||
|
||||
**Always use `import keras`** for Keras 3. Avoid `from tensorflow import keras` if you need to guarantee Keras 3 behavior, especially with older TensorFlow versions. Ensure `pip install --upgrade keras` is run.
|
||||
|
||||
### 4.3. Authentication and Authorization
|
||||
❌ BAD: Potential Keras 2 import
|
||||
```python
|
||||
# If TF < 2.16, this might give you Keras 2
|
||||
from tensorflow import keras
|
||||
```
|
||||
|
||||
- **Secure API:** Implement secure API communication using HTTPS.
|
||||
- **Authentication:** Require authentication for access to sensitive data and functionality.
|
||||
- **Authorization:** Enforce authorization policies to control access to resources.
|
||||
✅ GOOD: Explicit Keras 3 import
|
||||
```python
|
||||
import keras # This will always be Keras 3 if installed correctly
|
||||
```
|
||||
|
||||
### 4.4. Data Protection
|
||||
## 5. Type Hints
|
||||
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Anonymization:** Anonymize data to protect privacy.
|
||||
- **Data Governance:** Implement data governance policies to ensure data quality and security.
|
||||
**Always use type hints** for function signatures and class attributes. This improves code clarity, enables static analysis, and reduces bugs.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
❌ BAD: Untyped function
|
||||
```python
|
||||
def build_model(input_shape):
|
||||
inputs = keras.Input(shape=input_shape)
|
||||
x = keras.layers.Dense(10)(inputs)
|
||||
return keras.Model(inputs, x)
|
||||
```
|
||||
|
||||
- **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
|
||||
- **API Keys:** Use API keys to authenticate requests.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
|
||||
✅ GOOD: Type-hinted function
|
||||
```python
|
||||
import keras
|
||||
from typing import Tuple
|
||||
|
||||
## 5. Testing Approaches
|
||||
def build_model(input_shape: Tuple[int, ...]) -> keras.Model:
|
||||
inputs = keras.Input(shape=input_shape)
|
||||
x = keras.layers.Dense(10, activation="relu")(inputs)
|
||||
outputs = keras.layers.Dense(1, activation="sigmoid")(x)
|
||||
return keras.Model(inputs, outputs, name="typed_model")
|
||||
```
|
||||
|
||||
### 5.1. Unit Testing
|
||||
## 6. Virtual Environments
|
||||
|
||||
- **Test-Driven Development:** Write unit tests before writing code to ensure that the code meets the requirements.
|
||||
- **Test Cases:** Create test cases for different scenarios, including edge cases and error conditions.
|
||||
- **Assertions:** Use assertions to verify that the code behaves as expected.
|
||||
**Always use a virtual environment** (e.g., `venv`, `conda`) for every project. This isolates dependencies and prevents conflicts.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
```bash
|
||||
# Create and activate a virtual environment
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
||||
|
||||
- **Component Interaction:** Test the interaction between different components of the application.
|
||||
- **Data Flow:** Test the flow of data through the application.
|
||||
- **System Integration:** Test the integration of the application with other systems.
|
||||
# Install Keras and backend
|
||||
pip install --upgrade keras tensorflow # Or jax, torch
|
||||
```
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
## 7. Packaging
|
||||
|
||||
- **User Interface:** Test the user interface to ensure that it is functional and user-friendly.
|
||||
- **Workflow:** Test the entire workflow from start to finish.
|
||||
- **Real-World Scenarios:** Test the application in real-world scenarios to ensure that it meets the needs of the users.
|
||||
**Package reusable components** (custom layers, models, data utilities) into a local package. This promotes modularity and easy sharing across projects.
|
||||
|
||||
### 5.4. Test Organization
|
||||
```
|
||||
my_project/
|
||||
├── src/
|
||||
│ ├── __init__.py
|
||||
│ ├── models/
|
||||
│ │ ├── __init__.py
|
||||
│ │ └── custom_layers.py # Contains custom Keras layers
|
||||
│ └── data/
|
||||
│ ├── __init__.py
|
||||
│ └── data_loader.py # Contains data loading functions
|
||||
├── tests/
|
||||
│ └── test_models.py
|
||||
└── train.py
|
||||
```
|
||||
|
||||
- **Test Directory:** Create a dedicated `tests` directory to store test files.
|
||||
- **Test Modules:** Organize tests into modules based on the components they test.
|
||||
- **Test Naming Conventions:** Use clear and consistent naming conventions for test files and functions.
|
||||
## 8. Testing Approaches
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
**Always write unit tests** for custom layers, preprocessing functions, and other standalone components. **Implement integration tests** for full model training and inference pipelines.
|
||||
|
||||
- **Mock Objects:** Use mock objects to simulate the behavior of external dependencies.
|
||||
- **Stub Functions:** Use stub functions to replace complex or time-consuming operations with simple, predictable results.
|
||||
```python
|
||||
# tests/test_models.py
|
||||
import unittest
|
||||
import keras
|
||||
from src.models.custom_layers import MyCustomLayer # Example
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
class TestCustomLayer(unittest.TestCase):
|
||||
def test_output_shape(self):
|
||||
layer = MyCustomLayer(units=10)
|
||||
inputs = keras.ops.zeros((1, 5)) # Use keras.ops for backend-agnostic ops
|
||||
outputs = layer(inputs)
|
||||
self.assertEqual(outputs.shape, (1, 10))
|
||||
|
||||
### 6.1. Frequent Mistakes
|
||||
def test_trainable_weights(self):
|
||||
layer = MyCustomLayer(units=10)
|
||||
_ = layer(keras.ops.zeros((1, 5)))
|
||||
self.assertGreater(len(layer.trainable_weights), 0)
|
||||
|
||||
- **Incorrect Input Shapes:** Ensure that the input shapes match the expected dimensions.
|
||||
- **Data Type Mismatches:** Use consistent data types throughout the application.
|
||||
- **Gradient Vanishing/Exploding:** Use appropriate activation functions and weight initialization techniques to prevent gradient problems.
|
||||
- **Overfitting:** Use regularization techniques (e.g., dropout, L1/L2 regularization) to prevent overfitting.
|
||||
# src/models/custom_layers.py
|
||||
import keras
|
||||
|
||||
### 6.2. Edge Cases
|
||||
class MyCustomLayer(keras.layers.Layer):
|
||||
def __init__(self, units, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.units = units
|
||||
|
||||
- **Empty Datasets:** Handle empty datasets gracefully.
|
||||
- **Missing Values:** Handle missing values appropriately (e.g., imputation, deletion).
|
||||
- **Outliers:** Identify and handle outliers in the data.
|
||||
def build(self, input_shape):
|
||||
self.w = self.add_weight(
|
||||
shape=(input_shape[-1], self.units),
|
||||
initializer="random_normal",
|
||||
trainable=True,
|
||||
)
|
||||
self.b = self.add_weight(
|
||||
shape=(self.units,), initializer="zeros", trainable=True
|
||||
)
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
- **API Changes:** Be aware of API changes between different versions of Keras and TensorFlow.
|
||||
- **Compatibility:** Ensure that your code is compatible with the versions of Keras and TensorFlow that you are using.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
- **TensorFlow Compatibility:** Verify the compatibility between Keras and TensorFlow versions. Keras 3 can run on TensorFlow 2.16 onwards but there can be backwards compatibility issues.
|
||||
- **Hardware Compatibility:** Ensure compatibility with different hardware platforms (e.g., CPU, GPU, TPU).
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
- **Logging:** Use logging to track the execution of the code and identify potential problems.
|
||||
- **Debugging Tools:** Use debugging tools (e.g., `pdb`, `TensorBoard`) to inspect the state of the application.
|
||||
- **Print Statements:** Use print statements to display intermediate values and debug the code.
|
||||
- **TensorBoard:** Use TensorBoard to visualize the model architecture, training progress, and performance metrics.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
- **IDE:** Use an IDE (e.g., VS Code, PyCharm) with Keras and TensorFlow support.
|
||||
- **Virtual Environment:** Use a virtual environment (e.g., `venv`, `conda`) to isolate project dependencies.
|
||||
- **Jupyter Notebook:** Use Jupyter notebooks for experimentation and prototyping.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
- **Requirements File:** Use a `requirements.txt` file to specify project dependencies.
|
||||
- **Setup Script:** Use a `setup.py` script to define the project metadata and installation instructions.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
- **PEP 8:** Adhere to PEP 8 style guidelines for Python code.
|
||||
- **Linters:** Use linters (e.g., `flake8`, `pylint`) to enforce code style and identify potential problems.
|
||||
- **Formatters:** Use formatters (e.g., `black`, `autopep8`) to automatically format code.
|
||||
|
||||
### 7.4. Deployment
|
||||
|
||||
- **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies.
|
||||
- **Cloud Platforms:** Deploy the application to a cloud platform (e.g., AWS, Google Cloud, Azure).
|
||||
- **Serving Frameworks:** Use serving frameworks (e.g., TensorFlow Serving, KServe) to deploy models for inference.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
- **Continuous Integration:** Automate the build, test, and integration process using CI tools (e.g., Jenkins, Travis CI, GitHub Actions).
|
||||
- **Continuous Deployment:** Automate the deployment process using CD tools (e.g., AWS CodePipeline, Google Cloud Build, Azure DevOps).
|
||||
|
||||
This comprehensive guide provides a strong foundation for developing high-quality, maintainable, and secure Keras applications. By following these best practices, developers can improve their productivity, reduce the risk of errors, and build robust machine learning systems.
|
||||
def call(self, inputs):
|
||||
return keras.ops.matmul(inputs, self.w) + self.b
|
||||
```
|
||||
Reference in New Issue
Block a user