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:
+334
-233
@@ -1,285 +1,386 @@
|
||||
---
|
||||
description: This rule provides coding standards and best practices for using the gensim library, focusing on NLP, topic modeling, performance, and code organization. It offers actionable guidelines for developers to create effective and maintainable gensim-based applications.
|
||||
globs: *.py
|
||||
description: This guide outlines definitive best practices for using the gensim library, focusing on reproducibility, efficient corpus construction, robust model training, and maintainable code for NLP topic modeling tasks.
|
||||
globs: **/*.py
|
||||
---
|
||||
# gensim Library Best Practices and Coding Standards
|
||||
# gensim Best Practices
|
||||
|
||||
This document outlines the best practices for coding standards when working with the gensim library for Natural Language Processing (NLP) and topic modeling in Python. Following these guidelines will lead to more maintainable, efficient, and robust code.
|
||||
This document is your definitive guide for using `gensim` effectively and correctly within our team. We prioritize reproducibility, performance, and maintainability. Follow these rules to ensure consistent, high-quality NLP pipelines.
|
||||
|
||||
## Library Information:
|
||||
- Name: gensim
|
||||
- Tags: python, nlp, topic-modeling
|
||||
## 1. Ensure Reproducibility
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
Always configure logging and set a random seed at the entry point of any script using `gensim` models. This is non-negotiable for debugging and consistent results.
|
||||
|
||||
### 1.1 Directory Structure Best Practices:
|
||||
### ❌ BAD: Unpredictable Runs
|
||||
|
||||
Adopt a clear and structured directory organization for your gensim projects. A well-defined structure enhances code readability and maintainability.
|
||||
```python
|
||||
import gensim
|
||||
from gensim import models, corpora
|
||||
|
||||
# No logging, no seed
|
||||
# ... model training ...
|
||||
lda_model = models.LdaModel(corpus, num_topics=10)
|
||||
```
|
||||
|
||||
my_gensim_project/
|
||||
├── data/ # Raw and processed datasets
|
||||
│ ├── raw/ # Original datasets (read-only)
|
||||
│ └── processed/ # Processed data (e.g., corpus, dictionary)
|
||||
├── models/ # Trained gensim models
|
||||
│ ├── lda/ # LDA models
|
||||
│ └── lsi/ # LSI models
|
||||
├── scripts/ # Scripts for data processing, model training, etc.
|
||||
│ ├── preprocess.py # Data preprocessing script
|
||||
│ ├── train_model.py # Model training script
|
||||
│ └── evaluate.py # Model evaluation script
|
||||
├── utils/ # Utility functions and modules
|
||||
│ ├── helpers.py # Helper functions for common tasks
|
||||
│ └── visualization.py # Visualization functions
|
||||
├── notebooks/ # Jupyter notebooks for exploration and experimentation
|
||||
│ ├── exploration.ipynb
|
||||
│ └── analysis.ipynb
|
||||
├── tests/ # Unit and integration tests
|
||||
│ ├── test_preprocess.py
|
||||
│ ├── test_train_model.py
|
||||
│ └── conftest.py # pytest configuration file (optional)
|
||||
├── README.md # Project documentation
|
||||
├── requirements.txt # Project dependencies
|
||||
└── .gitignore # Git ignore file
|
||||
### ✅ GOOD: Reproducible and Observable Runs
|
||||
|
||||
```python
|
||||
import logging
|
||||
import numpy as np
|
||||
import gensim
|
||||
from gensim import models, corpora
|
||||
from gensim.utils import randseed
|
||||
|
||||
### 1.2 File Naming Conventions:
|
||||
# 1. Configure logging first
|
||||
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
|
||||
|
||||
Use descriptive and consistent file names. This makes it easier to understand the purpose of each file.
|
||||
# 2. Set a global random seed for gensim and numpy
|
||||
# Gensim's randseed sets numpy's seed internally.
|
||||
randseed = 42
|
||||
np.random.seed(randseed)
|
||||
|
||||
- Use lowercase letters and underscores for Python files (e.g., `preprocess.py`, `train_model.py`).
|
||||
- Use descriptive names that clearly indicate the file's purpose (e.g., `lda_model.pkl`, `corpus.mm`).
|
||||
- For data files, include the data source or processing stage in the name (e.g., `raw_data.txt`, `processed_corpus.txt`).
|
||||
- Use a consistent naming scheme for test files (e.g., `test_module.py` for testing `module.py`).
|
||||
# ... rest of your script ...
|
||||
# Ensure any model that takes a random_state or seed parameter uses it
|
||||
lda_model = models.LdaModel(corpus, num_topics=10, random_state=randseed)
|
||||
```
|
||||
|
||||
### 1.3 Module Organization:
|
||||
## 2. Construct Clean and Efficient Corpora
|
||||
|
||||
Organize your code into logical modules. Each module should handle a specific aspect of your NLP pipeline (e.g., data loading, preprocessing, model training).
|
||||
A well-prepared corpus is fundamental to effective topic modeling. Prioritize memory efficiency and intelligent vocabulary pruning.
|
||||
|
||||
- Create separate modules for data loading, preprocessing, model training, evaluation, and visualization.
|
||||
- Keep modules focused and avoid large, monolithic files.
|
||||
- Use clear and descriptive names for modules and functions.
|
||||
- Consider using packages to group related modules.
|
||||
### 2.1. Preprocessing with `gensim.utils.simple_preprocess` and `spaCy`
|
||||
|
||||
### 1.4 Component Architecture Recommendations:
|
||||
Combine `gensim`'s simple preprocessing with `spaCy` for robust tokenization and lemmatization. `simple_preprocess` handles basic tokenization and lowercasing efficiently.
|
||||
|
||||
Design your gensim applications with a component-based architecture. This promotes code reusability and maintainability.
|
||||
### ❌ BAD: Manual, Inconsistent Preprocessing
|
||||
|
||||
- Break down your application into smaller, independent components, such as:
|
||||
- `DataLoader`: Loads and preprocesses data.
|
||||
- `CorpusBuilder`: Creates a corpus from the preprocessed data.
|
||||
- `ModelTrainer`: Trains a gensim model on the corpus.
|
||||
- `ModelEvaluator`: Evaluates the trained model.
|
||||
- `Visualizer`: Visualizes the model results.
|
||||
- Each component should have a clear interface and well-defined responsibilities.
|
||||
- Use dependency injection to manage dependencies between components.
|
||||
```python
|
||||
import re
|
||||
|
||||
### 1.5 Code Splitting Strategies:
|
||||
documents = ["This is a document.", "Another document here."]
|
||||
stoplist = set('is a here'.split())
|
||||
|
||||
Split large files into smaller, manageable chunks. This improves code readability and reduces the likelihood of merge conflicts.
|
||||
texts = []
|
||||
for doc in documents:
|
||||
# Manual lowercasing, splitting, and stopword removal
|
||||
tokens = [word for word in re.findall(r'\b\w+\b', doc.lower()) if word not in stoplist]
|
||||
texts.append(tokens)
|
||||
```
|
||||
|
||||
- Break down large functions into smaller, more focused helper functions.
|
||||
- Split large modules into smaller, more focused submodules.
|
||||
- Use appropriate abstraction techniques (e.g., classes, interfaces) to encapsulate related functionality.
|
||||
- Consider using decorators or context managers to handle common tasks, such as logging or error handling.
|
||||
### ✅ GOOD: `gensim.utils.simple_preprocess` + `spaCy` for Production
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
```python
|
||||
import spacy
|
||||
from gensim.utils import simple_preprocess
|
||||
|
||||
### 2.1 Design Patterns:
|
||||
# Load spaCy model once
|
||||
nlp = spacy.load("en_core_web_sm", disable=['parser', 'ner'])
|
||||
|
||||
- **Factory Pattern:** Use factory patterns to create different types of gensim models or data transformations based on configuration.
|
||||
- **Strategy Pattern:** Employ strategy patterns to switch between different preprocessing techniques or similarity measures at runtime.
|
||||
- **Observer Pattern:** Implement observer patterns to react to model training events, such as logging progress or saving intermediate results.
|
||||
- **Pipeline Pattern:** Structure your NLP workflow as a pipeline, applying a sequence of transformations to your data.
|
||||
def preprocess_document(text: str) -> list[str]:
|
||||
"""
|
||||
Tokenizes, lowercases, removes stopwords, and lemmatizes text using spaCy.
|
||||
"""
|
||||
# Use gensim's simple_preprocess for initial tokenization and lowercasing
|
||||
tokens = simple_preprocess(text, deacc=True) # deacc=True removes accents
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks:
|
||||
# Process with spaCy for lemmatization and advanced stopword removal
|
||||
doc = nlp(" ".join(tokens))
|
||||
lemmas = [
|
||||
token.lemma_ for token in doc
|
||||
if not token.is_stop and not token.is_punct and not token.is_space
|
||||
]
|
||||
return lemmas
|
||||
|
||||
- **Text Preprocessing:** Use `gensim.utils.simple_preprocess` for basic text preprocessing, including tokenization and lowercasing. For more advanced preprocessing, integrate with NLTK or spaCy.
|
||||
- **Creating a Dictionary:** Use `gensim.corpora.Dictionary` to create a dictionary from your tokenized documents. Filter out infrequent and extremely frequent words using `filter_extremes()` to improve model quality and performance.
|
||||
- **Creating a Corpus:** Use `dictionary.doc2bow` to convert your documents into a bag-of-words corpus. For large corpora, use `gensim.corpora.MmCorpus` to store the corpus on disk.
|
||||
- **Training a Topic Model:** Use `gensim.models.LdaModel` or `gensim.models.LsiModel` to train a topic model on your corpus. Tune the model parameters (e.g., number of topics, alpha, beta) to optimize topic coherence.
|
||||
- **Evaluating a Topic Model:** Use `gensim.models.CoherenceModel` to evaluate the coherence of your topic model. Visualize the model topics using `pyLDAvis` or other visualization tools.
|
||||
documents = ["Human machine interface for lab abc computer applications",
|
||||
"A survey of user opinion of computer system response time"]
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells:
|
||||
processed_texts = [preprocess_document(doc) for doc in documents]
|
||||
```
|
||||
|
||||
- **Global Variables:** Avoid using global variables for gensim models, corpora, or dictionaries. Pass these objects as arguments to functions or classes.
|
||||
- **Hardcoded Paths:** Avoid hardcoding file paths in your code. Use configuration files or environment variables to manage file paths.
|
||||
- **Lack of Error Handling:** Implement proper error handling to gracefully handle unexpected exceptions. Log errors and provide informative error messages to the user.
|
||||
- **Ignoring Warnings:** Pay attention to warnings generated by gensim. These warnings often indicate potential problems with your code or data.
|
||||
- **Overly Complex Functions:** Avoid writing overly complex functions that perform too many tasks. Break down large functions into smaller, more focused helper functions.
|
||||
### 2.2. Vocabulary Pruning with `filter_extremes`
|
||||
|
||||
### 2.4 State Management:
|
||||
Always prune your dictionary using `filter_extremes` to remove very rare and very common tokens. This significantly improves model quality and reduces noise.
|
||||
|
||||
- Encapsulate state within classes.
|
||||
- Use immutable data structures where possible.
|
||||
- Avoid modifying shared state directly.
|
||||
- Consider using a state management library for complex applications.
|
||||
**Crucial**: `no_below` is an absolute count (int), `no_above` is a fraction (float).
|
||||
|
||||
### 2.5 Error Handling:
|
||||
### ❌ BAD: Unfiltered Dictionary or Misunderstood Parameters
|
||||
|
||||
- Use try-except blocks to catch exceptions.
|
||||
- Log exceptions with traceback information.
|
||||
- Provide informative error messages to the user.
|
||||
- Consider using custom exception classes for gensim-specific errors.
|
||||
```python
|
||||
from gensim import corpora
|
||||
|
||||
## 3. Performance Considerations:
|
||||
# Dictionary with all tokens, including noise
|
||||
dictionary = corpora.Dictionary(processed_texts)
|
||||
|
||||
### 3.1 Optimization Techniques:
|
||||
# Incorrectly using no_below as a fraction or no_above as an absolute count
|
||||
# This will lead to unexpected vocabulary sizes.
|
||||
dictionary.filter_extremes(no_below=0.05, no_above=100) # Incorrect units
|
||||
```
|
||||
|
||||
- **Use `MmCorpus` for large corpora:** Store your corpus on disk using `gensim.corpora.MmCorpus` to reduce memory consumption.
|
||||
- **Use `LdaMulticore` for parallel training:** Train LDA models in parallel using `gensim.models.LdaMulticore` to speed up training time.
|
||||
- **Optimize preprocessing:** Use efficient string processing techniques and avoid unnecessary computations during preprocessing.
|
||||
- **Filter extreme values:** Use the `filter_extremes()` function to remove words that are too frequent or infrequent, which can improve the performance of the model
|
||||
- **Batch Processing:** Process large datasets in batches to reduce memory consumption.
|
||||
- **Vectorization:** Use NumPy's vectorized operations to speed up numerical computations.
|
||||
- **Caching:** Cache intermediate results to avoid redundant computations.
|
||||
### ✅ GOOD: Intelligent Vocabulary Pruning
|
||||
|
||||
### 3.2 Memory Management:
|
||||
```python
|
||||
from gensim import corpora
|
||||
|
||||
- **Use generators for large datasets:** Load and process data using generators to avoid loading the entire dataset into memory at once.
|
||||
- **Delete unused objects:** Explicitly delete unused objects using `del` to release memory.
|
||||
- **Use memory profiling tools:** Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- **Limit vocabulary size:** Reduce the vocabulary size by filtering out infrequent words.
|
||||
dictionary = corpora.Dictionary(processed_texts)
|
||||
|
||||
### 3.3 Rendering Optimization (If Applicable):
|
||||
# Filter out tokens that appear in:
|
||||
# - less than 5 documents (no_below=5)
|
||||
# - more than 60% of documents (no_above=0.6)
|
||||
dictionary.filter_extremes(no_below=5, no_above=0.6)
|
||||
|
||||
- N/A - gensim is primarily a backend library and does not directly involve rendering.
|
||||
# Compactify IDs after filtering
|
||||
dictionary.compactify()
|
||||
```
|
||||
|
||||
### 3.4 Bundle Size Optimization:
|
||||
### 2.3. Streaming Corpora for Large Datasets
|
||||
|
||||
- N/A - gensim is primarily a backend library.
|
||||
For large text collections, always use streaming corpora to keep only one document in memory at a time. This prevents `MemoryError` and allows processing arbitrarily large datasets.
|
||||
|
||||
### 3.5 Lazy Loading:
|
||||
### ❌ BAD: Loading Entire Corpus into Memory
|
||||
|
||||
- Load gensim models and data only when they are needed. This can reduce the initial startup time of your application.
|
||||
- Use lazy initialization for expensive operations.
|
||||
```python
|
||||
# This loads all documents into memory, which is fine for small datasets
|
||||
# but will crash for large ones.
|
||||
corpus = [dictionary.doc2bow(text) for text in all_documents_in_memory]
|
||||
```
|
||||
|
||||
## 4. Security Best Practices:
|
||||
### ✅ GOOD: Streaming Corpus with `MmCorpus`
|
||||
|
||||
### 4.1 Common Vulnerabilities:
|
||||
```python
|
||||
from gensim.corpora import MmCorpus
|
||||
from gensim.utils import simple_preprocess
|
||||
import os
|
||||
|
||||
- **Arbitrary Code Execution:** Avoid loading untrusted gensim models from external sources, as this could lead to arbitrary code execution.
|
||||
- **Denial of Service:** Protect against denial-of-service attacks by limiting the size of input data and the complexity of model training.
|
||||
- **Data Injection:** Sanitize input data to prevent data injection attacks, such as SQL injection or cross-site scripting (XSS).
|
||||
# Assume 'my_large_corpus.txt' contains one document per line
|
||||
class StreamCorpus:
|
||||
def __init__(self, filepath, dictionary):
|
||||
self.filepath = filepath
|
||||
self.dictionary = dictionary
|
||||
|
||||
def __iter__(self):
|
||||
with open(self.filepath, 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
# Preprocess each line (document) on the fly
|
||||
tokens = simple_preprocess(line, deacc=True)
|
||||
yield self.dictionary.doc2bow(tokens)
|
||||
|
||||
# Example usage:
|
||||
# First, build dictionary from a sample or a single pass
|
||||
# For very large corpora, you might need to build the dictionary from a sample
|
||||
# or iterate through the full corpus once to build it.
|
||||
# For simplicity, let's assume `dictionary` is already built.
|
||||
|
||||
# Save corpus to disk in Matrix Market format for streaming
|
||||
# This is a one-time operation if you need to persist the streamed corpus
|
||||
# and iterate over it multiple times without re-preprocessing.
|
||||
# For direct streaming from source, the StreamCorpus class is sufficient.
|
||||
# MmCorpus.serialize('my_corpus.mm', StreamCorpus('my_large_corpus.txt', dictionary))
|
||||
|
||||
# Then, load and use the streamed corpus
|
||||
# streamed_corpus = MmCorpus('my_corpus.mm')
|
||||
# For direct streaming from source:
|
||||
streamed_corpus = StreamCorpus('my_large_corpus.txt', dictionary)
|
||||
|
||||
# Now you can train models on `streamed_corpus` without loading it all into memory
|
||||
# lda_model = models.LdaModel(streamed_corpus, num_topics=10)
|
||||
```
|
||||
|
||||
## 3. Robust Model Training and Evaluation
|
||||
|
||||
### 4.2 Input Validation:
|
||||
Structure your model training for clarity, maintainability, and objective evaluation.
|
||||
|
||||
- Validate all input data to ensure that it conforms to the expected format and range. This can prevent errors and security vulnerabilities.
|
||||
- Use regular expressions or other validation techniques to check the validity of input strings.
|
||||
- Check the size of input data to prevent denial-of-service attacks.
|
||||
### 3.1. Code Organization and Type Hints
|
||||
|
||||
### 4.3 Authentication and Authorization:
|
||||
Separate preprocessing, model building, and evaluation into distinct, type-annotated functions or modules. This mirrors standard Python package structure and facilitates unit testing.
|
||||
|
||||
- N/A - gensim itself does not provide authentication or authorization mechanisms. These mechanisms should be implemented at the application level.
|
||||
### ❌ BAD: Monolithic Script, Magic Numbers
|
||||
|
||||
### 4.4 Data Protection:
|
||||
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure communication protocols (e.g., HTTPS) to protect data in transit.
|
||||
- Implement access control policies to restrict access to sensitive data.
|
||||
- Anonymize or pseudonymize data to protect user privacy.
|
||||
|
||||
### 4.5 Secure API Communication:
|
||||
|
||||
- N/A - gensim itself does not provide APIs for communication with other services. Secure API communication should be implemented at the application level.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
### 5.1 Unit Testing:
|
||||
|
||||
- Write unit tests for individual functions and classes. This ensures that each component of your code works as expected.
|
||||
- Use a testing framework like `pytest` or `unittest` to write and run your unit tests.
|
||||
- Mock external dependencies to isolate the code under test.
|
||||
- Cover all branches of your code with unit tests.
|
||||
|
||||
### 5.2 Integration Testing:
|
||||
|
||||
- Write integration tests to verify that different components of your application work together correctly.
|
||||
- Test the interaction between your gensim code and other libraries or services.
|
||||
- Use realistic test data to simulate real-world scenarios.
|
||||
|
||||
### 5.3 End-to-End Testing:
|
||||
|
||||
- Write end-to-end tests to verify that your entire application works as expected.
|
||||
- Test the application from the user's perspective.
|
||||
- Automate your end-to-end tests to ensure that they are run regularly.
|
||||
|
||||
### 5.4 Test Organization:
|
||||
|
||||
- Organize your tests into a logical directory structure that mirrors your code structure.
|
||||
- Use descriptive names for your test files and test functions.
|
||||
- Group related tests into test classes.
|
||||
|
||||
### 5.5 Mocking and Stubbing:
|
||||
|
||||
- Use mocking and stubbing techniques to isolate the code under test.
|
||||
- Mock external dependencies to avoid relying on external services or data.
|
||||
- Use stubs to provide predefined responses to function calls.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
### 6.1 Frequent Mistakes:
|
||||
|
||||
- **Incorrect Data Types:** Ensure that you are using the correct data types for gensim functions and classes. For example, gensim expects input documents to be a list of tokens, not a string.
|
||||
- **Incorrect Model Parameters:** Tune the model parameters (e.g., number of topics, alpha, beta) to optimize topic coherence. Incorrect model parameters can lead to poor results.
|
||||
- **Ignoring Preprocessing Steps:** Proper preprocessing is critical to the success of topic modelling. Always preprocess your data before training a gensim model.
|
||||
- **Forgetting to Save/Load Models:** Trained models should be saved to disk using `model.save` and loaded using `gensim.models.LdaModel.load` or equivalent methods for other models.
|
||||
|
||||
### 6.2 Edge Cases:
|
||||
|
||||
- **Empty Documents:** Handle empty documents gracefully. Empty documents can cause errors during corpus creation or model training.
|
||||
- **Documents with Only Stop Words:** Remove stop words from your documents to improve model quality. However, be aware that removing all stop words from a document can result in an empty document.
|
||||
- **Very Short Documents:** Very short documents may not contain enough information to be effectively modeled.
|
||||
|
||||
### 6.3 Version-Specific Issues:
|
||||
|
||||
- Be aware of compatibility issues between different versions of gensim. Refer to the gensim documentation for information on version-specific changes.
|
||||
- Use a virtual environment to manage dependencies and avoid version conflicts.
|
||||
|
||||
### 6.4 Compatibility Concerns:
|
||||
|
||||
- Ensure that your version of gensim is compatible with other libraries you are using, such as NumPy, SciPy, and scikit-learn.
|
||||
- Use a virtual environment to manage dependencies and avoid version conflicts.
|
||||
|
||||
### 6.5 Debugging Strategies:
|
||||
|
||||
- Use a debugger to step through your code and inspect variables.
|
||||
- Print intermediate results to verify that your code is working as expected.
|
||||
- Use logging to track the execution of your code and identify potential problems.
|
||||
- Read the gensim documentation and search for solutions online.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
### 7.1 Recommended Development Tools:
|
||||
|
||||
- **Python:** Use Python 3.7 or later.
|
||||
- **Virtual Environment:** Use a virtual environment to manage dependencies and avoid version conflicts.
|
||||
- **IDE:** Use an IDE such as VS Code, PyCharm, or Jupyter Notebook.
|
||||
- **Testing Framework:** Use a testing framework such as `pytest` or `unittest`.
|
||||
- **Memory Profiler:** Use a memory profiler such as `memory_profiler` to identify memory leaks and optimize memory usage.
|
||||
|
||||
### 7.2 Build Configuration:
|
||||
|
||||
- Use a `requirements.txt` file to specify project dependencies.
|
||||
- Use a `setup.py` file to define your project metadata and package your code for distribution.
|
||||
- Use a build tool such as `Make` or `tox` to automate the build process.
|
||||
|
||||
### 7.3 Linting and Formatting:
|
||||
|
||||
- Use a linter such as `flake8` or `pylint` to enforce coding standards.
|
||||
- Use a formatter such as `black` or `autopep8` to automatically format your code.
|
||||
- Configure your IDE to automatically run the linter and formatter on save.
|
||||
|
||||
### 7.4 Deployment:
|
||||
|
||||
- Use a containerization tool such as Docker to package your application and its dependencies into a portable container.
|
||||
- Use a deployment platform such as AWS, Google Cloud, or Azure to deploy your application to the cloud.
|
||||
- Use a process manager such as `systemd` or `supervisor` to manage your application's processes.
|
||||
|
||||
### 7.5 CI/CD Integration:
|
||||
|
||||
- Use a continuous integration/continuous deployment (CI/CD) tool such as Jenkins, Travis CI, or CircleCI to automate the build, test, and deployment process.
|
||||
- Configure your CI/CD pipeline to run your linters, formatters, and tests on every commit.
|
||||
- Configure your CI/CD pipeline to automatically deploy your application to the cloud when tests pass.
|
||||
|
||||
By adhering to these best practices, you can significantly improve the quality, maintainability, and performance of your gensim projects. Always consult the official gensim documentation for the most up-to-date information and guidance.
|
||||
```python
|
||||
# main.py
|
||||
import gensim
|
||||
# ... lots of code ...
|
||||
# Preprocessing, model training, and evaluation all mixed
|
||||
lda = gensim.models.LdaModel(corpus, num_topics=5, passes=10)
|
||||
# ... more code ...
|
||||
```
|
||||
|
||||
### ✅ GOOD: Modular, Type-Hinted Functions
|
||||
|
||||
```python
|
||||
# my_project/preprocessing.py
|
||||
from typing import List
|
||||
from gensim import corpora
|
||||
import spacy
|
||||
|
||||
nlp = spacy.load("en_core_web_sm", disable=['parser', 'ner'])
|
||||
|
||||
def create_dictionary(documents: List[List[str]]) -> corpora.Dictionary:
|
||||
dictionary = corpora.Dictionary(documents)
|
||||
dictionary.filter_extremes(no_below=5, no_above=0.6)
|
||||
dictionary.compactify()
|
||||
return dictionary
|
||||
|
||||
# my_project/models.py
|
||||
from gensim import models, corpora
|
||||
from typing import Optional
|
||||
|
||||
def train_lda_model(corpus: corpora.MmCorpus, dictionary: corpora.Dictionary,
|
||||
num_topics: int, passes: int, random_state: Optional[int] = None) -> models.LdaModel:
|
||||
"""Trains an LDA model with specified parameters."""
|
||||
return models.LdaModel(
|
||||
corpus=corpus,
|
||||
id2word=dictionary,
|
||||
num_topics=num_topics,
|
||||
passes=passes,
|
||||
random_state=random_state
|
||||
)
|
||||
|
||||
# my_project/evaluation.py
|
||||
from gensim import models, corpora
|
||||
from gensim.models import CoherenceModel
|
||||
|
||||
def evaluate_coherence(model: models.LdaModel, texts: List[List[str]],
|
||||
dictionary: corpora.Dictionary, coherence_metric: str = 'c_v') -> float:
|
||||
"""Calculates topic coherence for an LDA model."""
|
||||
coherence_model = CoherenceModel(
|
||||
model=model,
|
||||
texts=texts,
|
||||
dictionary=dictionary,
|
||||
coherence=coherence_metric
|
||||
)
|
||||
return coherence_model.get_coherence()
|
||||
|
||||
# main.py (entry point)
|
||||
import logging
|
||||
import numpy as np
|
||||
from gensim.utils import randseed
|
||||
from my_project.preprocessing import preprocess_document, create_dictionary
|
||||
from my_project.models import train_lda_model
|
||||
from my_project.evaluation import evaluate_coherence
|
||||
|
||||
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
|
||||
randseed = 42
|
||||
np.random.seed(randseed)
|
||||
|
||||
if __name__ == "__main__":
|
||||
raw_documents = ["Doc 1 content...", "Doc 2 content..."] # Load from file in real app
|
||||
processed_texts = [preprocess_document(doc) for doc in raw_documents]
|
||||
dictionary = create_dictionary(processed_texts)
|
||||
corpus = [dictionary.doc2bow(text) for text in processed_texts] # Use streaming for large corpus
|
||||
|
||||
# Hyperparameters documented explicitly
|
||||
NUM_TOPICS = 10
|
||||
NUM_PASSES = 15
|
||||
|
||||
lda_model = train_lda_model(corpus, dictionary, NUM_TOPICS, NUM_PASSES, randseed)
|
||||
coherence_score = evaluate_coherence(lda_model, processed_texts, dictionary)
|
||||
|
||||
logging.info(f"LDA Model Coherence (c_v): {coherence_score:.4f}")
|
||||
```
|
||||
|
||||
### 3.2. Prefer LDA or LDA-Mallet
|
||||
|
||||
For topic modeling, `gensim`'s Latent Dirichlet Allocation (LDA) or its wrapper for [LDA-Mallet](https://radimrehurek.com/gensim/models/ldamallet.html) are the recommended choices. Evaluate topic quality using coherence scores.
|
||||
|
||||
```python
|
||||
from gensim.models import LdaModel, LdaMallet
|
||||
from gensim.models import CoherenceModel
|
||||
|
||||
# After training your LDA model:
|
||||
# lda_model = LdaModel(...)
|
||||
|
||||
# Calculate coherence score
|
||||
coherence_model_lda = CoherenceModel(model=lda_model, texts=processed_texts,
|
||||
dictionary=dictionary, coherence='c_v')
|
||||
coherence_lda = coherence_model_lda.get_coherence()
|
||||
logging.info(f"LDA Coherence: {coherence_lda}")
|
||||
|
||||
# If using LDA-Mallet (requires Mallet installation)
|
||||
# mallet_path = '/path/to/mallet-2.0.8/bin/mallet' # Update this path
|
||||
# ldamallet_model = LdaMallet(mallet_path, corpus=corpus, num_topics=NUM_TOPICS,
|
||||
# id2word=dictionary, iterations=NUM_PASSES, random_state=randseed)
|
||||
|
||||
# coherence_model_ldamallet = CoherenceModel(model=ldamallet_model, texts=processed_texts,
|
||||
# dictionary=dictionary, coherence='c_v')
|
||||
# coherence_ldamallet = coherence_model_ldamallet.get_coherence()
|
||||
# logging.info(f"LDA-Mallet Coherence: {coherence_ldamallet}")
|
||||
```
|
||||
|
||||
## 4. Performance Considerations
|
||||
|
||||
### 4.1. Serialize Transformed Corpora
|
||||
|
||||
If you apply a transformation (e.g., TF-IDF) to a corpus and iterate over the transformed corpus multiple times, serialize the result to disk. `gensim` transformations are often lazy, recomputing on each iteration.
|
||||
|
||||
```python
|
||||
from gensim import models, corpora
|
||||
|
||||
# tfidf_model = models.TfidfModel(corpus)
|
||||
# corpus_tfidf = tfidf_model[corpus] # This is a lazy wrapper
|
||||
|
||||
# If you iterate `corpus_tfidf` multiple times, serialize it:
|
||||
# corpora.MmCorpus.serialize('/tmp/corpus_tfidf.mm', corpus_tfidf)
|
||||
# Then load and use:
|
||||
# persistent_corpus_tfidf = corpora.MmCorpus('/tmp/corpus_tfidf.mm')
|
||||
```
|
||||
|
||||
## 5. Dependency Management
|
||||
|
||||
Always lock your dependencies using `requirements.txt` or `pyproject.toml` to ensure reproducibility across environments.
|
||||
|
||||
### ❌ BAD: Unspecified Dependencies
|
||||
|
||||
```
|
||||
# No requirements.txt or pyproject.toml
|
||||
# Relying on global environment or implicit versions
|
||||
```
|
||||
|
||||
### ✅ GOOD: Locked Dependencies
|
||||
|
||||
```toml
|
||||
# pyproject.toml (preferred for modern Python projects)
|
||||
[project]
|
||||
name = "my-gensim-project"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"gensim==4.3.2",
|
||||
"spacy==3.7.4",
|
||||
"en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.0/en_core_web_sm-3.7.0-py3-none-any.whl",
|
||||
"numpy==1.26.4",
|
||||
"pyldavis==3.4.1",
|
||||
]
|
||||
```
|
||||
|
||||
## 6. Testing Approaches
|
||||
|
||||
Implement unit tests for your preprocessing functions, dictionary creation, and model evaluation logic. This ensures that changes don't silently break your NLP pipeline.
|
||||
|
||||
```python
|
||||
# tests/test_preprocessing.py
|
||||
import unittest
|
||||
from my_project.preprocessing import preprocess_document, create_dictionary
|
||||
|
||||
class TestPreprocessing(unittest.TestCase):
|
||||
def test_preprocess_document(self):
|
||||
text = "This is a test document with some stopwords."
|
||||
expected_tokens = ['test', 'document', 'stopword'] # Assuming 'this', 'is', 'a', 'with', 'some' are stopwords
|
||||
self.assertEqual(preprocess_document(text), expected_tokens)
|
||||
|
||||
def test_create_dictionary_filtering(self):
|
||||
texts = [
|
||||
['apple', 'banana', 'apple'],
|
||||
['banana', 'orange'],
|
||||
['apple', 'orange', 'grape'],
|
||||
['kiwi', 'kiwi', 'kiwi'] # Appears in 1 doc, freq 3
|
||||
]
|
||||
# no_below=2, no_above=0.5 (filter 'kiwi' and 'apple' if it appears in > 2 docs)
|
||||
dictionary = create_dictionary(texts)
|
||||
self.assertIn('banana', dictionary.token2id)
|
||||
self.assertIn('orange', dictionary.token2id)
|
||||
self.assertNotIn('kiwi', dictionary.token2id) # filtered by no_below=2
|
||||
# 'apple' appears in 2/4 docs = 0.5, so it should be kept if no_above > 0.5, or filtered if no_above <= 0.5
|
||||
# With default no_above=0.6, 'apple' should be kept.
|
||||
self.assertIn('apple', dictionary.token2id)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
```
|
||||
Reference in New Issue
Block a user