Sub topic 2
Finding Themes in Unlabelled Reviews
Assume you know basic Python, JSON, and precision and recall. This chapter focuses on reviews without pre-existing labels.
Discover themes with clustering
Theme discovery groups similar reviews before you know the categories. TF-IDF represents each document as numbers based on how important each word is. K-means then groups nearby vectors. Read the strongest terms in each cluster and give the cluster a human name.
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
reviews = [
"Delivery was late and the box was damaged",
"Package arrived two days late",
"Courier left the parcel damaged and late",
"Great battery life and bright screen",
"The screen is bright and the battery lasts all day",
"Battery lasts two days and the screen looks great",
]
vectorizer = TfidfVectorizer(stop_words="english")
matrix = vectorizer.fit_transform(reviews)
model = KMeans(n_clusters=2, n_init=10, random_state=0)
model.fit(matrix)
terms = vectorizer.get_feature_names_out()
for cluster_id, center in enumerate(model.cluster_centers_):
indexes = center.argsort()[::-1][:3]
print(cluster_id, [terms[i] for i in indexes])An embedding is a vector that represents meaning rather than only word frequency. Embedding-based clustering can group “parcel arrived late” with “delivery took too long,” even though the words differ. Test several cluster counts and inspect sample reviews. A cluster is useful only if a person can explain it.
Extract structured labels with an LLM
After discovering recurring themes, define a fixed taxonomy, such as delivery, pricing, support, and product_quality. Ask the language model to return JSON containing a sentiment, a list of allowed themes, and an exact evidence quote.
Validate every response in code. Reject unknown labels, malformed JSON, and evidence that does not occur in the source review. Treat review text as data, not as instructions.
Aspect-based sentiment
Overall sentiment can hide useful detail. Aspect-based sentiment records both the feature and the opinion about it:
delivery: negativebattery: positiveprice: neutral
A single review may contain several aspects with conflicting sentiment. Store each result with the original review ID and the quoted evidence.
Summarise with traceability
Summarise groups of reviews only after labels and evidence are stored. Each summary claim should point to review IDs, for example: “Delivery complaints increased from 12% to 19% (reviews R14, R22, R31).” Keep the calculation separate from generated prose. Recheck claims against the source records before publishing.
Exercise
Why should a theme summary include review IDs or exact quotes?
Show answer
They let a reviewer verify the claim and detect incorrect or invented conclusions.