How to Group Reviews by Topic with BERTopic

Vladimir Lomtev•
How to Group Reviews by Topic with BERTopic

To group reviews by theme with BERTopic, prepare a CSV with persistent IDs, generate semantic text embeddings, run clustering, and review the content of the discovered groups. Then save a “review — topic” table and give the groups clear names. Reviews labeled -1 should be handled separately: this is not a ready-made “negative” topic and not a reason to delete records.

This guide is intended for analysts and product managers who need to understand what customers are writing about: delivery, missing items, packaging, or other recurring issues. To run the code, you’ll need someone familiar with Python. Customer reply automation is covered separately in the article on automating replies to reviews.

The workflow is based on the official documentation, verified November 9, 2026. BERTopic installation and corpus processing were not performed during preparation of this article. The commands, settings, and sample strings below are a suggested example for adaptation; they do not prove the quality of grouping on your data. Responsible publisher — AI Studio by Vladimir Lomtev.

Contents

Step 1. Define what picture the topics should reveal

BERTopic is a topic modeling library. In the standard approach, it uses embeddings, meaning numerical representations of text meaning, groups similar documents together, and describes topics with characteristic words via c-TF-IDF. These words help interpret the group, but by themselves they are not its business name. The mechanism is described in the official BERTopic overview.

Start with the team’s question: for example, “What delivery issues do customers of this store mention during the selected month?” Record the period, sources, and products included in the analysis. Mixing reviews about different products can produce groups by product names, while the manager needs the reasons for dissatisfaction.

Separate topic from sentiment. “The courier arrived on time” and “The courier was late” both relate to delivery, but evaluate it in opposite ways. BERTopic should not be treated as a ready-made customer satisfaction metric. If you need separate counts of positive and negative reviews, add a separate sentiment label and validate it independently.

Team task Approach
Find unknown recurring patterns Start with thematic grouping and reading examples
Sort reviews into already approved reasons Prepare labels and a classifier with predefined categories
Find urgent safety complaints Use a separate review workflow; topic size does not determine urgency

The result of this step is one analysis question and the sample boundaries. If the categories are already known, it is more useful to start with preparing human annotation than forcing discovered clusters to match a prebuilt reference list.

Step 2. Prepare the CSV and preserve the meaning of the text

The suggested minimal file schema for reviews.csv is review_id,text. Keep additional fields such as date, platform, product, and rating in the original export. The ID is needed to map the results back: row order may change during cleaning or export.

review_id,text
r001,The courier moved the delivery to the next day
r002,The box was missing the fastener
r003,The packaging was intact and the order arrived on time

This is an illustration of the format, not a sufficient corpus for tuning the model. Choose a real, consistent sample in which the topics of interest may recur. There is no universal number of reviews here that guarantees useful topics.

Remove technical markup, empty records, platform signatures, and repeated boilerplate phrases. Keep negations, part names, and circumstances: “they didn’t include the fastener” and “they included a different fastener” lead to different actions. Do not delete identical texts automatically. A repeated upload of the same record is a technical duplicate; the same wording from different customers may reflect complaint frequency. Define the rule for such cases before counting.

Work with authorized data and remove unnecessary phone numbers, addresses, and other personal information in advance. For long reviews, check the input limit of the selected model: the truncated ending may contain the main complaint. The model used below has a Sentence Transformers model card with max_seq_length=128 specified; this is a token sequence limit, not 128 words.

The result of this step is a copy of the CSV with non-empty texts, unique IDs, and a clear selection rule. If you split a long review into fragments, also store the original review ID: the number of fragments cannot be presented as the number of customers.

Step 3. Set up the environment and explicit settings

Create a separate environment and install the dependencies. The following commands are suggested for a standard Linux/macOS shell; package installation and compatibility in your environment need to be verified.

python3 -m venv .venv
. .venv/bin/activate
python -m pip install bertopic pandas sentence-transformers umap-learn hdbscan
python -m pip freeze > requirements-resolved.txt

The basic installation is described in the BERTopic repository. The saved version list is needed to understand which environment produced the files. For a reproducible workflow, also pin the model revision and the source dataset.

In the example, the embedding model is set explicitly: paraphrase-multilingual-MiniLM-L12-v2. This is an accessible multilingual option for an initial study, not a proven best choice for Russian reviews. In the BERTopic FAQ

model selection is tied to the language, the data, and the task. Do not transfer a good result from someone else’s corpus without validation. UMAP and HDBSCAN settings are also specified explicitly so you do not depend on hidden defaults. UMAP reduces the dimensionality of the embeddings, and HDBSCAN identifies dense groups. The values in the code are starter settings for learning, not the optimal configuration. Their purpose and effect are described in the parameter guide

.

Step 4. Get two linked tables Save the code in group_reviews.py

import pandas as pd
from bertopic import BERTopic
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import CountVectorizer
from umap import UMAP
from hdbscan import HDBSCAN

frame = pd.read_csv("reviews.csv", dtype=str, keep_default_na=False)
if not {"review_id", "text"}.issubset(frame.columns):
    raise ValueError("Required columns: review_id and text")
frame["review_id"] = frame["review_id"].str.strip()
frame["text"] = frame["text"].str.strip()
if (frame["review_id"] == "").any() or frame["review_id"].duplicated().any():
    raise ValueError("review_id must be non-empty and unique")
if (frame["text"] == "").any():
    raise ValueError("Handle empty texts first")

