Clustering hundreds of text-based answers to draw out key themes without using large language models (LLMs) is a classic task in traditional NLP. The goal is to use unsupervised learning and other lightweight NLP techniques to group semantically similar responses and reveal dominant topics or themes. Below is a structured approach:
✅ Step-by-Step Workflow
1. Text Preprocessing
Clean and normalize the text data to prepare it for analysis.
- Lowercasing
- Removing punctuation, special characters
- Tokenization
- Stopword removal
- (Optional): Lemmatization or stemming
Tools: nltk, spaCy, re
Example:
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re
def preprocess(text):
text = text.lower()
text = re.sub(r'[^a-z\s]', '', text)
tokens = text.split()
tokens = [t for t in tokens if t not in stopwords.words('english')]
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(t) for t in tokens]
return ' '.join(tokens)
2. Text Vectorization
Convert text into numerical representations suitable for clustering.
Option 1: TF-IDF Vectorizer (preferred for short to medium-length texts)
- Captures importance of terms across the corpus.
- Removes common terms and emphasizes distinct ones.
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(max_df=0.9, min_df=2, ngram_range=(1,2))
X = vectorizer.fit_transform(preprocessed_texts)
Alternative Option: CountVectorizer or Word Embeddings (like Word2Vec average) if appropriate.
3. Dimensionality Reduction (Optional but Recommended)
- Often text vectors are high-dimensional and sparse.
- Use for better clustering and visualization.
Options:
- TruncatedSVD (for sparse TF-IDF matrices)
- PCA (for dense vectors)
- UMAP or t-SNE for visualization (not for clustering itself)
from sklearn.decomposition import TruncatedSVD
svd = TruncatedSVD(n_components=50)
X_reduced = svd.fit_transform(X)
4. Clustering Algorithms
Choose an unsupervised clustering method:
🔹 KMeans (Most Common)
- Assumes spherical clusters.
- Requires choosing number of clusters
k.
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=5, random_state=42)
labels = kmeans.fit_predict(X_reduced)
🔍 Use Elbow Method or Silhouette Score to determine optimal k.
🔹 DBSCAN
- Density-based; no need to pre-define number of clusters.
- Good for identifying noise/outliers.
- Works better after dimensionality reduction.
🔹 Agglomerative Clustering
- Good when clusters have hierarchical structure.
- Can visualize with a dendrogram.
5. Interpret Clusters / Extract Themes
For each cluster:
- Look at most frequent words or TF-IDF terms.
- Use
vectorizer.inverse_transform() to get keywords per cluster.
- Manually label based on summary terms.
import numpy as np
def get_top_terms_per_cluster(tfidf_matrix, labels, vectorizer, n_terms=10):
top_terms = {}
for cluster in np.unique(labels):
idxs = np.where(labels == cluster)
cluster_tfidf = tfidf_matrix[idxs].mean(axis=0)
terms = np.array(vectorizer.get_feature_names_out())
top_indices = np.argsort(cluster_tfidf.toarray()[0])[::-1][:n_terms]
top_terms[cluster] = terms[top_indices]
return top_terms
6. Visualize Results (Optional but Useful)
- Scatter plots of reduced data colored by cluster.
- Word clouds per cluster.
Tools: matplotlib, seaborn, wordcloud
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
tsne = TSNE(n_components=2, perplexity=30)
X_2d = tsne.fit_transform(X_reduced)
plt.scatter(X_2d[:,0], X_2d[:,1], c=labels, cmap='tab10')
plt.title("Text Clusters")
plt.show()
✅ Summary: Techniques & Tools
| Task | Tool | Method |
|---|
| Preprocessing | nltk, spaCy | Normalize, tokenize, lemmatize |
| Vectorization | TfidfVectorizer | TF-IDF weighting |
| Dimensionality Reduction | TruncatedSVD, UMAP | Reduce vector space |
| Clustering | KMeans, DBSCAN, AgglomerativeClustering | Unsupervised clustering |
| Theme Extraction | N-gram frequency, TF-IDF terms | Keywords per cluster |
| Visualization | matplotlib, seaborn | Cluster plots, word clouds |
✅ Example Use Case Result:
| Cluster | Top Terms | Inferred Theme |
|---|
| 0 | price, value, cost, affordable | Pricing concerns |
| 1 | support, helpful, staff | Customer service feedback |
| 2 | interface, easy, navigate | UI/UX experience |
🧠 Looking to automate theme naming based on keywords? This is where basic ontologies or keyword-matching heuristics can help assign themes — or an analyst can manually label them.
Let me know if you want a ready-made Python script or notebook to implement this!