Scale Your SEO Keyword Clustering: Free Python Script for 10,000+ Keywords
Here’s what most SEO guides won’t tell you: keyword clustering is not a magic bullet, and for many websites, it’s complete overkill.
I’ve seen businesses spend weeks perfecting their keyword clusters using sophisticated NLP models, only to realize they could have ranked faster by publishing three solid articles based on manual keyword grouping. The dirty secret of SEO automation is that complexity often masquerades as sophistication.
But here’s the thing—at scale, semantic keyword clustering becomes indispensable. If you’re managing enterprise sites, multiple clients, or building topical authority across hundreds of topics, the right clustering approach can compress months of keyword research into days.
This guide provides a free Python script for semantic keyword clustering using deep learning models, but more importantly, it gives you the critical framework to decide when clustering is worth your time and how to validate that your clusters actually improve your SEO outcomes—not just organize your spreadsheets.
What Is Semantic Keyword Clustering
Standard definition: Semantic keyword clustering groups related keywords based on meaning and search intent rather than exact-match patterns.
The reality: Semantic clustering uses natural language processing models to identify conceptual relationships between keywords that traditional pattern-matching algorithms miss—like understanding that “bicycle” and “bike” are synonymous, or that “thermal gloves,” “heated gloves,” and “warm gloves” serve similar user needs.
Here’s what most articles gloss over: semantic similarity doesn’t equal strategic similarity.
The phrases “cheap divorce lawyer” and “best divorce lawyer” might cluster together semantically, but they represent completely different search intents, buyer stages, and monetization strategies. A pure semantic approach will group them; a strategic SEO approach might separate them.
This is why you need both algorithmic clustering AND human judgment.
When Keyword Clustering Actually Matters
Use Automated Clustering When:
You’re managing 1,000+ keywords across multiple topics where manual review becomes impossible. Enterprise sites, large e-commerce catalogs, and content agencies hit this threshold quickly.
You need to identify content consolidation opportunities across existing pages. If you have keyword cannibalization issues, clustering reveals which pages are competing for the same semantic space.
You’re building topical authority systematically and need to map keyword relationships to ensure comprehensive coverage without redundancy.
You’re running large-scale paid search campaigns where grouping thousands of keywords into semantic ad groups can improve Quality Scores and reduce cost-per-click. According to WordStream research, proper ad group structure can improve click-through rates by up to 28%.
You need multilingual keyword research where manual grouping becomes exponentially more difficult across languages you don’t speak fluently.
Skip Clustering When:
You’re working with under 200 keywords for a focused niche site. Manual grouping with a spreadsheet is faster and gives you better strategic insights.
Your keywords span wildly different intents that require human judgment (informational vs. transactional, brand vs. generic, top-funnel vs. bottom-funnel).
You’re just starting out and don’t have content ranking yet. Focus on publishing quality content first, optimize your clustering process later.
You don’t have a clear implementation plan for what you’ll do with the clusters. Organization without action is procrastination.
Why This Approach Beats Older Methods
Early keyword clustering tools relied on TF-IDF (Term Frequency-Inverse Document Frequency) matching, which groups keywords based on shared letter patterns and word frequency rather than actual meaning. This created bizarre clusters like grouping “bank account” with “bank river” because they share the word “bank.”
The breakthrough came with transformer-based language models trained on billions of text samples, which understand context and semantic relationships. These models, developed between 2018-2022 with continued improvements through 2025, can recognize that:
- “Dachshund sweater” and “dog sweater” are related
- “Xmas gifts” and “Christmas presents” are synonymous
- “Wholesale socks” and “bulk socks” serve the same search intent
The script shared here uses sentence transformers, which convert keywords into numerical vectors (embeddings) that capture semantic meaning. Keywords with similar meanings have vectors positioned closely in multi-dimensional space, making them mathematically clusterable.
What’s changed since 2022: The emergence of GPT-4 and newer models means even more sophisticated clustering is possible, but as Search Engine Journal reports, the balance between accuracy and computational cost matters more than pure performance for most SEO use cases.
How the Free Semantic Clustering Script Works
This Python script uses the Fast Clustering algorithm combined with pre-trained language models to group your keywords. Here’s what happens under the hood:
Step 1: Encoding – Each keyword is transformed into a 384-dimensional numerical vector that represents its semantic meaning. Similar concepts produce similar vectors.
Step 2: Similarity Calculation – The script measures the distance between all keyword vectors to identify which are semantically closest.
Step 3: Clustering – Keywords exceeding a similarity threshold (default: 85% match) are grouped together. The shortest keyword in each group becomes the cluster name.
Step 4: Output – Your original CSV file gets a new “Cluster Name” column showing which keywords belong together.
The default model all-MiniLM-L6-v2 balances speed and accuracy, processing thousands of keywords in minutes rather than hours. For reference, it can handle approximately 50,000 keywords before hitting memory limits in Google Colab’s free tier.
Step-by-Step: Using the Keyword Clustering Script
Prerequisites
- A Google account (for Google Colaboratory)
- A CSV file with a column named “Keyword”
- Basic familiarity with uploading files (that’s it—no coding required)
The Process (Simplified)
1. Access the Script
Open the Google Colab sheet (Note: The original article mentions a specific shared link—use the GitHub link provided by the author Lee Foot)
Click “Open in Colab” when prompted.
2. Configure Computing Resources
Navigate to Runtime > Change Runtime Type
Select GPU from the hardware accelerator dropdown
Why? GPU processing accelerates the semantic calculations by 10-50x compared to CPU processing.
3. Run the Script
Click Runtime > Run All (or press Ctrl+F9)
The script will execute all code cells automatically
4. Upload Your Keyword File
When prompted, upload your CSV file containing keywords
The script auto-detects CSV formatting and character encoding (works with exports from Ahrefs, SEMrush, Google Search Console, Google Ads)
5. Wait for Processing
Processing time varies by dataset size:
- 1,000 keywords: ~1-2 minutes
- 10,000 keywords: ~5-10 minutes
- 50,000 keywords: ~15-30 minutes
6. Download Results
The script automatically generates a new CSV file with “clustered” appended to the filename
Find your file in the left sidebar under the Files icon
The new “Cluster Name” column shows how keywords were grouped
What Your Output Looks Like
The script assigns cluster names using the shortest keyword in each group. For example:
Cluster: “bike helmet”
- bike helmet
- bicycle helmet
- cycling helmet
- helmets for biking
- bicycle safety helmet
This naming convention makes it easy to scan and identify topic themes quickly.
Tuning Cluster Accuracy vs. Coverage
Here’s where strategy meets execution. Two variables control your clustering quality:
cluster_accuracy (Default: 85)
Higher values (90-95): Creates tighter, more precise clusters with keywords that are extremely similar.
- Pros: Higher confidence that clustered keywords truly belong together
- Cons: More keywords marked as “no cluster” (orphaned)
Lower values (70-80): Creates broader clusters that capture more keywords.
- Pros: Fewer orphaned keywords, more comprehensive grouping
- Cons: Some clusters may include tangentially related keywords
My recommendation: Start at 85, then manually review a sample of 20-30 clusters. If you see too many poor groupings, increase to 90. If you have too many orphaned keywords (>30%), lower to 80.
min_cluster_size (Default: 2)
Sets the minimum number of keywords required to form a cluster.
Setting this to 3-5 is useful when you want to identify major topic opportunities and ignore niche variations.
Keeping it at 2 captures more granular relationships, useful for comprehensive content planning.
What Most People Get Wrong About Automated Clustering
Mistake #1: Trusting Clusters Without Manual Validation
The problem: Pre-trained language models weren’t specifically trained for SEO search intent. They might cluster “running shoes review” with “buy running shoes online” because they’re semantically similar—but these represent different funnel stages requiring different content types.
The solution: Always manually review at least 10% of your clusters, prioritizing high-volume keyword groups. Look for:
- Mixed search intents (informational + transactional)
- Different product categories that share terminology
- Branded vs. non-branded mixing
Mistake #2: Ignoring Commercial Intent Signals
The reality: Words like “buy,” “cheap,” “best,” “review,” and “near me” completely change keyword strategy, even if the core topic is semantically similar.
Better approach: Pre-filter your keywords by intent category BEFORE clustering. Run separate clusters for:
- Informational keywords (how-to, what is, why)
- Commercial investigation (best, top, review, vs)
- Transactional (buy, price, discount, order)
- Local (near me, in [city])
Mistake #3: Clustering Without a Content Plan
I’ve seen teams cluster 20,000 keywords beautifully, then stare at the spreadsheet wondering “now what?”
Strategic questions to answer BEFORE clustering:
- How many articles can we realistically publish this quarter?
- Are we creating new content, optimizing existing pages, or consolidating?
- What’s our topical authority goal—depth or breadth?
- How will we prioritize which clusters to target first?
Mistake #4: Assuming Semantic Clustering Equals Content Quality
Harsh truth: Perfect keyword organization doesn’t rank pages. Excellent content that satisfies search intent does.
Clustering is a research tool, not a ranking strategy. Your clusters identify topics and relationships; your content creation, on-page SEO, and backlink strategy do the actual ranking work.
Advanced Customization: Swapping Language Models
The default all-MiniLM-L6-v2 model works well for English and provides good speed-to-accuracy balance. But you might want alternatives:
For Better Multilingual Support
Replace with paraphrase-multilingual-MiniLM-L12-v2
Supports 50+ languages with more accurate cross-language semantic understanding
Trade-off: Slightly slower processing
For Maximum Accuracy (English)
Switch to all-mpnet-base-v2
Highest quality semantic representations from the Sentence Transformers library
Trade-off: 2-3x slower processing time
How to Actually Use Your Clusters: Strategic Applications
Application #1: Content Hub Architecture
The strategy: Use clusters to design comprehensive content hubs that establish topical authority.
Implementation:
- Identify your 5 largest clusters (by search volume)
- Create pillar pages targeting the cluster name keyword
- Build supporting articles for each keyword in the cluster
- Implement internal linking from supports → pillar
Real example: A cluster around “remote work tools” might include 47 keywords. Your pillar page covers “Best Remote Work Tools [2026 Guide]” comprehensively. Supporting articles dive deep into specific tools, collaboration categories, or use cases—all linking back to the pillar.
Application #2: Intelligent Content Consolidation
The problem: Google’s Helpful Content Update penalizes thin, redundant content.
The solution: Use clustering to identify multiple weak pages targeting the same semantic space.
Process:
- Export your existing ranking keywords from Search Console
- Run them through the clustering script
- Look for clusters where you have 3+ different URLs ranking
- Consolidate those pages into one comprehensive article
- Implement 301 redirects from old URLs
According to Ahrefs’ study on content consolidation, this can increase organic traffic by 20-30% for affected topics.
Application #3: FAQ Schema Generation
Cluster your question-based keywords to build comprehensive FAQ sections optimized for featured snippets.
Process:
- Filter keywords containing: what, why, how, when, where, can, does, is, are
- Run clustering on question keywords only
- Each cluster represents an FAQ opportunity
- Write concise answers (40-60 words) optimized for voice search
- Implement FAQ schema markup
Why this matters: According to BrightEdge, featured snippets receive 35% of all clicks for question-based queries.
Application #4: Paid Search Campaign Structure
Google Ads best practice: Single Keyword Ad Groups (SKAGs) or semantic theme groups improve Quality Score and ad relevance.
Using clusters:
- Export your target keywords for PPC campaigns
- Cluster them semantically
- Create ad groups based on clusters
- Write specific ad copy for each cluster’s semantic theme
- Direct each cluster to optimized landing pages
Bonus: Identify negative keyword opportunities by reviewing “no cluster” results—often these are irrelevant queries you should exclude.
Troubleshooting Common Issues
“CUDA Out of Memory” Error
Cause: You’re clustering too many keywords simultaneously (over ~50,000 with default settings)
Solutions:
- Split your dataset into multiple files of 30,000 keywords each
- Use a smaller/faster model like all-MiniLM-L6-v2
- Reduce batch size in the script (requires code editing)
- Upgrade to Google Colab Pro for more GPU memory
Too Many “No Cluster” Results (>40%)
Cause: Your dataset contains highly diverse keywords, or your accuracy threshold is too strict
Solutions:
- Lower cluster_accuracy from 85 to 75-80
- Reduce min_cluster_size from 2 to 2 (if you increased it)
- Pre-filter your keywords by topic before clustering
- Accept that some keywords are genuinely unique
Poor Quality Clusters
Cause: Accuracy threshold is too low, or keywords are ambiguous
Solutions:
- Increase cluster_accuracy to 90-95
- Manually split problematic clusters
- Add intent modifiers (buy, how, best) to disambiguate keywords before clustering
- Use a higher-quality model like all-mpnet-base-v2
Script Won’t Accept My CSV File
Cause: Column naming or encoding issues
Solutions:
- Ensure you have a column named exactly “Keyword” (case-sensitive)
- Save your CSV with UTF-8 encoding
- Remove special characters from column headers
- Try exporting from your tool again with standard settings
Free Script vs. Paid Tools
When the Free Script Wins:
- Budget constraints: Obviously, free is unbeatable
- Large datasets: Many paid tools charge per keyword or have limits
- Customization: You can modify the code for specific use cases
- Privacy: Your keyword data stays in your Google account
- Learning: Understanding the process makes you a better SEO
When Paid Tools Are Worth It:
MarketMuse, Clearscope, Surfer SEO: These don’t just cluster—they provide content briefs, competitor analysis, and optimization recommendations. The clustering is one component of comprehensive topic research.
Ahrefs/SEMrush built-in clustering: If you already subscribe, these integrate directly with your existing workflow, include search volume data, and offer intent classification.
Agency-level work: Paid tools provide client-friendly reports, team collaboration features, and support that free scripts can’t match.
My recommendation: Start with the free script to understand clustering deeply. Once you’re clustering regularly and the time investment justifies it, evaluate paid tools based on your specific workflow needs.
Data Privacy and Security Considerations
The elephant in the room: You’re uploading potentially sensitive keyword data to Google’s servers.
For Most Users:
This is fine. Google Colab sessions are private by default, and files are deleted after your session ends (typically 12 hours of inactivity).
For Client Work or Sensitive Projects:
Better practices:
- Remove brand names from keywords before uploading
- Use generic terminology where possible
- Run the script locally on your machine (requires Python environment setup)
- Use anonymous/aggregated keyword lists for testing
- Review Google Colab’s privacy terms
Enterprise consideration: Some SEO agencies run this script on internal servers using Docker containers to ensure complete data control.
The Clustering Quality Audit
Don’t just accept the script’s output blindly. Here’s your validation checklist:
Random Sample Review (15 minutes)
- Sort clusters by keyword count (descending)
- Review the 10 largest clusters manually
- Check 10 random mid-size clusters
- Look at 5 small clusters (2-3 keywords)
Quality check: Do keywords in each cluster share the same search intent and target topic?
Intent Consistency Check (20 minutes)
- Identify clusters mixing question keywords with commercial keywords
- Flag clusters combining brand names with generic terms
- Note clusters mixing local intent with national/global keywords
Action: Manually split these clusters or adjust your accuracy settings and re-run.
Competitive Validation (30 minutes)
- Pick 5 important clusters
- Google the cluster name (main keyword)
- Analyze top 10 results: Do they cover all keywords in your cluster?
Insight: If top-ranking pages address all keywords in your cluster on a single page, your clustering is validated. If they don’t, you might have overclustered.
Search Volume Distribution (15 minutes)
If you have search volume data:
- Check if your clusters contain one high-volume keyword with many low-volume variations (good)
- Or multiple medium-volume keywords with different intents (potentially problematic)
Action: High-volume + variations = target with one comprehensive page. Multiple medium-volume = might need separate content pieces.
The Future of Keyword Clustering in an AI Search World
The SGE/AI Overview Challenge
Google’s Search Generative Experience fundamentally changes how users interact with search results. AI overviews answer questions directly, reducing clicks to websites.
What this means for clustering:
- Focus shifts to conversational queries: Cluster longer, natural language phrases that AI overviews might source
- Answer comprehensiveness matters more: Clusters should identify all sub-questions around a topic
- Citation-worthiness is key: Create content so authoritative that AI models cite you
GPT-4 and Beyond for Clustering
Newer models like GPT-4 (2023) and Claude (2024-2025) understand context better but are:
- More expensive to run at scale
- Slower for batch processing
- Overkill for basic semantic similarity
Prediction: By 2027, we’ll see hybrid approaches that use lightweight models for initial clustering and large language models for intent classification and cluster validation.
The Intent Classification Layer
Next evolution: Clustering tools that automatically categorize keywords by:
- Search intent (informational, commercial, transactional, navigational)
- Funnel stage (awareness, consideration, decision)
- Content format (article, video, tool, product page)
Some enterprise SEO tools are already adding this, but expect it to become standard by 2026-2027.
The Uncomfortable Questions You Should Ask
Before you cluster your next 10,000 keywords, consider:
Is keyword volume even the right metric anymore? With AI overviews reducing click-through rates, should you prioritize keywords more likely to generate clicks rather than just volume?
Are you clustering to avoid the real work? Sometimes perfect organization is a form of procrastination. Could you rank for 20% of these keywords by just publishing quality content now?
Will your content actually be better? Clustering identifies relationships, but does your content creation process utilize those relationships effectively?
Are you ignoring user signals? Keywords represent demand, but analytics data (bounce rate, time on page, conversion rate) tells you what actually works. Are you clustering based on reality or assumptions?
Frequently Asked Questions
How often should I recluster my keywords?
Quarterly for active sites, or after major keyword research expansions. Search language evolves slowly—most clusters remain stable for 6-12 months.
Can I cluster keywords from different topics together?
You can, but shouldn’t. Clustering works best when keywords share topical relevance. Cluster “dog products” separately from “cat products” even though both are pet-related.
What’s the minimum dataset size worth clustering?
Around 500+ keywords. Below that, manual grouping in a spreadsheet is faster and more strategic.
Does this script work for local SEO keywords?
Yes, but be aware it might cluster “[service] in [city]” variations together even though you need separate location pages. Pre-filter by location for better results.
Can I use this for non-English languages?
Absolutely. The script supports 100+ languages, though accuracy varies. For best results with languages like Chinese, Japanese, or Arabic, consider using language-specific models from Hugging Face.
How do I prevent keyword cannibalization using clusters?
Create one primary target page per cluster. If you publish multiple pages, ensure they target different clusters and use distinct angles/intents.
Will clustering improve my rankings directly?
No. Clustering improves your content strategy, which leads to better rankings over time. It’s a research tool, not a ranking factor.
Can I cluster branded vs. non-branded keywords together?
Technically yes, but strategically no. Always separate branded keywords first—they require different content strategies and often target existing customers rather than new acquisition.
What to Do After Reading This
If you’re new to keyword clustering:
Start small. Pick one topic category (50-200 keywords), run the script, manually review results, and create content based on one cluster to test the workflow.
If you’re experienced with clustering:
Audit your current clustering approach. Are you validating clusters? Have you measured whether your clustered content strategy actually improved rankings? Consider adding intent classification to your process.
If you’re at enterprise scale:
Evaluate whether this free approach scales with your needs, or if investing in paid tools with API access, collaboration features, and automated workflows provides better ROI.
Clustering Is a Means, Not an End
Semantic keyword clustering using deep learning NLP is genuinely powerful. It reveals relationships that manual analysis would miss and enables content planning at scale that’s simply impossible otherwise.
But here’s what matters more than your clustering methodology: Do you have the content production capacity and SEO execution skill to capitalize on your research?
The graveyard of SEO is filled with beautifully clustered keyword spreadsheets that never became actual content. Don’t let perfect clustering prevent you from publishing good content.
Use this script as one tool in your SEO toolkit. Validate its output. Apply strategic thinking. Test your assumptions. Measure your results.
And remember: the best keyword cluster is the one that leads to content that ranks, converts, and helps real people solve real problems.
Ready to start clustering? Access the script on GitHub (use the original author’s link) and begin with a small test dataset. Report back with your biggest “aha moment” when you see semantic relationships you would have missed manually.
What will you do with your clusters that your competitors won’t?