docs = frame["text"].tolist()
encoder = SentenceTransformer(
    "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
)
umap_model = UMAP(
    n_neighbors=15, n_components=5, min_dist=0.0,
    metric="cosine", random_state=42
)
cluster_model = HDBSCAN(
    min_cluster_size=10, min_samples=5,
    metric="euclidean", prediction_data=True
)
vectorizer = CountVectorizer(ngram_range=(1, 2))
model = BERTopic(
    embedding_model=encoder,
    umap_model=numap_model,
    hdbscan_model=cluster_model,
    vectorizer_model=vectorizer
)
topics, _ = model.fit_transform(docs)
frame["topic_id"] = topics
frame.to_csv("reviews_with_topics.csv", index=False, encoding="utf-8-sig")
model.get_topic_info().to_csv(
    "topic_summary.csv", index=False, encoding="utf-8-sig"
)
print(frame["topic_id"].value_counts(dropna=False).sort_index())

Run: python group_reviews.py. Before a large export, make sure the environment can load the model and has enough resources. The three demo lines from the previous section are not intended to run with these settings: for a very small dataset, reduce the complexity separately or start with manual review.

The methods fit_transform and get_topic_info are described in the BERTopic API. The expected output files are reviews_with_topics.csv, which links each record to a topic, and topic_summary.csv, which contains the topic summary. After a successful run, verify that each input record has one topic_id, and that the number of rows in the first table matches the input. The absence of a Python error does not yet confirm that the clusters are useful.

Step 5. Name topics from the reviews, not just from the words

Open the summary, then filter the source reviews by the selected topic_id. Read the different wording within the group, including edge-case records. The name "delivery_day_order" may hide a date change, a late courier, or simply thanks for the speed.

The recommended analyst deliverable is a separate table topic_id,business_label,comment. For example, "Delivery date changed" is acceptable only after reading the group; this is an example name, not the result of running the script. Keep the topic’s machine-readable words alongside it so another employee can understand what the name is based on.

If the labels are filled with words like "product," "very," "store," revise the topic representation. In BERTopic CountVectorizer affects the words used to describe groups; changing stop words at this stage is not the same as recalculating embeddings and cluster boundaries. Bigrams in the example make it possible to obtain word combinations. Working with these settings is described in the Vectorizers section.

First, try removing confirmed function words from a consistent list. Do not add the negation "not" mechanically: it can change the meaning of the wording. If the group itself mixes different reasons, a nice label will not fix the problem—review the data, the model, or the clustering.

Step 6. Handle the -1 group and fix common errors

The label -1 indicates outliers, meaning documents that the clustering did not assign to regular topics. These may include short thank-you notes, rare complaints, mixed subjects, and texts with insufficient context. The reason must be determined by reading; a separate label does not define the value of the review.

Keep the original assignments. BERTopic offers reduce_outliers with different strategies, but forcibly reducing the number of outliers changes the distribution and requires a new review. The new assignments can be used to update the topic representations through update_topics; this is a separate action, not an automatic consequence of getting a list of new labels. The sequence is described in the outliers documentation.

Symptom What to check Next action
Almost everything ended up in -1 Short texts, heterogeneity, corpus size, HDBSCAN parameters Read examples; change one factor and compare the group contents
Too many small topics Check whether the model is splitting one subject by wording Review the minimum cluster size; keep the original version
Topics are hard to read, but the reviews within them are related Function words in the description Adjust the topic representation vocabulary
The group is large, but the reasons are different Mixed products, long reviews, excessive merging Split the sample by task or rerun the clustering
After a new run, the topic numbers changed New corpus, environment, and stochastic steps Match the meaning and composition of the groups, not just the numbers

When an hdbscan_model is passed in, the minimum size is set by min_cluster_size of that object: changing only min_topic_size in BERTopic does not reconfigure your HDBSCAN. nr_topics is used to reduce the number of detected topics; it is not a promise to find exactly the specified number of natural reasons. These differences are reflected in the API.

In the executive summary, state the size of the entire selected export, the number of assigned records, and the number of -1 entries. Calculate the share of each topic using a denominator that is explicitly named. If a record contains multiple issues, a single label does not reflect them all: evaluating each aspect will require a separate labeling or text-splitting rule.

How Vladimir Lomtev’s AI Studio helps with review analytics

Vladimir Lomtev’s AI studio focuses on data preparation, AI solution development, and integration. For review analytics, the work may involve three specific actions: preparing a consistent export with stable IDs, integrating the topic summary into the team’s workflow, and setting up group review with employee examples. This process does not assume that every detected topic automatically becomes the cause of a complaint.

The first step is to choose one review source, a time period, the current review method, and a criterion for a useful result: for example, the ability to trace each topic back to the source texts and hand it off to the responsible employee. Discuss the project.

Bottom line: keep the link between topics and the original reviews

A useful output of BERTopic is a table of clear, recurring themes with a link to each original record and a separately visible group -1. Start with a limited, consistently sampled dataset, save the parameters and versions, read through the group contents, and only then use them in product work. Changing the number of clusters by itself does not show that the analysis has improved.

Request an audit

Share your contact details and we will follow up.

← All articles

Comments (0)

Loading comments…

Leave a comment
No registration required

Book a strategy call
for agentic operations

Tell us which workflow you want to improve. We will map feasibility, risks, and the fastest MVP path.

By submitting, you agree to our privacy policy

Contacts

Global Operations

Serving U.S. clients remotely
with private cloud and on-prem options

Strategy calls by request

We respond after reviewing your workflow context.

info@agentsunrise.pro

For partnership inquiries

Have a proposal?

Write to us in messengers

© 2026 AgentSunrise