pip install gensimInstalls gensim 4.x (a C compiler enables the fast training routines).from gensim import corpora, models, similarities★The three workhorse sub-packages.from gensim.utils import simple_preprocessThe quickest text→tokens helper.import gensim.downloader as apiFetch pretrained vectors & datasets.import logging; logging.basicConfig(level=logging.INFO)See training progress & timings live.gensim.__version__Confirm you're on 4.x — the API changed a lot from 3.x.
simple_preprocess(text, min_len=2)★Lowercase, tokenise, drop punctuation & short tokens.from gensim.utils import tokenizelist(tokenize(text, lowercase=True))— a token generator.from gensim.parsing.preprocessing import preprocess_stringRuns the DEFAULT_FILTERS: strip tags/punct/numeric/short, stopwords, stem.remove_stopwords(text)Drop gensim's 337 built-in English stopwords.from gensim.parsing.preprocessing import STOPWORDSThe frozenset itself — extend or inspect it.stem_text(text)Porter-stem every word (running→run).
dct = corpora.Dictionary(texts)★Build an id map from a list of tokenised docs.dct.token2id{token: id}; reverse withdct[id].dct.doc2bow(tokens)★One doc → sorted bag-of-words[(id,count)].dct.filter_extremes(no_below=5, no_above=0.5)★Drop tokens in <5 docs or >50% of docs, then renumber.dct.add_documents(more_texts)Grow the vocabulary online.dct.save("x.dict") · Dictionary.load("x.dict")Persist so ids stay stable across runs.
corpus = [dct.doc2bow(t) for t in texts]★A list of BoW vectors — the standard corpus.class C:★
def __iter__(self):
for line in open(f): yield dct.doc2bow(line.split())A streaming corpus — never loads the file into memory.corpora.MmCorpus.serialize("c.mm", corpus)Save to Matrix Market format on disk.corpus = corpora.MmCorpus("c.mm")Lazily read it back, one vector at a time.corpora.SvmLightCorpus · BleiCorpus · LowCorpusOther on-disk formats (SVMlight, Blei LDA-C, GibbsLDA).
tfidf = models.TfidfModel(corpus)★Learn document frequencies from the corpus.tfidf[bow]★Transform one vector — rare terms weigh more.tfidf[corpus]A lazy view that transforms the whole corpus on iteration.models.TfidfModel(corpus, smartirs="ntc")Pick an explicit SMART weighting scheme.models.OkapiBM25Model(corpus)4.xBM25 ranking transform — often stronger for retrieval.normalize=TrueL2-normalise output to unit length (the default).
lsi = models.LsiModel(tfidf[corpus], id2word=dct, num_topics=200)★Compress into latent semantic dimensions via truncated SVD.lsi[bow]Project a document into the low-dim topic space.lsi.print_topics(5)Show the top-weighted terms per topic.lsi.add_documents(more)Incremental / online update — no full retrain.models.RpModel · models.LogEntropyModelRandom-projection & log-entropy transforms.
lda = models.LdaModel(corpus, id2word=dct, num_topics=10, passes=10, random_state=1)★The classic topic model — each doc is a mix of topics.models.LdaMulticore(corpus, id2word=dct, num_topics=10, workers=4)★Parallel LDA — much faster on many cores.lda.print_topics(num_words=5)★The top terms defining each topic.lda.get_document_topics(bow)★This doc's topic mixture[(topic, prob)].lda.show_topic(0, topn=10)(word, prob)pairs for one topic.lda.update(new_corpus)Online update with fresh documents.lda.log_perplexity(corpus)Held-out fit (lower is better).
models.HdpModel(corpus, id2word=dct)Hierarchical Dirichlet Process — infers the topic count for you.models.Nmf(corpus, num_topics=10)Non-negative matrix factorisation topics.models.LdaSeqModel(...)Dynamic topics that drift over time slices.models.AuthorTopicModel(...)Topic distributions per author.models.EnsembleLda(...)Find stable topics across many LDA runs.
from gensim.models import PhrasesDetect collocations from co-occurrence stats.bigram = Phrases(sentences, min_count=5, threshold=10)★Learn "new york" →new_york.bigram[sentence]★Apply the transform to glue phrases.frozen = bigram.freeze()4.xFreeze for speed/memory (wasPhraserin 3.x).from gensim.models.phrases import ENGLISH_CONNECTOR_WORDSPass asconnector_words=to skip of/the/and.Word2Vec(bigram[corpus])Feed phrased tokens straight into an embedding model.
index = similarities.MatrixSimilarity(lsi[corpus], num_features=len(dct))★In-RAM cosine index over transformed docs.similarities.SparseMatrixSimilarity(corpus, num_features=...)Sparse variant for large, high-dim vocabularies.index = similarities.Similarity("/tmp/idx", corpus, num_features=...)★Sharded to disk — scales past RAM.sims = index[query_vec]★Cosine of the query against every document.sorted(enumerate(sims), key=lambda x: -x[1])Turn scores into a ranked hit list.similarities.SoftCosineSimilarity · WmdSimilarityEmbedding-aware indexes (soft cosine, Word Mover's).
cm = models.CoherenceModel(model=lda, texts=texts, dictionary=dct, coherence="c_v")★Score how interpretable the topics are.cm.get_coherence()★Higher = more coherent topics.coherence="u_mass"Faster metric — needscorpus=, nottexts=.for k in range(2,20): ... compare coherence★Sweepnum_topicsand keep the peak.wv.evaluate_word_analogies("questions-words.txt")Analogy accuracy for embeddings.wv.evaluate_word_pairs("wordsim353.tsv")Correlation with human similarity judgements.
import gensim.downloader as apiThe pretrained model & dataset hub.api.info()["models"].keys()List everything you can download.wv = api.load("glove-wiki-gigaword-100")★GloVe 100-d vectors — returns a KeyedVectors.api.load("word2vec-google-news-300")3M words/phrases (~1.7 GB download).corpus = api.load("text8")A dataset (iterable of token lists), not a model.~/gensim-data/Where downloads are cached.
model.save("m.model")★Native pickle — keeps full state, so training can resume.Model.load("m.model")★Restore any gensim object.wv.save_word2vec_format("v.txt", binary=False)Portable vectors-only export (loses training state).KeyedVectors.load_word2vec_format("v.bin", binary=True)Read that portable format back.corpora.MmCorpus.serialize(...) · dct.save(...)Persist corpus & dictionary alongside the model.Model.load("m.model", mmap="r")Memory-map big models to share across processes.