Registry / data / gensim

gensim

JSON →
library4.4.0pypypi✓ verified 25d ago

Gensim is a Python library for topic modeling, document indexing, and similarity retrieval with large corpora. It is currently at version 4.4.0 and maintains an active release cadence with regular updates and bug fixes, including recent support for NumPy 2.0. Designed for natural language processing (NLP) and information retrieval (IR) tasks, it supports memory-independent processing for datasets larger than RAM.

pip install gensim
INSTALL
IMPORT
SIG · GENSIM
G
gensim
datapythonv4.4.0
Install
8.9s avg
Import
3180ms
Disk
283MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
build_error
glibc
py 3.103.95 runs
installs and imports cleanly · install 8.9s · import 3.180s · 279MB
283MB installed
● package 283MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Word2Vec
from gensim.models import Word2Vec
Doc2Vec
from gensim.models import Doc2Vec
LdaModel
from gensim.models import LdaModel
Dictionary
from gensim.corpora import Dictionary
simple_preprocess
from gensim.utils import simple_preprocess
model.wv.index_to_key
model.wv.index_to_key
model.wv.vocab.keys()
In Gensim 4.0+, the `vocab` attribute was removed from `KeyedVectors`. Use `model.wv.index_to_key` for a list of words or `model.wv.key_to_index` for a word-to-index mapping.
model.wv.most_similar()
model.wv.most_similar(word)
model.most_similar(word)
Many vector-related methods (like `most_similar`, `wmdistance`, `doesnt_match`, `similarity`) were moved from the top-level model object to the `KeyedVectors` object (`.wv`) in Gensim 4.0+.

This quickstart demonstrates how to preprocess text, create a dictionary, train a Word2Vec model, and then save, load, and use the model to find similar words. It highlights best practices for corpus preparation and basic model interaction.

import logging from gensim.models import Word2Vec from gensim.corpora import Dictionary from gensim.utils import simple_preprocess logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # Sample corpus corpus = [ "Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relation of user perceived response time to error measurement", "The generation of random binary non-linear sequences of great length", "The interaction of user and computer in an easy way", "Doctors use computers for medical diagnosis", "A quick brown fox jumps over the lazy dog" ] # Preprocess the corpus: tokenize, lowercase, and filter tokenized_corpus = [simple_preprocess(doc) for doc in corpus] # Create a dictionary from the tokenized corpus dictionary = Dictionary(tokenized_corpus) # Filter out words that appear in less than 2 documents or more than 50% of documents dictionary.filter_extremes(no_below=2, no_above=0.5) # Prepare corpus for Word2Vec training (list of lists of words) # Word2Vec expects an iterable of sentences, where each sentence is a list of words. # Train a Word2Vec model model = Word2Vec( sentences=tokenized_corpus, # Your list of tokenized sentences vector_size=100, # Dimensionality of the word vectors window=5, # Maximum distance between the current and predicted word within a sentence min_count=1, # Ignores all words with total frequency lower than this workers=4, # Use 4 worker threads to train the model epochs=10 # Number of iterations (epochs) over the corpus ) # Save the model model.save("word2vec_model.model") # Load the model loaded_model = Word2Vec.load("word2vec_model.model") # Find the most similar words to 'computer' if 'computer' in loaded_model.wv: similar_words = loaded_model.wv.most_similar('computer') print("\nWords similar to 'computer':") for word, score in similar_words: print(f"{word}: {score:.4f}") else: print("\n'computer' not in vocabulary.")
Debug
Known issues
breakingGensim 4.0 introduced significant breaking API changes from 3.x. Key attributes and methods were renamed or moved. For example, `model.vocab` was replaced by `model.wv.key_to_index` or `model.wv.index_to_key`, and many vector-related methods like `most_similar()` moved from the model object to `model.wv` (KeyedVectors). The `size` parameter was renamed to `vector_size`, and `iter` to `epochs`.
fix
Consult the official Gensim 3.x to 4.x migration guide on GitHub. Update attribute access (e.g., `model.wv.index_to_key` instead of `model.wv.vocab.keys()`) and method calls (e.g., `model.wv.most_similar()` instead of `model.most_similar()`). Adjust parameter names for model initialization (e.g., `vector_size` instead of `size`, `epochs` instead of `iter`).
affects: 4.0.0 and later
breakingGensim 4.0.0 and later versions officially dropped support for Python 2.7. Users requiring Python 2.7 must use Gensim 3.8.3 or an earlier version.
fix
Upgrade to Python 3.9+ (Gensim 4.4.0 requires >=3.9). If Python 2.7 is strictly necessary, pin Gensim to version 3.8.3: `pip install gensim==3.8.3`.
affects: 4.0.0 and later
gotchaWhile Gensim is designed for memory-independent processing, training models like LDA or Word2Vec on extremely large corpora can still lead to high memory consumption, especially if not preprocessed efficiently or if the entire corpus is loaded into RAM.
fix
Employ memory-efficient practices: filter stopwords, remove rare words, and use Gensim's `MmCorpus` or custom iterators that stream data from disk. Reduce dictionary size by filtering `no_below` and `no_above` extremes. Consider using `LdaMulticore` for LDA models with multiple cores.
affects: All versions
gotchaEnsure your NumPy version is compatible with your Gensim installation. While Gensim 4.4.0 officially added support for NumPy 2.0, older Gensim 4.x releases (e.g., 4.0.1) had specific compatibility issues with NumPy binary packages on Windows.
fix
Always install the latest Gensim version (`pip install --upgrade gensim`) which includes the most recent compatibility fixes. If encountering issues, try pinning NumPy to a known compatible version or ensuring your BLAS libraries are correctly configured if building NumPy from source.
affects: Gensim 4.0.x to 4.3.x, especially with newer NumPy versions.
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'gensim'
The gensim library is not installed in your Python environment, or the Python interpreter you are using does not have access to the installed gensim package. This can also happen if there's a typo in the import statement.
fix
Install gensim using pip: `pip install gensim`. If using a virtual environment, ensure it's activated. If the module was recently installed, try restarting your Python environment or IDE.
AttributeError: module 'gensim' has no attribute 'models'
This error often occurs when your Python script file is named `gensim.py`, causing a conflict with the actual `gensim` library. Python tries to import your file instead of the installed package.
fix
Rename your Python script file to something other than `gensim.py` (e.g., `my_script.py`) to avoid shadowing the installed library.
AttributeError: 'Word2Vec' object has no attribute 'most_similar'
In gensim versions 4.0.0 and later, the `most_similar()` method for `Word2Vec` models was moved from the model object itself to its `.wv` (word vectors) attribute.
fix
Access the `most_similar()` method through the `wv` attribute: `model.wv.most_similar('your_word')`.
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected X from C header, got Y from PyObject
This error typically arises due to an incompatibility between the installed versions of `gensim` and `numpy`. `gensim` often relies on specific `numpy` C API versions for its optimized C extensions.
fix
Uninstall both `gensim` and `numpy`, then reinstall them, ensuring a compatible pair is installed. Often, updating `numpy` first, then reinstalling `gensim` resolves the issue: `pip uninstall numpy gensim && pip install numpy gensim`.
TypeError: 'list' object cannot be interpreted as an integer
This error occurs when a function expects an integer argument (e.g., for sizes or counts), but it receives a list instead. This is common when incorrectly passing a list of tokens where a single integer or an iterable of iterables of strings is expected, such as when initializing a `Dictionary` or training a `Word2Vec` model.
fix
Ensure that the data passed to the `gensim` function matches the expected type. For instance, `Dictionary` expects an iterable of lists of strings (e.g., `[['word1', 'word2'], ['word3']]`). If you're passing a single list of tokens, wrap it in another list: `corpus = [your_list_of_tokens]`.
Upgrade
Version history
4.4.0latest on PyPI · released Oct 18, 2025
Audit
Dependencies
numpyrequiredEssential for numerical operations and core to Gensim's performance.
scipyrequiredUsed for scientific computing tasks within Gensim's algorithms.
smart_openrequiredEnables efficient streaming of very large files, including remote storage and compressed files.
BLAS library (e.g., OpenBLAS, MKL, ATLAS)optionalHighly recommended for significant performance improvements in numerical computations (optional, but NumPy benefits greatly).
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
1
Resources
gensim — pip install gensim · libregistry