Representations¶
BaseRepresentation
¶
Bases: BaseEstimator
The base representation model for fine-tuning topic representations.
Source code in bertopic\representation\_base.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Extract topics.
Each representation model that inherits this class will have its arguments automatically passed. Therefore, the representation model will only have access to the information about topics related to those arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
The BERTopic model that is fitted until topic representations are calculated. |
required |
corpus |
Corpus
|
Documents and their metadata. |
required |
topic_representations |
dict[int, Keywords]
|
A dictionary mapping topic IDs to their Keywords representations as calculated by c-TF-IDF. |
required |
c_tf_idf |
csr_matrix
|
A c-TF-IDF representation that is typically
identical to |
required |
embeddings |
ndarray | None
|
Pre-trained document embeddings. |
None
|
Source code in bertopic\representation\_base.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
Cohere
¶
Bases: LLMRepresentation
Use the Cohere API to generate topic labels based on their generative model.
Find more about their models here: https://docs.cohere.ai/docs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client |
A |
required | |
model |
str
|
Model to use within Cohere, defaults to |
'command-r7b-12-2024'
|
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
system_prompt |
str | None
|
The system prompt to be used in the model. If no system prompt is given,
|
None
|
json_schema |
dict[str, Any] | bool
|
A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used ( |
False
|
generator_kwargs |
dict[str, Any] | None
|
Kwargs passed to |
None
|
delay_in_seconds |
float | None
|
The delay in seconds between consecutive prompts in order to prevent RateLimitErrors. |
None
|
nr_docs |
int
|
The number of documents to pass to Cohere if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to Cohere. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use this, you will need to install cohere first:
pip install cohere
Then, get yourself an API key and use Cohere's API as follows:
import cohere
from bertopic.representation import Cohere
from bertopic import BERTopic
# Create your representation model
co = cohere.ClientV2(my_api_key)
representation_model = Cohere(co)
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can also use a custom prompt:
prompt = "I have the following documents: [DOCUMENTS]. What topic do they contain?"
representation_model = Cohere(co, prompt=prompt)
You can also use structured output with a JSON schema:
representation_model = Cohere(co, json_schema=True)
Source code in bertopic\representation\_cohere.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
KeyBERTInspired
¶
Bases: BaseRepresentation
Source code in bertopic\representation\_keybert.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
__init__(top_n_words=10, nr_repr_docs=5, nr_samples=500, nr_candidate_words=100, random_state=42)
¶
Use a KeyBERT-like model to fine-tune the topic representations.
The algorithm follows KeyBERT but does some optimization in order to speed up inference.
The steps are as follows. First, we extract the top n representative
documents per topic. To extract the representative documents, we
randomly sample a number of candidate documents per cluster
which is controlled by the nr_samples parameter. Then,
the top n representative documents are extracted by calculating
the c-TF-IDF representation for the candidate documents and finding,
through cosine similarity, which are closest to the topic c-TF-IDF representation.
Next, the top n words per topic are extracted based on their
c-TF-IDF representation, which is controlled by the nr_repr_docs
parameter.
Then, we extract the embeddings for words and representative documents and create topic embeddings by averaging the representative documents. Finally, the most similar words to each topic are extracted by calculating the cosine similarity between word and topic embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
top_n_words |
int
|
The top n words to extract per topic. |
10
|
nr_repr_docs |
int
|
The number of representative documents to extract per cluster. |
5
|
nr_samples |
int
|
The number of candidate documents to extract per cluster. |
500
|
nr_candidate_words |
int
|
The number of candidate words per cluster. |
100
|
random_state |
int
|
The random state for randomly sampling candidate documents. |
42
|
Usage:
from bertopic.representation import KeyBERTInspired
from bertopic import BERTopic
# Create your representation model
representation_model = KeyBERTInspired()
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
Source code in bertopic\representation\_keybert.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Extract topics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
A BERTopic model |
required |
corpus |
Corpus
|
The input documents including (calculated) embeddings |
required |
topic_representations |
dict[int, Keywords]
|
The candidate topic representations |
required |
c_tf_idf |
csr_matrix
|
The topic c-TF-IDF representation |
required |
embeddings |
ndarray
|
Pre-trained document embeddings (not used) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
updated_topics |
dict[int, Keywords]
|
Updated topic representations |
Source code in bertopic\representation\_keybert.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
LangChain
¶
Bases: LLMRepresentation
Using a LangChain chat model to generate topic labels.
Accepts any LangChain chat model (e.g. from init_chat_model, ChatOpenAI,
ChatAnthropic, etc.). For structured output, uses model.with_structured_output()
which automatically selects the best method (provider-native or tool-calling fallback).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
A LangChain chat model instance (e.g. |
required | |
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
system_prompt |
str | None
|
The system prompt to be used in the model. If no system prompt is given,
|
None
|
json_schema |
dict[str, Any] | bool
|
A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used ( |
False
|
generator_kwargs |
dict[str, Any]
|
Kwargs passed to |
{}
|
nr_docs |
int
|
The number of documents to pass to the model if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to the model. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use this, you will need to install the langchain package first. Additionally, you will need a provider package for your chosen model:
pip install langchain langchain-openai
Then, you can use the LangChain representation model as follows:
from langchain.chat_models import init_chat_model
from bertopic.representation import LangChain
from bertopic import BERTopic
# Create your representation model
model = init_chat_model("gpt-6-luna")
representation_model = LangChain(model)
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can also use a custom prompt:
prompt = "I have the following documents: [DOCUMENTS]. What topic do they contain?"
representation_model = LangChain(model, prompt=prompt)
You can also use structured output with a JSON schema:
representation_model = LangChain(model, json_schema=True)
Source code in bertopic\representation\_langchain.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
LiteLLM
¶
Bases: LLMRepresentation
Using the LiteLLM API to generate topic labels.
For an overview of models see:
https://docs.litellm.ai/docs/providers
Arguments:
model: Model to use. Defaults to OpenAI's "gpt-6-luna".
generator_kwargs: Kwargs passed to `litellm.completion`.
prompt: The prompt to be used in the model. If no prompt is given,
`bertopic.representation._prompts.DEFAULT_CHAT_PROMPT` is used instead.
NOTE: Use `"[KEYWORDS]"` and `"[DOCUMENTS]"` in the prompt
to decide where the keywords and documents need to be
inserted.
system_prompt: The system prompt to be used in the model. If no system prompt is given,
`bertopic.representation._prompts.DEFAULT_SYSTEM_PROMPT` is used instead.
json_schema: A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used (`bertopic.representation._prompts.DEFAULT_JSON_SCHEMA`).
Uses LiteLLM's `response_format` with `json_schema` type.
delay_in_seconds: The delay in seconds between consecutive prompts
in order to prevent RateLimitErrors.
exponential_backoff: Retry requests with a random exponential backoff.
A short sleep is used when a rate limit error is hit,
then the requests is retried. Increase the sleep length
if errors are hit until 10 unsuccesfull requests.
If True, overrides `delay_in_seconds`.
nr_docs: The number of documents to pass to LiteLLM if a prompt
with the `["DOCUMENTS"]` tag is used.
diversity: The diversity of documents to pass to LiteLLM.
Accepts values between 0 and 1. A higher
values results in passing more diverse documents
whereas lower values passes more similar documents.
doc_length: The maximum length of each document. If a document is longer,
it will be truncated. If None, the entire document is passed.
tokenizer: The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to `doc_length`
* If tokenizer is 'whitespace', the document is split up
into words separated by whitespaces. These words are counted
and truncated depending on `doc_length`
* If tokenizer is 'vectorizer', then the internal CountVectorizer
is used to tokenize the document. These tokens are counted
and truncated depending on `doc_length`
* If tokenizer is a callable, then that callable is used to tokenize
the document. These tokens are counted and truncated depending
on `doc_length`
Usage:
To use this, you will need to install the litellm package first:
`pip install litellm`
Then, get yourself an API key of any provider (for instance OpenAI) and use it as follows:
```python
import os
from bertopic.representation import LiteLLM
from bertopic import BERTopic
# set ENV variables
os.environ["OPENAI_API_KEY"] = "your-openai-key"
# Create your representation model
representation_model = LiteLLM(model="gpt-6-luna")
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
```
You can also use a custom prompt:
```python
prompt = "I have the following documents: [DOCUMENTS]
These documents are about the following topic: '"
representation_model = LiteLLM(model="gpt-6-luna", prompt=prompt)
You can also use structured output with a JSON schema:python
representation_model = LiteLLM(model="gpt-6-luna", json_schema=True)
```
Source code in bertopic\representation\_litellm.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
LlamaCPP
¶
Bases: LLMRepresentation
A llama.cpp implementation to use as a representation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
str | Llama
|
Either a string pointing towards a local LLM or a
|
required |
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
system_prompt |
str | None
|
The system prompt to be used in the model. If no system prompt is given,
|
None
|
json_schema |
dict[str, Any] | bool
|
A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used ( |
False
|
generator_kwargs |
dict[str, Any] | None
|
Kwargs passed to |
None
|
nr_docs |
int
|
The number of documents to pass to the model if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to the model. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use a llama.cpp, first download the LLM:
wget https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF/resolve/main/gemma-4-E2B-it-Q4_0.gguf
Then, we can now use the model the model with BERTopic in just a couple of lines:
from bertopic import BERTopic
from bertopic.representation import LlamaCPP
# Use llama.cpp to load in a 4-bit quantized version of Gemma 4 E2B
representation_model = LlamaCPP("gemma-4-E2B-it-Q4_0.gguf")
# Create our BERTopic model
topic_model = BERTopic(representation_model=representation_model, verbose=True)
If you want to have more control over the LLMs parameters, you can run it like so:
from bertopic import BERTopic
from bertopic.representation import LlamaCPP
from llama_cpp import Llama
# Use llama.cpp to load in a 4-bit quantized version of Gemma 4 E2B
llm = Llama(model_path="gemma-4-E2B-it-Q4_0.gguf", n_gpu_layers=-1, n_ctx=16384)
representation_model = LlamaCPP(llm)
# Create our BERTopic model
topic_model = BERTopic(representation_model=representation_model, verbose=True)
You can also use structured output with a JSON schema:
representation_model = LlamaCPP("gemma-4-E2B-it-Q4_0.gguf", json_schema=True)
Source code in bertopic\representation\_llamacpp.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
MaximalMarginalRelevance
¶
Bases: BaseRepresentation
Calculate Maximal Marginal Relevance (MMR) between candidate keywords and the document.
MMR considers the similarity of keywords/keyphrases with the document, along with the similarity of already selected keywords and keyphrases. This results in a selection of keywords that maximize their within diversity with respect to the document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diversity |
float
|
How diverse the select keywords/keyphrases are. Values range between 0 and 1 with 0 being not diverse at all and 1 being most diverse. |
0.1
|
top_n_words |
int
|
The number of keywords/keyhprases to return |
10
|
Usage:
from bertopic.representation import MaximalMarginalRelevance
from bertopic import BERTopic
# Create your representation model
representation_model = MaximalMarginalRelevance(diversity=0.3)
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
Source code in bertopic\representation\_mmr.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Extract topic representations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
The BERTopic model |
required |
corpus |
Corpus
|
The input documents including (calculated) embeddings |
required |
topic_representations |
dict[int, Keywords]
|
The candidate topic representations |
required |
c_tf_idf |
csr_matrix
|
The topic c-TF-IDF representation |
required |
embeddings |
ndarray
|
Pre-trained document embeddings (not used) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
updated_topics |
dict[int, Keywords]
|
Updated topic representations |
Source code in bertopic\representation\_mmr.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
MultiModalRepresentation
¶
Bases: TextConverter
Represent topics by their media, and describe that media so c-TF-IDF has words.
A topic that holds photographs and voice notes is one topic, so it gets one
representation carrying both. The same sample of representative media serves twice:
it is described in text, which is what gives a media-only corpus any keywords at all,
and it is kept as the topic's Media representation. Each modality also gets one
summary that stands for the topic: a collage of its images, a sheet of its videos'
middle frames, and a montage of the first seconds of its audio.
Describing every item would be prohibitive on a corpus of millions, so only
nr_repr_media items per topic are described. MMR picks them near each topic's
centroid while discarding near-duplicates.
A modality without its own model is described by model. Note that a model name
is loaded into that modality's own task, so one name rarely covers both captioning
and transcription; a callable can, since it decides for itself. Models are loaded on
first use, so a modality absent from the corpus costs nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
str | Pipeline | Callable | None
|
The model that describes media in words, for any modality without its own.
Either the name of a model to load into a |
None
|
image_model |
str | Pipeline | Callable | None
|
The model that describes only images. |
None
|
audio_model |
str | Pipeline | Callable | None
|
The model that transcribes only audio. |
None
|
video_model |
str | Pipeline | Callable | None
|
The model that describes only video. |
None
|
nr_repr_media |
int
|
Number of representative media items to describe per topic. |
9
|
nr_frames |
int
|
Number of frames to sample from each video, since one still cannot stand for a clip. |
3
|
image_height |
int
|
The height of the resulting collage and frame sheet. |
600
|
image_squares |
bool
|
Whether to crop each image in a collage or frame sheet to fill a square, rather than keep it whole in a cell of the images' typical shape. |
False
|
prompt |
str
|
What to ask the model for, when it is a pipeline rather than a callable. |
'Describe this image in one short sentence.'
|
batch_size |
int
|
The number of items to describe at a time. |
4
|
Usage:
from bertopic import BERTopic
from bertopic.representation import MultiModalRepresentation
# Media is an additional way of looking at a topic, so it is passed as an aspect
representation_model = {
"Media": MultiModalRepresentation(
"HuggingFaceTB/SmolVLM-256M-Instruct", audio_model="openai/whisper-base"
)
}
topic_model = BERTopic(representation_model=representation_model)
Source code in bertopic\representation\_multimodal.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Collect each topic's representative media into a single representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
A BERTopic model |
required |
corpus |
Corpus
|
The input documents including (calculated) embeddings |
required |
topic_representations |
dict[int, Keywords]
|
The candidate topic representations |
required |
c_tf_idf |
csr_matrix
|
The topic c-TF-IDF representation (unused, for API compatibility) |
required |
embeddings |
ndarray
|
Pre-trained document embeddings (unused, for API compatibility) |
None
|
Returns:
| Type | Description |
|---|---|
dict[int, Media]
|
A |
dict[int, Media]
|
and empty for a topic without media so every topic has the same columns |
Source code in bertopic\representation\_multimodal.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
to_text(corpus)
¶
Describe a sample of each topic's media, writing into those rows' text channel.
The corpus keeps its shape. Only sampled rows without text gain some, so documents, captions the user gave, and modalities this model does not handle are left exactly as they were, and several converters can run one after another without overwriting each other.
Source code in bertopic\representation\_multimodal.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
Ollama
¶
Bases: LLMRepresentation
Using the Ollama API to generate topic labels based on a local LLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
str
|
Model to use within Ollama. |
required |
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
system_prompt |
str | None
|
The system prompt to be used in the model. If no system prompt is given,
|
None
|
json_schema |
dict[str, Any] | bool
|
A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used ( |
False
|
generator_kwargs |
dict[str, Any] | None
|
Kwargs passed to |
None
|
nr_docs |
int
|
The number of documents to pass to Ollama if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to Ollama. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use this, you will need to install the ollama package first:
pip install ollama
Then, you can use the Ollama representation model as follows:
from bertopic.representation import Ollama
from bertopic import BERTopic
# Create your representation model
representation_model = Ollama("gemma4")
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can also use a custom prompt:
prompt = "I have the following documents: [DOCUMENTS] \nThese documents are about the following topic: '"
representation_model = Ollama("gemma4", prompt=prompt)
Source code in bertopic\representation\_ollama.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
OpenAI
¶
Bases: LLMRepresentation
Using the OpenAI Chat Completions API to generate topic labels.
Uses OpenAI's Chat Completions API, which OpenAI-compatible servers such as vLLM, LM Studio and Ollama serve as well, with Structured Outputs for schema-adherent JSON generation.
For an overview see: https://developers.openai.com/api/docs/guides/text https://developers.openai.com/api/docs/guides/structured-outputs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client |
A |
required | |
model |
str
|
Model to use within OpenAI, defaults to |
'gpt-6-luna'
|
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
system_prompt |
str | None
|
The system prompt to be used in the model. If no system prompt is given,
|
None
|
json_schema |
dict[str, Any] | bool
|
A dictionary representing the JSON schema to enforce structured output.
If set to True, a default schema will be used ( |
False
|
generator_kwargs |
dict[str, Any] | None
|
Kwargs passed to |
None
|
delay_in_seconds |
float | None
|
The delay in seconds between consecutive prompts in order to prevent RateLimitErrors. |
None
|
exponential_backoff |
bool
|
Retry requests with a random exponential backoff.
A short sleep is used when a rate limit error is hit,
then the requests is retried. Increase the sleep length
if errors are hit until 10 unsuccessful requests.
If True, overrides |
False
|
nr_docs |
int
|
The number of documents to pass to OpenAI if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to OpenAI. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use this, you will need to install the openai package first:
pip install openai
Then, get yourself an API key and use OpenAI's API as follows:
import openai
from bertopic.representation import OpenAI
from bertopic import BERTopic
# Create your representation model
client = openai.OpenAI(api_key=MY_API_KEY)
representation_model = OpenAI(client)
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can also use a custom prompt:
prompt = "I have the following documents: [DOCUMENTS] \nThese documents are about the following topic: '"
representation_model = OpenAI(client, prompt=prompt)
You can also use structured output with a JSON schema:
representation_model = OpenAI(client, json_schema=True)
Source code in bertopic\representation\_openai.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
PartOfSpeech
¶
Bases: BaseRepresentation
Extract Topic Keywords based on their Part-of-Speech.
DEFAULT_PATTERNS = [ [{'POS': 'ADJ'}, {'POS': 'NOUN'}], [{'POS': 'NOUN'}], [{'POS': 'ADJ'}] ]
From candidate topics, as extracted with c-TF-IDF, find documents that contain keywords found in the candidate topics. These candidate documents then serve as the representative set of documents from which the Spacy model can extract a set of candidate keywords for each topic.
These candidate keywords are first judged by whether they fall within the DEFAULT_PATTERNS or the user-defined pattern. Then, the resulting keywords are sorted by their respective c-TF-IDF values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
str | Language
|
The Spacy model to use |
'en_core_web_sm'
|
top_n_words |
int
|
The top n words to extract |
10
|
pos_patterns |
list[str] | None
|
Patterns for Spacy to use. See https://spacy.io/usage/rule-based-matching |
None
|
Usage:
from bertopic.representation import PartOfSpeech
from bertopic import BERTopic
# Create your representation model
representation_model = PartOfSpeech("en_core_web_sm")
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can define custom POS patterns to be extracted:
pos_patterns = [
[{'POS': 'ADJ'}, {'POS': 'NOUN'}],
[{'POS': 'NOUN'}], [{'POS': 'ADJ'}]
]
representation_model = PartOfSpeech("en_core_web_sm", pos_patterns=pos_patterns)
Source code in bertopic\representation\_pos.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Extract topics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
A BERTopic model |
required |
corpus |
Corpus
|
The input documents including (calculated) embeddings |
required |
topic_representations |
dict[int, Keywords]
|
The candidate topic representations |
required |
c_tf_idf |
csr_matrix
|
The topic c-TF-IDF representation, with a row per topic in |
required |
embeddings |
ndarray
|
Not used |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
updated_topics |
dict[int, Keywords]
|
Updated topic representations |
Source code in bertopic\representation\_pos.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
TextGeneration
¶
Bases: LLMRepresentation
Text generation with transformers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
Union[str, pipeline]
|
A transformers pipeline that should be initialized as "text-generation",
for example |
required |
prompt |
str | None
|
The prompt to be used in the model. If no prompt is given,
|
None
|
pipeline_kwargs |
dict[str, Any]
|
Kwargs that you can pass to the transformers.pipeline when it is called. |
{}
|
random_state |
int
|
A random state to be passed to |
42
|
nr_docs |
int
|
The number of documents to pass to the model if a prompt
with the |
4
|
diversity |
float | None
|
The diversity of documents to pass to the model. Accepts values between 0 and 1. A higher values results in passing more diverse documents whereas lower values passes more similar documents. |
None
|
doc_length |
int | None
|
The maximum length of each document. If a document is longer, it will be truncated. If None, the entire document is passed. |
None
|
tokenizer |
str | Callable | None
|
The tokenizer used to calculate to split the document into segments
used to count the length of a document.
* If tokenizer is 'char', then the document is split up
into characters which are counted to adhere to |
None
|
Usage:
To use a model from the Hugging Face Hub:
from bertopic.representation import TextGeneration
from bertopic import BERTopic
# Create your representation model
representation_model = TextGeneration('google/gemma-4-E2B-it')
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
You can use a custom prompt and decide where the keywords should
be inserted by using the [KEYWORDS] or documents with the [DOCUMENTS] tag:
from transformers import pipeline
from bertopic.representation import TextGeneration
prompt = (
"I have a topic described by the following keywords: [KEYWORDS]. "
"Give a short label for this topic, and nothing else."
)
# Create your representation model
generator = pipeline('text-generation', model='google/gemma-4-E2B-it')
representation_model = TextGeneration(generator, prompt=prompt)
Source code in bertopic\representation\_textgeneration.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
ZeroShotClassification
¶
Bases: BaseRepresentation
Zero-shot Classification on topic keywords with candidate labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidate_topics |
list[str]
|
A list of labels to assign to the topics if they
exceed |
required |
model |
str
|
A transformers pipeline that should be initialized as
"zero-shot-classification". For example,
|
'facebook/bart-large-mnli'
|
pipeline_kwargs |
dict[str, Any]
|
Kwargs that you can pass to the transformers.pipeline
when it is called. NOTE: Use |
{}
|
min_prob |
float
|
The minimum probability to assign a candidate label to a topic |
0.8
|
Usage:
from bertopic.representation import ZeroShotClassification
from bertopic import BERTopic
# Create your representation model
candidate_topics = ["space and nasa", "bicycles", "sports"]
representation_model = ZeroShotClassification(candidate_topics, model="facebook/bart-large-mnli")
# Use the representation model in BERTopic on top of the default pipeline
topic_model = BERTopic(representation_model=representation_model)
Source code in bertopic\representation\_zeroshot.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
extract_topics(topic_model, corpus, topic_representations, c_tf_idf, embeddings=None)
¶
Extract topics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic_model |
BERTopic
|
Not used |
required |
corpus |
Corpus
|
Not used |
required |
topic_representations |
dict[int, Keywords]
|
The candidate topic representations |
required |
c_tf_idf |
csr_matrix
|
Not used |
required |
embeddings |
ndarray
|
Not used |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
updated_topics |
dict[int, Keywords]
|
Updated topic representations |
Source code in bertopic\representation\_zeroshot.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |