[Free Script Again] - BlogPro's Keyword Clustering Script - Using Topic Modeling

BlogPro

Elite Member
Jr. Executive VIP
Jr. VIP
Joined
Apr 23, 2012
Messages
2,842
Reaction score
5,850
Hey all,
So when I shared my Bulk Keyword Deduplication/Similarity Check Script - a lot of you ended up asking me for a decent Keyword Clustering Script. Well, here we go!
The Problem
Your spreadsheet is a jungle, your keywords are on a caffeine buzz, and no amount of 'vlookup' sorcery can tame them. Enter - my script - it's like a magical lasso for your keywords, clustering them into topics faster than you can say "Search Engine Optimization"!
Well, we all have access to a plethora of keywords. But they're all over the place. If you start at cell 1 and begin creating pages, by the time you reach cell 20 - you find you're at the first keyword or a variation of it.
Exports from SEMRush, ahrefs or anywhere else suffer the same issue.
These keywords need to be grouped! And the current solutions are either too expensive, or they simply don't work in a nuance manner.
The Magic of the script
The script using topic modeling via BERTopic which uses transformer models and c-TF-IDF - it preprocesses your entry, performs topic modeling etc.
It then does three things -
1. It creates a cluster of your keywords
2. It creates an Excel Spreadsheet with your keywords on the left, and cluster on the right. Each group/cluster is color coded for easy reading.
3. It creates an additional Spreadsheet where it dumps all the Outliers - aka Keywords it couldn't group or cluster.

█████​

Example
I gave it 10,000 keywords - with everybody's favorite topics NFT - On an old Macbook Pro it took 6 minutes to get me 8597 unique keywords, removed 1402 keywords
Original Keywords I gave the script - Check here
Excel File the Script generated with Clustering - Check here
Outliers the Script Generated (Non-Clustered Keywords) - Check here

It grouped Pizza and Papa John's together

Screen-Shot-2023-11-06-at-2-46-07-AM.png


It found investment related How-Tos and got them together

Screen-Shot-2023-11-06-at-2-48-39-AM.png


It found "Start a Project" related How-Tos and put them in a different cluster

Screen-Shot-2023-11-06-at-2-49-46-AM.png


It put Huxley and Evolution in the same group

Screen-Shot-2023-11-06-at-2-50-15-AM.png

█████​

How to use the script?
There are two ways you can use the script. Running it locally on your computer, or via Google Colab - I'll explain both below.

█████​

Option 1 - Running it locally - on your computer
You can download the script through the below link or by clicking here - click the green "Code" button and download as Zip
Step 1: Prepare your keyword list
Create a CSV file containing your list of keywords - Name this file keywords.csv. Each keyword should be on a separate line. No headers.
Step 2: Install the required packages
Make sure you have Python 3.6 or higher installed on your system. Then, install the required packages by running the following command in your terminal or command prompt - please navigate to the directory where the script is present. If you're using something like VSCode things become easier.
Bash:
pip install pandas bertopic openpyxl tqdm
Step 3: Edit the Config file (Optional)
You can edit config.json and adjust parameters - but I'd recommend doing this only if you know what you're doing.
Step 4: Run the script
Open your terminal or command prompt and navigate to the directory where the deduplication.py script is located. Run the script with the following command:
Bash:
python deduplication.py
Step 5: Check the output
Once the script finishes running, it will generate two output files in the same directory
  • clustered_keywords.xlsx - An Excel spreadsheet with color-coded groups of your keywords.
  • outliers.xlsx - An Excel file with keywords, that couldn't be grouped - your outliers, basically.
That's it you're done!

█████​

Option 2 - Running it on Google Colab
1. Open the Google Colab of the file here - Google Colab Link
2. Make sure you're logged in to your Gmail and click the Copy to Drive button (just below the file name at the top) - if you're unable to find it, just click File >> Save a Copy in Drive
If you do it right, a new Window will open with your file's copy from your Google Drive

3. Now, in the top menu, goto Runtime and click on Run All

//

That's it - your script is now ready to take your Keyword file and perform clustering.
Here comes the fun part -

1. Step 1 - This is where it will ask you to upload your keywords.csv - just click on "Choose Files" and upload.

2. Step 2 - Is where you can make edits to the Config file. Although do it only if you know what you're doing.

3. Once that is done, scroll to the very bottom and watch as the script runs its magic, generates the necessary embeddings etc.

4. Once it is done - it will create two files - it will zip them and offer you one single download. :)
  • clustered_keywords.xlsx - An Excel spreadsheet with color-coded groups of your keywords.
  • outliers.xlsx - An Excel file with keywords, that couldn't be grouped - your outliers, basically.
That's it you're done!

█████​

How does it work?
1. Reads CSV Data
The script pulls data from a specified CSV file, where keywords are expected to be delineated. These keywords are then loaded into a Python list for processing.​
2. Keyword Preprocessing
It employs a preprocessing step where each keyword is converted to lowercase and stripped of leading or trailing whitespace to ensure uniformity and improve the quality of the topic modeling.​
3. Topic Modeling with BERTopic
Utilizing the BERTopic library, the script performs topic modeling. This process involves the transformation of preprocessed keywords into topics using unsupervised machine learning, specifically leveraging transformer-based embeddings to understand context and group similar keywords.​
4. Logging
Throughout its operation, the script logs important information and errors. It uses both console and file logging handlers, with a rotating file handler to manage log size and retention.​
5. Configuration Management
The script reads a JSON configuration file at the start, which dictates various parameters such as file paths, minimum cluster size, language for BERTopic, and other operational settings.​
6. Excel Output
Post-clustering, the script generates an Excel Spreadsheet with separate sheets for categorized topics and outliers. The topics are color-coded for visual differentiation, and the workbook is formatted with adjustable column widths for readability.​
The script creates two output files for you:​
  • clustered_keywords.xlsx - An Excel spreadsheet with color-coded groups of your keywords.
  • outliers.xlsx - An Excel file with keywords, that couldn't be grouped - your outliers, basically.
7. Error Handling
Exception handling is integrated to ensure any errors encountered during processing are logged appropriately, providing traceability and aiding in troubleshooting.​

█████

█████

█████

 
I tried everything - I went through various models - I tried integration with GPT. I mean, to give you perspective, it took me 33+ tests to select a clustering method for this script. I finally went with HDBScan.
Initially, I tried using kmeans - along with sklearn. This setup would render a Silhoutte Score - which basically determines the similarity of an object to its own cluster, as against clusters.

This would require training a model, then evaluating it. The results were - well nah!

I then moved on to using Jaccard Index - it would render a Similarity Matrix, then we'd use a clustering algorithm that can work with precomputed Similarity Matrixes and et voila!

Again, it was good, not great!

That's when I decided - "Hey BlogPro - Remember transformer models?" - So we headed back to our trusty old all-MiniLM-L6-v2 - with a combination of HDBScan (after trying various clustering algos). The results improved drastically. The above dataset gave me 200 clusters. But still, all my datasets rendered a lot of outliers and the number of clusters weren't just enough.

But we were getting somewhere. I began adding enhancements. Preprocessing the data. Logging everything. And we were getting there.

I added a progress bar - so you can see how the script is progressing. I ensured the output was seperated. (HDBScan assigns -1 group to all outliers) - so I moved them to a different excel file.

This is when, I decided to go with full-scale topic modelling. And in came, BERTopic. BERTopic is a topic modeling library, which internally uses transformers and HDBSCAN for clustering (which we were already using). It leverages HDBSCAN for clustering embeddings and c-TF-IDF to construct topics in a class-based TF-IDF fashion.

This paved the way to where you are today.

Hope some of you find this useful!

Now go make some money!

Cheers
 
Just quickly imported around 10k keywords to try this bot, but failed to generate the expected csv files.
Here is the screencut:

error1.jpg

Any idea of whats wrong I did for this error?

thanks a lot for this bot, and just one I am looking for.

Cheers
 
Just quickly imported around 10k keywords to try this bot, but failed to generate the expected csv files.
Here is the screencut:

View attachment 296841

Any idea of whats wrong I did for this error?

thanks a lot for this bot, and just one I am looking for.

Cheers

Hey,

Apologies for that. I have fixed the issue. Please make a fresh copy of the colab to your drive and try once more.

Let me know if you run into any issues.

Explanation

seaborn is a python visualisation library that I use. I originally intended to use matplotlib and seaborn to generate cluster maps - but decided against it as I am sure most SEOs won't be reading cluster maps or have any use for it.

So I removed it entirely, but forgot that I was using seaborn for coloring the excel spreadsheets.

It can simply be fixed by adding import seaborn as sns to Step 4 of the colab.

Cheers
 
thanks bro, just got what I wanna.
Great tool! Small but very effective, and when I looked through the grouped kws column,
they are mostly accurate in grouping.
I used many online clustering tools, but this one is much better than those.
I also checked the outlier file, and there are still many keywords I can pick and add to the grouped lists.
but not a big problem for me, and happy with the result.
Thanks so much and I will be using it along with ur Similarity check tool daily base.
 
Amazing, sir!
Thank you so much for the script.
 
I went the similar way and ended up with auto-hyperparameter tuning HDBscan for keyword clustering, w/ and w/o bertopic.
I also added serp data for more accurate clustering!
It works pretty well 90% of the time but it's not perfect, still needs some manual work. But it's 100% usable.

Thanks for sharing this script.

BHW needs gold sharing like this.
 
I used many online clustering tools, but this one is much better than those.

I am so happy to hear this man. Glad I could be of help.

I went the similar way and ended up with auto-hyperparameter tuning HDBscan for keyword clustering, w/ and w/o bertopic.
I also added serp data for more accurate clustering!
It works pretty well 90% of the time but it's not perfect, still needs some manual work. But it's 100% usable.

Thanks for sharing this script.

BHW needs gold sharing like this.

For my internal use, I am integrating SERP data (God my proxy bills are gonna be horrible).

But for clustering - doing that would be a little over-engineering, don't you think?

Using the Similarity Script I shared earlier, one can get rid of similar keywords - following up with this to run clusters and you should have the basis for a pretty strong article.

Thank you for the kind words. I'll do my best to share more.
 
Step 3: Edit the Config file (Optional)
You can edit config.json and adjust parameters - but I'd recommend doing this only if you know what you're doing.

@BlogPro

Do we need to change the language in the config.json file, in case the keywords are not in English, or should we always leave english as default?





Step 4: Run the script
Open your terminal or command prompt and navigate to the directory where the deduplication.py script is located. Run the script with the following command:
Bash:
python deduplication.py

Maybe you meant cluster.py instead deduplication.py :)



Many thanks!!!



 
@BlogPro

Do we need to change the language in the config.json file, in case the keywords are not in English, or should we always leave english as default?

Depends on the core language of your keywords.

So let's say if you were looking at Spanish keywords, you'd use Spanish there.

But if you're running it for an English site and suspect that there might be some Spanish keywords - you can keep it at English.

Maybe you meant cluster.py instead deduplication.py :)



Many thanks!!!

Oh yes - it should be cluster.py

I copied some info from my previous thread for formatting and forgot to edit.

Good catch, I'll ask a moderator if they can edit it.
 
@BlogPro Thanks a lot for taking the time not only to build and offer the script for free but to run tests and actually offer something that is worth bookmarking.

If I may share a couple of insights:
  • The label for the keyword cluster group is a number? - Can it be a phrase relevant to the cluster?
  • Have you tried building a keyword clustering tool connecting it to the GSC API?
    • This would be helpful to map out the content on a site and even with internal linking
  • Have you tried building a keyword clustering tool based on what´s already ranking for that keyword?
    • I know this would require a SERP API but there are many out there that are really affordable
Again, thanks again for taking the time to build, test, and offer it for free!
 
But for clustering - doing that would be a little over-engineering, don't you think?
That's mostly the case. I feel it's a bit of over-engineering as well, as you say. The completed setup does not deliver significantly better results.
I think it depends on the niche. If it can cluster the keywords well with only embedding, then no need for serp data.
For instance, one of my testing keyword group happens to have a lot of keywords that are polysemous, so I have to rely on serp data for more context when embedding. For example, apple being the fruit apple and the company apple. I need the serps to cluster the keywords into the right group.

But most of the time, sbert, bertopic and hdbscan can get the job done perfectly.
 
@BlogPro Thanks a lot for taking the time not only to build and offer the script for free but to run tests and actually offer something that is worth bookmarking.

Of course! Happy to help :)

If I may share a couple of insights:
  • The label for the keyword cluster group is a number? - Can it be a phrase relevant to the cluster?

Yes, for now we're using basic HDBScan grouping - which relies on numbers.

I believe extracting context for each group shouldn't be a big deal.

Let me see what I can do.


  • Have you tried building a keyword clustering tool connecting it to the GSC API?
    • This would be helpful to map out the content on a site and even with internal linking

  • Have you tried building a keyword clustering tool based on what´s already ranking for that keyword?
    • I know this would require a SERP API but there are many out there that are really affordable

Can I bother you to elaborate on the above two a little bit?

If it is something possible, I'd be happy to write an integration.

I created a small dashboard to extract data from GSC API for all my sites (So I don't have to log in to a million Google Accounts) - so am familiar with that.
 
Nice share.
Does the script run via Terminal on Mac?
 
I don't know what is a CLI element - but I'd appreciate if the script could run as well on Mac Terminal

Ahh!

CLI = Command Line Interface

A set of functions, that let the script run via the command line (CMD in Windows, Terminal in Mac)

I'll include this in the script, that's not a big deal.

Currently figuring out context extraction, so groups can be named, rather than numbered - as @Roger Marquez requested.
 
Back
Top