Machine Learning 📂 Unsupervised Learning · 3 of 3 202 min read

Hierarchical Clustering

Master hierarchical clustering from first principles. Learn agglomerative & divisive methods, linkage criteria, dendrograms, distance metrics, and apply everything to two fully-solved real- world case studies with Python code.

🌐
SectionSection第 01 节

The Story That Explains Hierarchical Clusteringवह कहानी जो Hierarchical Clustering समझाती है一个讲清层次聚类的故事

The Librarian's BookshelfLibrarian की Bookshelf图书管理员的书架
Imagine a librarian walks into a room with 500 loose books on the floor. She has no catalogue and no genre labels — just the books.

She picks up the two books that feel most similar (same subject, same author) and puts them together. Then she looks again, finds the next closest pair (or a book closest to an existing pile), and merges them. She keeps going — always merging the two closest piles — until everything is in one big pile.

At any moment she could stop and say: "These groups make sense for my library." The full history of every merge is drawn as a branching diagram called a dendrogram.

That is Hierarchical Clustering: it builds a complete tree of merges, so you can cut the tree at any level and get any number of clusters — without choosing K in advance.
कल्पना करें कि एक librarian एक कमरे में आती है जहाँ फ़र्श पर 500 किताबें बिखरी हैं। न catalogue है, न genre labels — सिर्फ़ किताबें।

वह वे दो किताबें उठाती है जो सबसे ज़्यादा मिलती-जुलती लगती हैं (एक ही विषय, एक ही लेखक) और उन्हें साथ रख देती है। फिर दोबारा देखती है, अगला सबसे पास का जोड़ा (या किसी ढेर के सबसे पास वाली किताब) खोजती है, और उन्हें मिला देती है। वह यही करती रहती है — हमेशा दो सबसे पास वाले ढेर मिलाती है — जब तक सब एक बड़े ढेर में न आ जाए।

किसी भी पल वह रुककर कह सकती है: "ये groups मेरी library के लिए सही हैं।" हर merge का पूरा इतिहास एक शाखाओं वाले चित्र में बनता है, जिसे dendrogram कहते हैं।

यही Hierarchical Clustering है: यह merges का पूरा पेड़ बनाता है, ताकि आप पेड़ को किसी भी स्तर पर काटकर जितने चाहें उतने clusters पा सकें — पहले से K चुने बिना।
想象一位图书管理员走进一个房间,地上散落着 500 本书。没有目录,没有类别标签 —— 只有书本身。

她拿起两本感觉最相似的书(同一主题、同一作者),把它们放在一起。然后再看一遍,找出下一对最接近的书(或离某个书堆最近的一本),把它们合并。 她一直这样做 —— 每次都合并最接近的两堆 —— 直到所有书都在一大堆里。

任何时刻她都可以停下来说:“这些分组对我的图书馆来说很合理。”每一次合并的完整历史被画成一张分叉图,叫作树状图(dendrogram)。

这就是层次聚类(Hierarchical Clustering):它构建一棵完整的合并树,你可以在任何高度切开这棵树,得到任意数量的簇 —— 无需事先指定 K。

Hierarchical clustering is one of the oldest and easiest-to-explain clustering methods in unsupervised machine learning. Unlike K-Means — where you must choose the number of clusters before you begin — hierarchical clustering builds a full nested structure of groups and lets you choose the level of detail after you have seen the data.

Hierarchical clustering, unsupervised machine learning के सबसे पुराने और समझाने में सबसे आसान clustering तरीकों में से एक है। K-Means के उलट — जहाँ शुरू करने से पहले clusters की संख्या चुननी पड़ती है — hierarchical clustering groups का पूरा nested ढाँचा बनाता है और data देखने के बाद detail का स्तर चुनने देता है।

层次聚类是无监督机器学习中最古老、也最容易解释的聚类方法之一。与 K-Means 不同 —— K-Means 必须在开始前确定簇的个数 —— 层次聚类会构建一个完整的嵌套分组结构,让你在看过数据之后再决定要多细的分组。

💡
Why "Hierarchical"?"Hierarchical" क्यों?为什么叫“层次”?

The result is not a flat split (like K-Means) but a tree of nested clusters. Every cluster at a higher level contains all the points of the clusters below it. This tree is called a dendrogram, and it is the signature output of the method.

नतीजा एक सपाट बँटवारा (K-Means जैसा) नहीं, बल्कि nested clusters का पेड़ होता है। ऊपर के स्तर का हर cluster अपने नीचे के clusters के सभी points रखता है। इस पेड़ को dendrogram कहते हैं, और यही इस तरीके की पहचान है।

结果不是像 K-Means 那样的平铺划分,而是一棵嵌套簇的树。较高层的每个簇都包含其下方各簇的全部点。 这棵树叫作树状图(dendrogram),是这种方法的标志性输出。


SectionSection第 02 节

Hierarchical Clustering in Pictures — Understand It Before the Mathsतस्वीरों में Hierarchical Clustering — गणित से पहले समझें图解层次聚类 — 先看懂,再学公式

Six words are enough to read every dendrogram on this page. Learn them from the pictures first.

इस page का हर dendrogram पढ़ने के लिए छह शब्द काफ़ी हैं। पहले इन्हें तस्वीरों से सीखें।

读懂本页所有树状图,只需要六个词。先通过图片学会它们。

🖼️ PICTURE DICTIONARY — SIX WORDSतस्वीरों वाला शब्दकोश — छह शब्द图片词典 — 六个关键词
Hierarchical clustering picture dictionary LEAFLEAF叶子(leaf) one data point at the bottomनीचे एक data point底部的一个数据点 MERGEMERGE合并(merge) two groups join into oneदो groups मिलकर एक两组合并为一组 HEIGHTHEIGHT高度(height) close far h how far apart they wereवे कितने दूर थे合并时它们相距多远 CUTCUT切割(cut) K = 3 a line across = choose Kआड़ी line = K चुनें横切一刀 = 选定 K LINKAGELINKAGE连接方式(linkage) min?max? rule for group-to-group distancegroup से group दूरी का नियम组与组之间距离的规则 DENDROGRAMDENDROGRAM树状图(dendrogram) the full family tree of mergesmerges का पूरा family tree全部合并过程的家谱

Everyday trees you already knowरोज़ के पेड़ जिन्हें आप पहले से जानते हैं你早已熟悉的日常“树”

Everyday thingरोज़ की चीज़日常事物How it is like hierarchical clusteringयह hierarchical clustering जैसा कैसे है它与层次聚类的相似之处
🌳 Family tree🌳 Family tree🌳 家谱Siblings join first (very similar), then cousins, then the whole family. The height of a join = how distant the relatives are.पहले भाई-बहन जुड़ते हैं (बहुत मिलते-जुलते), फिर cousins, फिर पूरा परिवार। जोड़ की ऊँचाई = रिश्तेदार कितने दूर हैं।先是兄弟姐妹(非常相似),再是堂表亲,最后是整个家族。连接的高度 = 亲戚关系有多远。
🏆 Sports tournament bracket🏆 Sports tournament bracket🏆 体育比赛对阵表Read it backwards: pairs join round by round until one champion "cluster" is left.इसे उल्टा पढ़ें: जोड़े round-दर-round मिलते जाते हैं जब तक एक champion "cluster" न बचे।倒过来看:每一轮两两合并,直到只剩一个冠军“簇”。
📁 Folders on your computer📁 Computer के folders📁 电脑里的文件夹Files inside sub-folders inside folders: nested groups. You choose how deep to look.Folders के अंदर sub-folders के अंदर files: nested groups. कितना गहरा देखना है, आप चुनते हैं।文件夹里套子文件夹,子文件夹里放文件:嵌套分组。看多深由你决定。
🐾 Tree of life (biology)🐾 Tree of life (biology)🐾 生命之树(生物学)Humans and chimps join low, dogs join higher, fish join near the top. Exactly a dendrogram.इंसान और chimps नीचे जुड़ते हैं, कुत्ते ऊपर, मछलियाँ लगभग सबसे ऊपर। बिल्कुल dendrogram.人和黑猩猩在低处相连,狗在更高处,鱼几乎在顶端。完全就是一张树状图。
🧠
The Whole Algorithm in One Sentenceपूरा Algorithm एक वाक्य में一句话讲完整个算法

Start with every point alone, keep joining the two closest groups, and write down how far apart they were each time. That written record is the dendrogram. Linkage decides what "closest groups" means; the cut decides how many clusters you keep.

हर point को अकेले शुरू करें, बार-बार दो सबसे पास वाले groups जोड़ें, और हर बार लिखें कि वे कितने दूर थे। वही लिखा हुआ record dendrogram है। Linkage तय करता है कि "सबसे पास वाले groups" का मतलब क्या है; cut तय करता है कि आप कितने clusters रखेंगे।

每个点先各自为一组,然后不断合并最接近的两组,并记下每次合并时它们相距多远。 这份记录就是树状图。连接方式决定“最接近的两组”是什么意思;切割位置决定你保留几个簇。


SectionSection第 03 节

Two Flavours — Agglomerative vs Divisiveदो तरीके — Agglomerative vs Divisive两种方式 — 凝聚式 vs 分裂式

There are two directions to build a hierarchy: from the bottom up, or from the top down.

Hierarchy बनाने की दो दिशाएँ हैं: नीचे से ऊपर, या ऊपर से नीचे।

构建层次结构有两个方向:自底向上,或自顶向下。

📊
Agglomerative (Bottom-Up)Agglomerative (नीचे से ऊपर)凝聚式(自底向上)
AGNES — the usual choiceAGNES — आम पसंदAGNES —— 最常用
Start with every data point as its own cluster. At each step, merge the two most similar clusters. Continue until all points are in one cluster. Then cut the dendrogram at a chosen height.
हर data point को उसका अपना cluster मानकर शुरू करें। हर step पर दो सबसे मिलते-जुलते clusters merge करें। तब तक चलाएँ जब तक सब एक cluster में न आ जाएँ। फिर dendrogram को चुनी हुई ऊँचाई पर काटें।
从每个数据点各自成簇开始。每一步合并最相似的两个簇,直到所有点都在一个簇里。然后在选定的高度切开树状图。
✓ Fine for small and medium datasetsछोटे और मध्यम datasets के लिए ठीक适合中小规模数据集
✓ Built into scikit-learn and SciPyscikit-learn और SciPy में मौजूदscikit-learn 和 SciPy 都已内置
✗ Naive version is O(n³); good libraries are O(n²) time and O(n²) memoryसीधा version O(n³); अच्छी libraries O(n²) समय और O(n²) memory朴素实现 O(n³);好的库为 O(n²) 时间、O(n²) 内存
🗡️
Divisive (Top-Down)Divisive (ऊपर से नीचे)分裂式(自顶向下)
DIANA — less commonDIANA — कम इस्तेमालDIANA —— 较少用
Start with all data in one cluster. At each step, split the most mixed-up cluster into two. Repeat until every point stands alone (or you stop early).
सारे data को एक cluster में रखकर शुरू करें। हर step पर सबसे मिले-जुले cluster को दो में बाँटें। तब तक दोहराएँ जब तक हर point अकेला न हो (या आप पहले रुक जाएँ)।
从所有数据在一个簇开始。每一步把最混杂的簇一分为二。重复直到每个点单独成簇(或提前停止)。
✓ Good when you only need the top few splitsजब सिर्फ़ ऊपर के कुछ splits चाहिए तब अच्छा只需要最上面几次划分时很合适
✗ Trying every split is O(2ⁿ), so real versions use shortcutsहर split आज़माना O(2ⁿ) है, इसलिए असली versions shortcuts लेते हैं穷举所有划分是 O(2ⁿ),实际实现都用近似方法
✗ Not in scikit-learn or SciPyscikit-learn या SciPy में नहींscikit-learn 和 SciPy 都没有
🌳
The DendrogramDendrogram树状图
Output of both methodsदोनों तरीकों का output两种方法的共同输出
A tree diagram. The vertical axis is the distance at which two clusters merged; the horizontal axis lists the data points. A horizontal cut at any height gives a valid clustering.
एक पेड़ जैसा चित्र। खड़ी axis वह दूरी है जिस पर दो clusters merge हुए; आड़ी axis पर data points हैं। किसी भी ऊँचाई पर आड़ा cut एक सही clustering देता है।
一张树形图。纵轴是两个簇合并时的距离;横轴列出数据点。在任意高度横切一刀,都能得到一种有效的聚类。
✓ Shows all possible clusterings at onceसभी संभव clusterings एक साथ दिखाता है一次展示所有可能的聚类
✓ Reveals natural structureस्वाभाविक ढाँचा दिखाता है揭示自然结构
📊 AGGLOMERATIVE (BOTTOM-UP) vs DIVISIVE (TOP-DOWN)AGGLOMERATIVE (नीचे से ऊपर) vs DIVISIVE (ऊपर से नीचे)凝聚式(自底向上)vs 分裂式(自顶向下)
Agglomerative vs divisive E F A B C D AGGLOMERATIVEAGGLOMERATIVE凝聚式 start: 6 clustersशुरुआत: 6 clusters开始:6 个簇 merge, merge, merge…merge, merge, merge…合并、合并、再合并… DIVISIVEDIVISIVE分裂式 start: 1 clusterशुरुआत: 1 cluster开始:1 个簇 split, split, split…split, split, split…分裂、分裂、再分裂… bottom-upनीचे से ऊपर自底向上 top-downऊपर से नीचे自顶向下

Both directions describe a tree of nested groups. Note: they do not always produce the same tree — agglomerative makes the best choice at the bottom, divisive at the top.

दोनों दिशाएँ nested groups का एक पेड़ बताती हैं। ध्यान दें: वे हमेशा एक ही पेड़ नहीं बनातीं — agglomerative नीचे सबसे अच्छा चुनाव करता है, divisive ऊपर।

两个方向描述的都是嵌套分组的树。注意:它们不一定得到同一棵树 —— 凝聚式在底层做最优选择,分裂式在顶层做最优选择。

🔎
The 95% Rule95% नियम95% 法则

When people say "hierarchical clustering" they almost always mean agglomerative clustering. Divisive methods are elegant but rarely found in mainstream ML libraries. This tutorial focuses on agglomerative clustering.

जब लोग "hierarchical clustering" कहते हैं तो लगभग हमेशा उनका मतलब agglomerative clustering होता है। Divisive तरीके सुंदर हैं पर आम ML libraries में कम मिलते हैं। यह tutorial agglomerative clustering पर ध्यान देता है।

人们说“层次聚类”时,几乎总是指凝聚式聚类。分裂式方法很优雅,但主流机器学习库中很少提供。本教程重点讲凝聚式聚类。


SectionSection第 04 节

Step by Step: How Agglomerative Clustering WorksStep by Step: Agglomerative Clustering कैसे काम करता है一步一步:凝聚式聚类如何运作

Five Cities — Finding Natural Groupsपाँच Cities — स्वाभाविक Groups खोजना五座城市 — 寻找自然分组
We have 5 cities — A, B, C, D, E — with the road distances (km) below. We cluster them with agglomerative clustering and single linkage (the distance between two groups = their closest pair of cities).
हमारे पास 5 cities हैं — A, B, C, D, E — और नीचे सड़क की दूरियाँ (km)। हम इन्हें agglomerative clustering और single linkage से cluster करते हैं (दो groups के बीच दूरी = उनकी सबसे पास वाली cities की जोड़ी)।
有 5 座城市 —— A、B、C、D、E —— 道路距离(公里)如下表。我们用凝聚式聚类和单连接(single linkage)来聚类 (两组之间的距离 = 两组中最近的那对城市的距离)。
ABCDE
A—10507090
B10—456585
C5045—2060
D706520—40
E90856040—
01
Initialise — each city is its own clusterशुरुआत — हर city अपना cluster初始化 —— 每座城市自成一簇
Clusters: {A}, {B}, {C}, {D}, {E} → 5 clusters, 0 merges.
Clusters: {A}, {B}, {C}, {D}, {E} → 5 clusters, 0 merges.
簇:{A}、{B}、{C}、{D}、{E} → 5 个簇,0 次合并。
02
Smallest distance — merge A & B (10)सबसे छोटी दूरी — A & B merge (10)最小距离 —— 合并 A 与 B(10)
A and B are closest. New clusters: {A,B}, {C}, {D}, {E}. Merge height = 10.
A और B सबसे पास हैं। नए clusters: {A,B}, {C}, {D}, {E}. Merge height = 10.
A 和 B 最近。新簇:{A,B}、{C}、{D}、{E}。合并高度 = 10。
03
Update distances to {A,B}{A,B} तक की दूरियाँ update करें更新到 {A,B} 的距离
Single linkage: d({A,B}, C) = min(50, 45) = 45; d({A,B}, D) = min(70, 65) = 65; d({A,B}, E) = min(90, 85) = 85.
Single linkage: d({A,B}, C) = min(50, 45) = 45; d({A,B}, D) = min(70, 65) = 65; d({A,B}, E) = min(90, 85) = 85.
单连接:d({A,B}, C) = min(50, 45) = 45;d({A,B}, D) = min(70, 65) = 65;d({A,B}, E) = min(90, 85) = 85。
04
Next smallest — merge C & D (20)अगली सबसे छोटी — C & D merge (20)次小 —— 合并 C 与 D(20)
Clusters: {A,B}, {C,D}, {E}. Merge height = 20. Update: d({C,D}, E) = min(60, 40) = 40; d({A,B}, {C,D}) = min(45, 65) = 45.
Clusters: {A,B}, {C,D}, {E}. Merge height = 20. Update: d({C,D}, E) = min(60, 40) = 40; d({A,B}, {C,D}) = min(45, 65) = 45.
簇:{A,B}、{C,D}、{E}。合并高度 = 20。更新:d({C,D}, E) = min(60, 40) = 40;d({A,B}, {C,D}) = min(45, 65) = 45。
05
Next smallest — merge {C,D} & E (40)अगली सबसे छोटी — {C,D} & E merge (40)次小 —— 合并 {C,D} 与 E(40)
Clusters: {A,B}, {C,D,E}. Merge height = 40. Two clusters remain.
Clusters: {A,B}, {C,D,E}. Merge height = 40. दो clusters बचे।
簇:{A,B}、{C,D,E}。合并高度 = 40。剩下两个簇。
06
Final merge — {A,B} & {C,D,E} (45)आख़िरी merge — {A,B} & {C,D,E} (45)最后一次合并 —— {A,B} 与 {C,D,E}(45)
All 5 cities are in one cluster at height 45. Cut at height 30 → {A,B} and {C,D,E}. Cut at 15 → {A,B}, {C,D}, {E}.
सभी 5 cities height 45 पर एक cluster में। Height 30 पर काटें → {A,B} और {C,D,E}. 15 पर काटें → {A,B}, {C,D}, {E}.
5 座城市在高度 45 处合为一个簇。在 30 处切 → {A,B} 和 {C,D,E};在 15 处切 → {A,B}、{C,D}、{E}。
LIVELIVE互动Merge the Five Cities Yourself — Watch the Table Shrinkपाँच Cities खुद Merge करें — Table को छोटा होते देखें亲手合并五座城市 — 看着距离表缩小

Orange cell = the smallest distance, merged next. Green = distances to the newly merged cluster, with the calculation shown below. Switch the linkage to see how the heights change (complete uses max, average uses the mean).

नारंगी cell = सबसे छोटी दूरी, जो अगली merge होगी। हरा = नए merged cluster तक की दूरियाँ, नीचे गणना के साथ। Linkage बदलकर देखें कि heights कैसे बदलती हैं (complete max लेता है, average औसत)।

橙色格子 = 最小距离,下一步就合并它。绿色 = 到新合并簇的距离,计算过程显示在下方。切换连接方式,看看合并高度如何变化(全连接取最大值,平均连接取均值)。

📈
Reading the Resultनतीजा पढ़ना解读结果

With single linkage the merge heights are 10, 20, 40, 45. Cut at height 30 and you get 2 clusters: {A, B} and {C, D, E}. Cut at height 15 and you get 3 clusters: {A, B}, {C, D}, {E}. One run gives you every possible clustering at once — the main advantage over K-Means. Switch to complete linkage in the simulator: the order of merges stays the same here, but the heights become 10, 20, 60, 90.

Single linkage में merge heights 10, 20, 40, 45 हैं। Height 30 पर काटें तो 2 clusters मिलते हैं: {A, B} और {C, D, E}. Height 15 पर काटें तो 3 clusters: {A, B}, {C, D}, {E}. एक run सभी संभव clusterings एक साथ देता है — K-Means पर यही मुख्य बढ़त है। Simulator में complete linkage चुनें: यहाँ merges का क्रम वही रहता है, पर heights 10, 20, 60, 90 हो जाती हैं।

单连接下的合并高度是 10、20、40、45。在高度 30 处切,得到 2 个簇:{A, B} 和 {C, D, E}。 在高度 15 处切,得到 3 个簇:{A, B}、{C, D}、{E}。运行一次就同时得到所有可能的聚类 —— 这是相对 K-Means 的主要优势。 在模拟器中换成全连接:这里的合并顺序不变,但高度变成 10、20、60、90。

Now with 12 points on a mapअब map पर 12 points के साथ现在换成地图上的 12 个点

LIVELIVE互动Build a Dendrogram, One Merge at a Timeएक-एक merge करके Dendrogram बनाएँ一步一步合并,构建树状图

Left: 12 points; the orange line joins the two groups merged last. Right: the dendrogram growing — the height of each joint is the merge distance. Move "Cut into" to choose the number of clusters, and try different linkages.

बाएँ: 12 points; नारंगी line आख़िरी merge हुए दो groups को जोड़ती है। दाएँ: बढ़ता dendrogram — हर जोड़ की ऊँचाई merge की दूरी है। Clusters की संख्या चुनने के लिए "इतने में काटें" खिसकाएँ, और अलग linkages आज़माएँ।

左:12 个点,橙色线连接最近一次合并的两组。右:逐步生长的树状图 —— 每个连接点的高度就是合并距离。拖动“切成”选择簇数,并试试不同的连接方式。


SectionSection第 05 节

Linkage Criteria — How to Measure Distance Between ClustersLinkage Criteria — Clusters के बीच दूरी कैसे मापें连接准则 — 如何度量簇与簇之间的距离

Once two points form a cluster, how far is that cluster from the others? The rule that answers this is the linkage criterion. It is the most important choice in hierarchical clustering.

जब दो points एक cluster बना लेते हैं, तो वह cluster बाकियों से कितना दूर है? इसका जवाब देने वाला नियम linkage criterion है। Hierarchical clustering में यही सबसे ज़रूरी चुनाव है।

两个点合成一个簇之后,这个簇离其他簇有多远?回答这个问题的规则叫作连接准则(linkage criterion)。它是层次聚类中最重要的选择。

📷 THE SAME TWO CLUSTERS, FOUR LINKAGES (COMPUTED)वही दो CLUSTERS, चार LINKAGES (गणना से)同样的两个簇,四种连接方式(真实计算)
Linkage criteria SINGLE = minSINGLE = min单连接 = 最小 81 COMPLETE = maxCOMPLETE = max全连接 = 最大 133 AVERAGE = mean of 9AVERAGE = 9 का mean平均 = 9 对的均值 107 WARD = growth of WCSSWARD = WCSS की बढ़तWARD = WCSS 的增量 15,267 (units²) Same two clusters, four different "distances". The number decides which pair merges first.वही दो clusters, चार अलग "दूरियाँ"। यही number तय करता है कि कौन सा जोड़ा पहले merge होगा।同样的两个簇,四种不同的“距离”。这个数决定哪一对先合并。
🥰
Single LinkageSingle Linkage单连接
min distance between any point in A and any point in BA के किसी भी point और B के किसी भी point के बीच min दूरीA 中任一点与 B 中任一点之间的最小距离
Uses the closest pair. Can follow long, curved shapes, but suffers from chaining: a thin bridge of points can join two separate groups.
सबसे पास वाला जोड़ा इस्तेमाल करता है। लंबे, मुड़े आकारों के साथ चल सकता है, पर chaining की समस्या है: points का पतला पुल दो अलग groups को जोड़ सकता है।
使用最近的一对点。能跟随细长、弯曲的形状,但有链式效应:一条细细的点桥就能把两个分开的组连起来。
🚫
Complete LinkageComplete Linkage全连接
max distance between any point in A and any point in BA के किसी भी point और B के किसी भी point के बीच max दूरीA 中任一点与 B 中任一点之间的最大距离
Uses the farthest pair. Gives tight, compact clusters. One far-away point makes a cluster look "big", so outliers can change the result.
सबसे दूर वाला जोड़ा इस्तेमाल करता है। कसे, सघन clusters देता है। एक दूर का point cluster को "बड़ा" दिखाता है, इसलिए outliers नतीजा बदल सकते हैं।
使用最远的一对点。得到紧凑的簇。一个很远的点会让簇显得“很大”,所以离群点可能改变结果。
⚖️
Average Linkage (UPGMA)Average Linkage (UPGMA)平均连接(UPGMA)
average of all pairwise distancesसभी pairwise दूरियों का औसत所有点对距离的平均值
A middle path between single and complete. Works with any distance (including correlation), which is why it is popular in biology.
Single और complete के बीच का रास्ता। किसी भी distance (correlation समेत) के साथ चलता है, इसीलिए biology में लोकप्रिय है।
介于单连接与全连接之间的折中方案。适用于任何距离(包括相关距离),所以在生物学中很流行。
📅
Ward's MethodWard's MethodWard 方法
smallest increase in within-cluster sum of squareswithin-cluster sum of squares में सबसे कम बढ़त簇内平方和增加最少
Merges the pair whose merge adds the least to the total WCSS — the same quantity K-Means minimises. Gives compact, similar-sized clusters. The scikit-learn default and the usual first choice.
वह जोड़ा merge करता है जिसके merge से कुल WCSS सबसे कम बढ़े — वही मात्रा जो K-Means घटाता है। सघन, एक जैसे आकार के clusters देता है। scikit-learn का default और आम पहली पसंद।
合并后让总 WCSS 增加最少的那一对 —— 正是 K-Means 最小化的那个量。得到紧凑、大小相近的簇。scikit-learn 的默认值,也是通常的首选。
🎯
Centroid Linkage (UPGMC)Centroid Linkage (UPGMC)质心连接(UPGMC)
distance between the cluster meanscluster means के बीच दूरी两个簇均值之间的距离
Simple idea, but it can create inversions: a later merge can be lower than an earlier one, which makes the dendrogram hard to read. Available in SciPy, not in scikit-learn.
आसान विचार, पर इससे inversions बन सकते हैं: बाद वाला merge पहले वाले से नीचे हो सकता है, जिससे dendrogram पढ़ना मुश्किल होता है। SciPy में है, scikit-learn में नहीं।
思路简单,但会出现倒置(inversion):后一次合并可能比前一次更低,让树状图难以阅读。SciPy 提供,scikit-learn 没有。
🌊
Median Linkage (WPGMC)Median Linkage (WPGMC)中位数连接(WPGMC)
distance between weighted midpointsweighted midpoints के बीच दूरी加权中点之间的距离
Like centroid linkage, but a big cluster does not outweigh a small one when they merge. Can also create inversions. Rarely used.
Centroid linkage जैसा, पर merge होते समय बड़ा cluster छोटे पर भारी नहीं पड़ता। इसमें भी inversions बन सकते हैं। कम इस्तेमाल होता है।
类似质心连接,但合并时大簇不会压倒小簇。同样会出现倒置。很少使用。
LinkageLinkage连接方式Cluster shapeCluster का आकार簇的形状Outlier sensitivityOutliers का असर对离群点敏感度Chaining?Chaining?链式效应?Best forकिसके लिए最适合
SingleAny / long, curvedकोई भी / लंबा, मुड़ा任意 / 细长弯曲Very highबहुत ज़्यादा很高Yesहाँ是Curved shapes with clear gapsसाफ़ gaps वाले मुड़े आकार间隙清晰的弯曲形状
CompleteCompactसघन紧凑Highज़्यादा高Noनहीं否Compact groups of similar sizeएक जैसे आकार के सघन groups大小相近的紧凑组
AverageModerateमध्यम中等Moderateमध्यम中等Rarelyकम ही很少Any distance metric; biologyकोई भी distance metric; biology任意距离度量;生物学
WardCompact & balancedसघन & संतुलित紧凑且均衡Moderate (uses squared distances)मध्यम (squared distances)中等(使用距离平方)Noनहीं否Most tabular data ⭐ज़्यादातर tabular data ⭐大多数表格数据 ⭐
CentroidModerateमध्यम中等Moderateमध्यम中等Possible + inversionsसंभव + inversions可能 + 倒置Rarely recommendedकम ही सुझाया जाता很少推荐
LIVELIVE互动Linkage Showdown — Same Data, Four LinkagesLinkage मुक़ाबला — वही Data, चार Linkages连接方式对决 — 同样的数据,四种连接

Choose a dataset. Each panel cuts its own dendrogram into the true number of groups. The percentage in the corner is how many points land in their true group. No linkage wins everywhere.

एक dataset चुनें। हर panel अपने dendrogram को groups की असली संख्या में काटता है। कोने का प्रतिशत बताता है कि कितने points अपने असली group में पहुँचे। कोई भी linkage हर जगह नहीं जीतता।

选择一个数据集。每个面板把自己的树状图切成真实的组数。角上的百分比表示有多少点落在了真实所属的组。没有哪种连接方式能处处取胜。

⚠️
Ward Needs Euclidean DistanceWard को Euclidean Distance चाहिएWard 需要欧氏距离

Ward's method minimises variance, which only makes sense with Euclidean distance. scikit-learn even refuses other metrics with linkage='ward'. If you need cosine, Manhattan or correlation distance, use average or complete linkage.

Ward's method variance घटाता है, जिसका मतलब सिर्फ़ Euclidean distance के साथ बनता है। scikit-learn तो linkage='ward' के साथ दूसरे metrics स्वीकार ही नहीं करता। अगर cosine, Manhattan या correlation distance चाहिए, तो average या complete linkage इस्तेमाल करें।

Ward 方法最小化方差,这只有在欧氏距离下才有意义。scikit-learn 在 linkage='ward' 时甚至直接拒绝其他度量。 如果需要余弦、曼哈顿或相关距离,请用 average 或 complete 连接。


SectionSection第 06 节

Distance Metrics — What Does "Similar" Mean?Distance Metrics — "मिलता-जुलता" का मतलब क्या?距离度量 — “相似”到底指什么?

Before measuring the distance between clusters, we need the distance between two points. The choice changes the result a lot.

Clusters के बीच दूरी मापने से पहले हमें दो points के बीच की दूरी चाहिए। यह चुनाव नतीजे को बहुत बदल देता है।

在度量簇间距离之前,我们需要先定义两点之间的距离。这个选择会极大地影响结果。

📐
Euclidean DistanceEuclidean Distance欧氏距离
L2 — √(Σ(aᵢ−bᵢ)²)
The straight-line distance. The default for numeric data. Needs feature scaling, because features with large ranges control the distance.
सीधी line की दूरी। Numeric data के लिए default. Feature scaling ज़रूरी, क्योंकि बड़ी range वाले features दूरी पर कब्ज़ा कर लेते हैं।
直线距离,数值数据的默认选择。需要特征缩放,因为取值范围大的特征会主导距离。
✓ Simple and widely usedआसान और बहुत इस्तेमाल होने वाली简单、应用广泛
✗ Sensitive to scale and to many dimensionsScale और ज़्यादा dimensions से प्रभावित对尺度和高维敏感
📍
Manhattan DistanceManhattan Distance曼哈顿距离
L1 — Σ|aᵢ−bᵢ|
Sum of absolute differences — like walking along city blocks. Less affected by one big difference than Euclidean (it does not square), and often behaves better in many dimensions.
Absolute अंतरों का जोड़ — जैसे city blocks पर चलना। Euclidean से कम प्रभावित होती है एक बड़े अंतर से (square नहीं करती), और ज़्यादा dimensions में अक्सर बेहतर चलती है।
绝对差之和 —— 就像沿着城市街区走路。因为不平方,所以受单个大差值的影响比欧氏距离小,在高维时常常表现更好。
✓ Less affected by outliersOutliers का कम असर受离群点影响较小
✗ Also needs scalingइसे भी scaling चाहिए同样需要缩放
🔔
Cosine DistanceCosine Distance余弦距离
1 − cos(angle)1 − cos(कोण)1 − cos(夹角)
Looks only at the direction of two vectors and ignores their length. Standard for text (TF-IDF), where a long and a short document on the same topic should look similar.
दो vectors की सिर्फ़ दिशा देखती है, लंबाई नहीं। Text (TF-IDF) के लिए standard, जहाँ एक ही विषय का लंबा और छोटा document मिलता-जुलता दिखना चाहिए।
只看两个向量的方向,忽略长度。是文本(TF-IDF)的标准选择:同一主题的长文和短文应当看起来相似。
✓ Ignores size, compares directionआकार अनदेखा, दिशा की तुलना忽略大小,比较方向
✗ Not a true metric (triangle inequality can fail)सही metric नहीं (triangle inequality टूट सकती है)不是真正的度量(可能违反三角不等式)
Euclidean
d = √( Σ (xᵢ − yᵢ)² )
Continuous numeric features after scaling. The default.
Scaling के बाद continuous numeric features. Default.
缩放后的连续数值特征。默认选择。
Manhattan
d = Σ |xᵢ − yᵢ|
Less affected by outliers; good for many dimensions.
Outliers का कम असर; ज़्यादा dimensions के लिए अच्छी।
受离群点影响小;适合高维。
Cosine SimilarityCosine Similarity余弦相似度
cos(θ) = (x · y) / (‖x‖ · ‖y‖)
Direction, not size. Cosine distance = 1 − cos(θ). Standard for text.
दिशा, आकार नहीं। Cosine distance = 1 − cos(θ). Text के लिए standard.
看方向而非大小。余弦距离 = 1 − cos(θ)。文本的标准选择。
Correlation DistanceCorrelation Distance相关距离
d = 1 − r(x, y)
Compares the shape of two profiles (rise and fall together). 0 = same shape, 1 = unrelated, 2 = mirror image. Used in Case Study 02.
दो profiles के आकार की तुलना (साथ बढ़ना-घटना)। 0 = वही आकार, 1 = कोई संबंध नहीं, 2 = उल्टा आकार। Case Study 02 में इस्तेमाल।
比较两条曲线的形状(是否同升同降)。0 = 形状相同,1 = 无关,2 = 镜像相反。案例二中使用。
Hamming DistanceHamming Distance汉明距离
d = #{ i : xᵢ ≠ yᵢ }
For binary or categorical features: the number (or share) of positions that differ.
Binary या categorical features के लिए: कितनी जगहें अलग हैं (संख्या या हिस्सा)।
用于二值或类别特征:取值不同的位置个数(或比例)。
LIVELIVE互动Drag Two Points — Three Distances at Onceदो Points खींचें — एक साथ तीन दूरियाँ拖动两个点 — 同时看三种距离

Drag A and B. Orange = Euclidean (straight line), blue = Manhattan (city blocks), purple = the angle used by cosine distance (measured from the origin 0,0).

A और B को खींचें। नारंगी = Euclidean (सीधी line), नीली = Manhattan (city blocks), बैंगनी = cosine distance वाला कोण (origin 0,0 से मापा गया)।

拖动 A 和 B。橙色 = 欧氏距离(直线),蓝色 = 曼哈顿距离(街区路线),紫色 = 余弦距离使用的夹角(从原点 0,0 量起)。

Euclidean
—
Manhattan
—
Cosine distanceCosine distance余弦距离
—

▶️
Always Scale Before ClusteringClustering से पहले हमेशा Scale करें聚类之前务必缩放

If your data has Age (0–100), Salary (20,000–200,000) and Height (1.5–2.0 m), Euclidean distance will be controlled almost completely by Salary — the other features disappear. Apply StandardScaler (mean 0, standard deviation 1) or MinMaxScaler before hierarchical clustering, unless your features are already in the same units.

अगर आपके data में Age (0–100), Salary (20,000–200,000) और Height (1.5–2.0 m) हैं, तो Euclidean distance पर लगभग पूरा कब्ज़ा Salary का होगा — बाकी features ग़ायब हो जाएँगे। Hierarchical clustering से पहले StandardScaler (mean 0, standard deviation 1) या MinMaxScaler लगाएँ, जब तक आपके features पहले से एक ही unit में न हों।

如果数据里有年龄(0–100)、工资(20,000–200,000)和身高(1.5–2.0 米),欧氏距离几乎完全由工资决定 —— 其他特征等于消失了。 除非特征本来就是同一单位,否则在层次聚类前请使用 StandardScaler(均值 0、标准差 1)或 MinMaxScaler。


SectionSection第 07 节

The Dendrogram — Reading It Like a ProDendrogram — Pro की तरह पढ़ना树状图 — 像专家一样阅读

The Family Tree of DataData का Family Tree数据的家谱
Imagine a family tree hanging upside down. The leaves at the bottom are individuals (data points). As you move up, branches join — siblings into families, families into clans, clans into tribes — until everyone belongs to one root at the top. The height at which two branches join is the distance between those groups. A long vertical line before a join means the two groups were very different. A short one means they were close.
एक उल्टे लटके family tree की कल्पना करें। नीचे की leaves लोग हैं (data points)। ऊपर जाने पर शाखाएँ जुड़ती हैं — भाई-बहन परिवारों में, परिवार कुलों में, कुल कबीलों में — जब तक सब ऊपर एक जड़ में न आ जाएँ। जिस ऊँचाई पर दो शाखाएँ जुड़ती हैं वह उन groups के बीच की दूरी है। जुड़ने से पहले लंबी खड़ी line मतलब दोनों groups बहुत अलग थे। छोटी line मतलब वे पास थे।
想象一棵倒挂的家谱树。底部的叶子是个人(数据点)。向上走,分支不断汇合 —— 兄弟姐妹汇成家庭,家庭汇成宗族,宗族汇成部落 —— 直到顶端所有人归于一个根。 两条分支汇合的高度就是这两组之间的距离。汇合前的竖线很长,说明两组差别很大;很短,说明它们很接近。
📊 How to Read a DendrogramDendrogram कैसे पढ़ें如何阅读树状图
X-axis
The data points (leaves). The algorithm re-orders them so the tree looks clean — the left-right position means nothing beyond "these are in the same branch". Data points (leaves)। Algorithm इन्हें इस तरह क्रम में रखता है कि पेड़ साफ़ दिखे — बाएँ-दाएँ की जगह का मतलब सिर्फ़ "ये एक ही शाखा में हैं" है। 数据点(叶子)。算法会重新排列它们让树看起来整洁 —— 左右位置除了“它们在同一分支”外没有其他含义。
Y-axis
The distance at which a merge happened. Higher = the groups were more different. This is the axis you use to decide where to cut. वह दूरी जिस पर merge हुआ। ऊँचा = groups ज़्यादा अलग थे। कहाँ काटना है, यह इसी axis से तय करते हैं। 发生合并时的距离。越高 = 两组越不相似。决定在哪里切,就看这根轴。
Cut lineCut line切割线
Draw a horizontal line across the tree. The number of vertical lines it crosses = the number of clusters. पेड़ के आर-पार एक आड़ी line खींचें। यह जितनी खड़ी lines काटती है = clusters की संख्या। 在树上横画一条线。它穿过的竖线条数 = 簇的个数。
Big gapबड़ा gap大间隙
A long stretch of height with no merges means the groups below it are clearly separate. Cutting inside that gap is usually a good choice. ऊँचाई का लंबा हिस्सा जिसमें कोई merge नहीं, बताता है कि उसके नीचे के groups साफ़ अलग हैं। उस gap के अंदर काटना आमतौर पर अच्छा चुनाव है। 一大段高度内都没有合并,说明下面的组彼此明显分开。在这个间隙里切,通常是好选择。
Coloursरंग颜色
SciPy's dendrogram(color_threshold=…) colours each branch below the threshold differently, so cluster membership is easy to see. SciPy का dendrogram(color_threshold=…) threshold से नीचे की हर शाखा को अलग रंग देता है, ताकि cluster membership आसानी से दिखे। SciPy 的 dendrogram(color_threshold=…) 会给阈值以下的每个分支涂上不同颜色,簇的归属一目了然。
📊 HOW TO READ A DENDROGRAM (COMPUTED, WARD LINKAGE, 12 POINTS)DENDROGRAM कैसे पढ़ें (गणना से, WARD LINKAGE, 12 POINTS)如何阅读树状图(真实计算,Ward 连接,12 个点)
Reading a dendrogram P11 P10 P9 P12 P1 P4 P2 P3 P5 P8 P6 P7 0 2 4 6 cut here → K = 3यहाँ काटें → K = 3在此切 → K = 3 cut here → K = 2यहाँ काटें → K = 2在此切 → K = 2 biggest gap:सबसे बड़ा gap:最大间隙: 1.17 → 5.17 ↑ merge height↑ merge height↑ 合并高度 (distance)(दूरी)(距离) 12 points (leaves). Left-right order only keeps groups together; it has no other meaning.12 points (leaves)। बाएँ-दाएँ का क्रम सिर्फ़ groups को साथ रखता है; इसका और कोई मतलब नहीं।12 个点(叶子)。左右顺序只是让同组的点挨在一起,没有其他含义。

Merge heights near the top: 1.08, 1.17, then a jump to 5.17 and 7.13. The empty band between 1.17 and 5.17 is the biggest gap, so K = 3 is the natural answer.

ऊपर के पास merge heights: 1.08, 1.17, फिर छलाँग 5.17 और 7.13 पर। 1.17 और 5.17 के बीच का ख़ाली हिस्सा सबसे बड़ा gap है, इसलिए K = 3 स्वाभाविक जवाब है।

靠近顶部的合并高度:1.08、1.17,然后跳到 5.17 和 7.13。1.17 到 5.17 之间的空白带是最大间隙,所以 K = 3 是自然的答案。

LIVELIVE互动Drag the Cut Line — Choose K YourselfCut Line खींचें — K खुद चुनें拖动切割线 — 亲自选择 K

Drag anywhere on the dendrogram to move the red cut. The scatter plot on the right colours the points by the clusters you get. The orange band marks the biggest gap. Change the true number of groups to test the rule.

लाल cut खिसकाने के लिए dendrogram पर कहीं भी खींचें। दाईं ओर का scatter plot आपको मिले clusters के रंग में points दिखाता है। नारंगी पट्टी सबसे बड़ा gap दिखाती है। नियम जाँचने के लिए groups की असली संख्या बदलें।

在树状图上任意位置拖动,移动红色切割线。右侧散点图按你得到的簇给点上色。橙色带标出最大间隙。改变真实组数来检验这条规则。

Silhouette at this cutइस cut पर silhouette此切割的轮廓系数
—

✂️
The "Biggest Gap" Rule"सबसे बड़ा Gap" नियम“最大间隙”法则

Look for the longest stretch of height with no merges. Cut inside it. The number of vertical lines you cross is a good K. This is the most common way to choose K from a dendrogram — the hierarchical version of the elbow method. Always confirm it with the silhouette score (Section 09).

ऊँचाई का वह सबसे लंबा हिस्सा खोजें जिसमें कोई merge न हो। उसके अंदर काटें। जितनी खड़ी lines कटती हैं, वह एक अच्छा K है। Dendrogram से K चुनने का यह सबसे आम तरीका है — elbow method का hierarchical रूप। हमेशा silhouette score से पुष्टि करें (Section 09)।

找出没有任何合并的最长一段高度,在其中切一刀。穿过的竖线条数就是一个好的 K。 这是从树状图选择 K 最常用的方法 —— 相当于层次聚类版的肘部法。务必再用轮廓系数确认(第 09 节)。


SectionSection第 08 节

Time and Memory — How Big Can the Data Be?समय और Memory — Data कितना बड़ा हो सकता है?时间与内存 — 数据能有多大?

Hierarchical clustering needs the distance between every pair of points. That is what limits it. Here are real timings from SciPy on 5-feature data:

Hierarchical clustering को points के हर जोड़े के बीच दूरी चाहिए। यही इसकी सीमा है। 5-feature data पर SciPy की असली timings ये हैं:

层次聚类需要每一对点之间的距离,这正是它的瓶颈。下面是 SciPy 在 5 个特征的数据上的真实计时:

import time
import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.cluster import KMeans

rng = np.random.default_rng(0)
KMeans(5, n_init=1, random_state=0).fit(rng.normal(size=(500, 5)))   # warm-up run
print(f"{'n':>6} | {'distance matrix':>15} | {'Ward linkage':>12} | {'K-Means (K=5)':>13}")
for n in [1000, 2000, 4000, 8000, 16000]:
    X = rng.normal(size=(n, 5))
    mem_mb = n * (n - 1) / 2 * 8 / 1e6            # condensed matrix, 8 bytes per float
    t0 = time.time(); linkage(X, method='ward'); t_hc = time.time() - t0
    t0 = time.time(); KMeans(5, n_init=1, random_state=0).fit(X); t_km = time.time() - t0
    print(f"{n:>6} | {mem_mb:>12.0f} MB | {t_hc:>10.2f} s | {t_km:>11.2f} s")
OUTPUT
n | distance matrix | Ward linkage | K-Means (K=5) 1000 | 4 MB | 0.04 s | 0.00 s 2000 | 16 MB | 0.27 s | 0.00 s 4000 | 64 MB | 0.92 s | 0.01 s 8000 | 256 MB | 4.00 s | 0.02 s 16000 | 1024 MB | 19.53 s | 0.10 s

Each time n doubles, the memory grows 4× and the Ward time grows roughly 4× too — that is O(n²). K-Means stays almost flat. (Your times will differ by machine; the growth pattern will not.)

हर बार n दोगुना होने पर memory 4× बढ़ती है और Ward का समय भी लगभग 4× — यही O(n²) है। K-Means लगभग सपाट रहता है। (आपकी machine पर समय अलग होगा; बढ़ने का pattern नहीं।)

n 每翻一倍,内存增长 4 倍,Ward 的耗时也大约增长 4 倍 —— 这就是 O(n²)。K-Means 几乎不变。(不同机器的耗时会不同,但增长规律不会变。)

AlgorithmAlgorithm算法Timeसमय时间MemoryMemory内存Practical limit (laptop)व्यावहारिक सीमा (laptop)实际上限(笔记本)
Naive agglomerativeसीधा agglomerative朴素凝聚式O(n³)O(n²)a few thousand rowsकुछ हज़ार rows几千行
SciPy linkage / scikit-learnO(n²)O(n²)~20,000–30,000 rows~20,000–30,000 rows约 2–3 万行
scikit-learn with connectivityscikit-learn connectivity के साथscikit-learn + connectivitymuch less (sparse graph)बहुत कम (sparse graph)低得多(稀疏图)O(n·k)100,000+ rows100,000+ rows10 万行以上
K-Means (comparisonतुलना对比)O(n·K·t)O(n·K)millions of rowsलाखों-करोड़ों rows数百万行
LIVELIVE互动Will It Fit? — Memory and Time Calculatorक्या यह समाएगा? — Memory और Time Calculator装得下吗?— 内存与时间计算器

Move the slider to change the number of rows. Bars use a log scale. Times are extrapolated from the real measurements above.

Rows की संख्या बदलने के लिए slider खिसकाएँ। Bars log scale पर हैं। समय ऊपर के असली measurements से आगे बढ़ाया गया है।

拖动滑块改变行数。条形图使用对数刻度。耗时由上面的真实测量外推得到。

⚠️
Scalability WarningScalability चेतावनी可扩展性警告

Hierarchical clustering stores about n²/2 distances. For 10,000 rows that is 50 million numbers — about 400 MB at 8 bytes each, before any other work. For data above a few tens of thousands of rows, use K-Means, Mini-Batch K-Means, DBSCAN or BIRCH — or run hierarchical clustering on a representative sample.

Hierarchical clustering लगभग n²/2 दूरियाँ रखता है। 10,000 rows के लिए यह 5 करोड़ numbers हैं — 8 bytes प्रति number पर लगभग 400 MB, और कोई काम शुरू होने से पहले। कुछ दसियों हज़ार rows से बड़े data के लिए K-Means, Mini-Batch K-Means, DBSCAN या BIRCH इस्तेमाल करें — या एक प्रतिनिधि sample पर hierarchical clustering चलाएँ।

层次聚类要存储约 n²/2 个距离。1 万行就是 5000 万个数 —— 每个 8 字节,约 400 MB,这还没开始做其他计算。 超过几万行的数据,请用 K-Means、Mini-Batch K-Means、DBSCAN 或 BIRCH —— 或者在有代表性的样本上运行层次聚类。


SectionSection第 09 节

Evaluating Cluster QualityCluster Quality जाँचना评估聚类质量

There are no true labels, so we use internal scores that only look at the data and the clusters.

कोई असली labels नहीं हैं, इसलिए हम internal scores इस्तेमाल करते हैं जो सिर्फ़ data और clusters देखते हैं।

没有真实标签,所以我们使用只看数据和簇本身的内部指标。

🔓
Silhouette ScoreSilhouette Score轮廓系数
For each point: s = (b − a) / max(a, b), where a = average distance to its own cluster and b = average distance to the nearest other cluster. Range −1 to +1. Higher is better; above about 0.5 is good.
हर point के लिए: s = (b − a) / max(a, b), जहाँ a = अपने cluster से औसत दूरी और b = सबसे पास वाले दूसरे cluster से औसत दूरी। Range −1 से +1. ज़्यादा बेहतर; लगभग 0.5 से ऊपर अच्छा।
对每个点:s = (b − a) / max(a, b),a = 到本簇的平均距离,b = 到最近其他簇的平均距离。范围 −1 到 +1,越高越好;大于约 0.5 算好。
📈
Calinski-Harabasz IndexCalinski-Harabasz IndexCalinski-Harabasz 指数
Between-cluster spread divided by within-cluster spread (adjusted for K and n). Higher = better separated. Fast to compute; there is no fixed "good" value, so compare K values.
Clusters के बीच का फैलाव ÷ cluster के अंदर का फैलाव (K और n के हिसाब से adjust)। ज़्यादा = बेहतर अलग। जल्दी निकलता है; कोई तय "अच्छी" value नहीं, इसलिए K values की तुलना करें।
簇间离散度除以簇内离散度(按 K 和 n 调整)。越高 = 分得越开。计算快;没有固定的“好”值,所以要在不同 K 之间比较。
📋
Davies-Bouldin IndexDavies-Bouldin IndexDavies-Bouldin 指数
For each cluster, its worst ratio of (own spread + other spread) / distance between centres, averaged. Lower = better; 0 is perfect. Uses cluster centres, so it is cheaper than silhouette.
हर cluster के लिए (अपना फैलाव + दूसरे का फैलाव) / centres के बीच दूरी का सबसे ख़राब ratio, फिर औसत। कम = बेहतर; 0 perfect. Cluster centres इस्तेमाल करता है, इसलिए silhouette से सस्ता है।
对每个簇取(自身离散度 + 另一簇离散度)/ 中心距离的最差比值,再求平均。越低越好,0 为完美。使用簇中心,所以比轮廓系数便宜。
💡
Silhouette Analysis for Choosing KK चुनने के लिए Silhouette Analysis用轮廓系数选择 K

Cut the dendrogram at several heights (K = 2, 3, … 10), compute the silhouette for each K, and look for the highest score. Because the tree is built only once, trying many cuts is cheap. Combine it with the biggest-gap rule and with what makes sense for your problem.

Dendrogram को कई ऊँचाइयों पर काटें (K = 2, 3, … 10), हर K का silhouette निकालें, और सबसे ऊँचा score देखें। पेड़ सिर्फ़ एक बार बनता है, इसलिए कई cuts आज़माना सस्ता है। इसे सबसे बड़े gap वाले नियम और अपनी problem की समझ के साथ मिलाएँ।

在多个高度切开树状图(K = 2、3、… 10),计算每个 K 的轮廓系数,找出最高分。因为树只需构建一次,尝试多种切法成本很低。 再结合最大间隙法则和对问题本身的理解来做决定。


SectionSection第 10 节

Python Implementation — Full WalkthroughPython Implementation — पूरा WalkthroughPython 实现 — 完整演练

A complete implementation using scipy (for the dendrogram) and scikit-learn (for pipelines). Every output below is the real output of the code.

scipy (dendrogram के लिए) और scikit-learn (pipelines के लिए) से पूरा implementation. नीचे का हर output code का असली output है।

使用 scipy(画树状图)和 scikit-learn(用于流水线)的完整实现。下面每个输出都是代码真实运行的结果。

Step 1 — Import Libraries and Generate DataStep 1 — Libraries import करें और Data बनाएँ第 1 步 — 导入库并生成数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# scipy — dendrogram plotting
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from scipy.spatial.distance   import pdist

# sklearn — clustering + evaluation
from sklearn.cluster           import AgglomerativeClustering
from sklearn.preprocessing     import StandardScaler
from sklearn.metrics           import silhouette_score, davies_bouldin_score
from sklearn.datasets          import make_blobs

# Reproducibility
np.random.seed(42)

# Generate 3-cluster synthetic data
X, y_true = make_blobs(
    n_samples=150,
    centers=3,
    cluster_std=0.8,
    random_state=42
)

print(f"Dataset shape: {X.shape}")
OUTPUT
Dataset shape: (150, 2)

Step 2 — Scale FeaturesStep 2 — Features scale करें第 2 步 — 缩放特征

# Always scale before distance-based algorithms
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

print("Mean per feature:  ", X_scaled.mean(axis=0).round(4) + 0.0)   # + 0.0 turns -0.0 into 0.0
print("Std  per feature:  ", X_scaled.std(axis=0).round(4))
OUTPUT
Mean per feature: [0. 0.] Std per feature: [1. 1.]

Step 3 — Build the Linkage Matrix and Plot the DendrogramStep 3 — Linkage Matrix बनाएँ और Dendrogram plot करें第 3 步 — 构建连接矩阵并画树状图

# Build the full linkage matrix using Ward's method
Z = linkage(X_scaled, method='ward', metric='euclidean')

# Z is an (n-1) x 4 matrix; each row:
# [cluster_i, cluster_j, distance, count_in_new_cluster]
np.set_printoptions(suppress=True)          # plain numbers, no 1e+01
print("Linkage matrix shape:", Z.shape)
print("First 3 merges:\n", Z[:3].round(3))
print("Last 3 merge heights:", Z[-3:, 2].round(2))

# ── Plot the dendrogram ─────────────────────────────────────
plt.figure(figsize=(14, 6))
plt.title('Hierarchical Clustering Dendrogram (Ward Linkage)', fontsize=14)
plt.xlabel('Sample Index')
plt.ylabel('Distance (Ward)')

dendrogram(
    Z,
    color_threshold=5.0,     # 5 sits inside the big gap (1.49 → 13.06) → 3 colours
    leaf_font_size=8,
    above_threshold_color='grey'
)

# Draw a horizontal cut line at height = 5
plt.axhline(y=5.0, color='red', linestyle='--', label='Cut threshold')
plt.legend()
plt.tight_layout()
plt.show()
OUTPUT
Linkage matrix shape: (149, 4) First 3 merges: [[ 24. 52. 0.002 2. ] [ 72. 117. 0.006 2. ] [ 74. 124. 0.008 2. ]] Last 3 merge heights: [ 1.49 13.06 20.43]

Each row of Z is one merge: [cluster i, cluster j, merge height, size of the new cluster]. Ids 0–149 are the original points; id 150 is the first new cluster, and so on. The last three heights (1.49 → 13.06 → 20.43) show a huge gap, which is why color_threshold=5.0 gives 3 colours.

Z की हर row एक merge है: [cluster i, cluster j, merge height, नए cluster का size]. Ids 0–149 असली points हैं; id 150 पहला नया cluster है, और इसी तरह आगे। आख़िरी तीन heights (1.49 → 13.06 → 20.43) एक बड़ा gap दिखाती हैं, इसीलिए color_threshold=5.0 3 रंग देता है।

Z 的每一行是一次合并:[簇 i, 簇 j, 合并高度, 新簇大小]。编号 0–149 是原始点;150 是第一个新簇,依此类推。最后三个高度(1.49 → 13.06 → 20.43)之间有巨大间隙,所以 color_threshold=5.0 会得到 3 种颜色。

Step 4 — Extract Clusters and EvaluateStep 4 — Clusters निकालें और जाँचें第 4 步 — 提取簇并评估

# ── Method A: scipy fcluster (cut dendrogram at K=3) ───────
labels_scipy = fcluster(Z, t=3, criterion='maxclust')

# ── Method B: sklearn AgglomerativeClustering ──────────────
# Production-grade, integrates with sklearn pipelines
hac = AgglomerativeClustering(
    n_clusters=3,
    linkage='ward',
    metric='euclidean'
)
labels_sklearn = hac.fit_predict(X_scaled)

# ── Evaluation metrics ──────────────────────────────────────
sil  = silhouette_score(X_scaled, labels_sklearn)
dbi  = davies_bouldin_score(X_scaled, labels_sklearn)

print(f"Silhouette Score  : {sil:.4f}  (higher = better, max=1.0)")
print(f"Davies-Bouldin    : {dbi:.4f}  (lower  = better, min=0.0)")
print(f"Cluster sizes     : {np.bincount(labels_sklearn)}")
OUTPUT
Silhouette Score : 0.8771 (higher = better, max=1.0) Davies-Bouldin : 0.1682 (lower = better, min=0.0) Cluster sizes : [50 50 50]

Step 5 — Silhouette for Every Cut to Find the Best KStep 5 — सबसे अच्छा K खोजने के लिए हर Cut का Silhouette第 5 步 — 对每种切法计算轮廓系数,找出最佳 K

# Cut dendrogram at K = 2 to 8 and score each
k_range = range(2, 9)
sil_scores = []

for k in k_range:
    labels = fcluster(Z, t=k, criterion='maxclust')
    sil_scores.append(silhouette_score(X_scaled, labels))

best_k  = k_range[int(np.argmax(sil_scores))]
best_sc = max(sil_scores)
print(f"Best K = {best_k}  →  Silhouette = {best_sc:.4f}")

for k, sc in zip(k_range, sil_scores):
    bar = '█' * int(sc * 50)
    marker = ' ← BEST' if k == best_k else ''
    print(f"  K={k}  {bar}  {sc:.4f}{marker}")
OUTPUT
Best K = 3 → Silhouette = 0.8771 K=2 ███████████████████████████████████ 0.7013 K=3 ███████████████████████████████████████████ 0.8771 ← BEST K=4 ███████████████████████████████████ 0.7169 K=5 ███████████████████████████ 0.5509 K=6 ██████████████████ 0.3677 K=7 ██████████████████ 0.3696 K=8 ██████████████████ 0.3719

K = 3 wins clearly (0.88), matching the 3 blobs we generated and the big gap in the dendrogram.

K = 3 साफ़ जीतता है (0.88), जो हमारे बनाए 3 blobs और dendrogram के बड़े gap से मेल खाता है।

K = 3 明显胜出(0.88),与我们生成的 3 个团以及树状图中的大间隙一致。


SectionSection第 11 节

Hierarchical vs K-Means — When to Use WhichHierarchical vs K-Means — कब कौन सा层次聚类 vs K-Means — 何时用哪个

Propertyगुण特性Hierarchical ClusteringHierarchical Clustering层次聚类K-Means
Choose K in advance?K पहले से चुनना?需要预先指定 K?No — choose after seeing the dendrogramनहीं — dendrogram देखकर चुनें不需要 —— 看了树状图再选Yes — before runningहाँ — चलाने से पहले需要 —— 运行前就要定
Cluster shapeCluster का आकार簇的形状Depends on linkage (single can follow curves)Linkage पर निर्भर (single curves के साथ चल सकता है)取决于连接方式(单连接能跟随曲线)Round, similar spreadगोल, एक जैसा फैलाव圆形、分散程度相近
ScalabilityScalability可扩展性O(n²) memory — tens of thousands of rowsO(n²) memory — दसियों हज़ार rowsO(n²) 内存 —— 几万行O(n·K·t) — millions of rowsO(n·K·t) — लाखों rowsO(n·K·t) —— 数百万行
Same result every run?हर run में वही नतीजा?每次结果都一样?Yes (no random start)हाँ (कोई random शुरुआत नहीं)是(没有随机初始化)Only with a fixed random_stateसिर्फ़ तय random_state के साथ只有固定 random_state 时才是
Handles outliersOutliers संभालना处理离群点Depends on linkageLinkage पर निर्भर取决于连接方式Centroids get pulledCentroids खिंच जाते हैं质心会被拉偏
Easy to explainसमझाना आसान易于解释Very — the tree tells the storyबहुत — पेड़ कहानी बताता है非常 —— 树本身就在讲故事Moderateठीक-ठाक一般
Best useसबसे अच्छा इस्तेमाल最佳用途Exploration, biology, small/medium dataExploration, biology, छोटा/मध्यम data探索分析、生物学、中小数据Large data, K roughly knownबड़ा data, K का अंदाज़ा पता大数据、大致知道 K
🏆
The Practitioner's Decision RulePractitioner का फ़ैसला-नियम实践者决策法则

Use hierarchical clustering when the data has up to a few tens of thousands of rows, you do not know K, you want an explainable result, or you need to show a tree to stakeholders. Use K-Means when the data is large, K is roughly known, and speed matters more than the tree. A common workflow: run hierarchical clustering on a sample to choose K, then run K-Means on the full data with that K.

Hierarchical clustering तब इस्तेमाल करें जब data में कुछ दसियों हज़ार rows तक हों, K पता न हो, समझाने लायक नतीजा चाहिए, या stakeholders को पेड़ दिखाना हो। K-Means तब इस्तेमाल करें जब data बड़ा हो, K का अंदाज़ा हो, और पेड़ से ज़्यादा speed ज़रूरी हो। एक आम workflow: K चुनने के लिए एक sample पर hierarchical clustering चलाएँ, फिर उसी K से पूरे data पर K-Means चलाएँ।

当数据不超过几万行、不知道 K、需要可解释的结果,或要向相关人员展示树形结构时,用层次聚类。 当数据量大、大致知道 K、速度比树更重要时,用 K-Means。 常见流程:先在样本上运行层次聚类确定 K,再用这个 K 在全量数据上运行 K-Means。


SectionSection第 12 节

Common Pitfalls and How to Avoid Themआम ग़लतियाँ और उनसे कैसे बचें常见陷阱及规避方法

🚫 Hierarchical Clustering — Pitfalls & FixesHierarchical Clustering — ग़लतियाँ & उपाय层次聚类 — 陷阱与对策
1
Forgetting to scale features. A salary column (20K–200K) will completely hide a satisfaction score (1–5). Run StandardScaler or MinMaxScaler first.
Features scale करना भूल जाना। Salary column (20K–200K) satisfaction score (1–5) को पूरी तरह छिपा देगा। पहले StandardScaler या MinMaxScaler चलाएँ।
忘记缩放特征。工资列(2 万–20 万)会完全掩盖满意度评分(1–5)。先运行 StandardScaler 或 MinMaxScaler。
2
Using Ward linkage with a non-Euclidean distance. Ward only makes sense with Euclidean distance. For cosine, Manhattan or correlation distance use linkage="average" or "complete".
Non-Euclidean distance के साथ Ward linkage. Ward सिर्फ़ Euclidean distance के साथ सही है। Cosine, Manhattan या correlation distance के लिए linkage="average" या "complete" इस्तेमाल करें।
在非欧氏距离上使用 Ward 连接。Ward 只适用于欧氏距离。余弦、曼哈顿或相关距离请用 linkage="average" 或 "complete"。
3
Ignoring noise and outliers. With single linkage, a few noise points lying between two groups act as a bridge and chain them together; with single or complete linkage, a far outlier can take a whole cluster for itself. Remove or flag outliers first (for example with DBSCAN or a z-score check).
Noise और outliers को अनदेखा करना। Single linkage में दो groups के बीच पड़े कुछ noise points पुल बनकर उन्हें chain कर देते हैं; single या complete linkage में एक दूर का outlier पूरा cluster अपने लिए ले सकता है। पहले outliers हटाएँ या चिह्नित करें (जैसे DBSCAN या z-score से)।
忽视噪声和离群点。用单连接时,两组之间的几个噪声点会充当“桥”把它们串在一起;用单连接或全连接时,一个远处的离群点可能独占一整个簇。先删除或标记离群点(比如用 DBSCAN 或 z 分数检查)。
4
Clustering raw high-dimensional data. In very many dimensions, distances become similar ("curse of dimensionality"). Reduce with PCA first (keep ~80–90% of the variance), then cluster.
कच्चे high-dimensional data को cluster करना। बहुत ज़्यादा dimensions में दूरियाँ एक जैसी हो जाती हैं ("curse of dimensionality")। पहले PCA से घटाएँ (~80–90% variance रखें), फिर cluster करें।
直接对高维原始数据聚类。维度很多时,距离会变得差不多(“维度灾难”)。先用 PCA 降维(保留约 80–90% 方差),再聚类。
5
Counting branches by eye. Do not just "count the bumps". Use the biggest-gap rule and the silhouette score to choose the cut.
आँख से शाखाएँ गिनना। सिर्फ़ "उभार गिनने" से काम नहीं चलेगा। Cut चुनने के लिए सबसे बड़े gap वाला नियम और silhouette score इस्तेमाल करें।
靠目测数分支。不要只是“数鼓包”。用最大间隙法则和轮廓系数来选择切割位置。
6
Running it on very large data. Above a few tens of thousands of rows, the O(n²) memory will run out (see the calculator in Section 08). Use Mini-Batch K-Means or BIRCH, or pass a sparse connectivity graph to scikit-learn.
बहुत बड़े data पर चलाना। कुछ दसियों हज़ार rows से ऊपर O(n²) memory ख़त्म हो जाएगी (Section 08 का calculator देखें)। Mini-Batch K-Means या BIRCH इस्तेमाल करें, या scikit-learn को sparse connectivity graph दें।
在超大数据上运行。超过几万行,O(n²) 的内存就会耗尽(见第 08 节的计算器)。改用 Mini-Batch K-Means 或 BIRCH,或给 scikit-learn 传入稀疏的 connectivity 图。

Case Study 01Case Study 01案例 01

🏪 Customer Segmentation for a Retail BankRetail Bank के लिए Customer Segmentation零售银行的客户分群

Segmenting 800 Customers by Financial Behaviour800 Customers को Financial Behaviour से बाँटना按金融行为对 800 位客户分群
A mid-size retail bank wants to segment its 800 retail customers to design personalised product offers. There are no predefined segments — the bank wants the data to show the natural groups. Features: age, annual income, credit score, number of products held, and monthly transaction count.

Goal: find natural customer segments with hierarchical clustering so the marketing team can tailor loans, savings products and digital-banking upgrades to each segment.
एक मध्यम आकार का retail bank अपने 800 retail customers को segments में बाँटना चाहता है ताकि personalised product offers बना सके। कोई पहले से तय segment नहीं — bank चाहता है कि data स्वाभाविक groups दिखाए। Features: age, annual income, credit score, कितने products हैं, और हर महीने के transactions.

लक्ष्य: hierarchical clustering से स्वाभाविक customer segments खोजना ताकि marketing team हर segment के लिए loans, savings products और digital-banking upgrades तैयार कर सके।
一家中型零售银行希望把 800 位零售客户分群,以设计个性化产品方案。没有预设的客户群 —— 银行希望让数据自己展示自然分组。 特征:年龄、年收入、信用分、持有产品数和每月交易次数。

目标:用层次聚类找出自然的客户群,让市场团队为每个群体定制贷款、储蓄产品和数字银行升级方案。
ℹ️
About the DataData के बारे में关于数据

Real bank data is private, so we simulate it — but with 4 hidden customer types built in. If every column is generated independently at random (a common shortcut), there are no real segments; the silhouette stays near 0.1–0.2 and any "profiles" you print are just noise. The algorithm is never told the types.

असली bank data private होता है, इसलिए हम उसे simulate करते हैं — पर उसमें 4 छिपे customer types रखकर। अगर हर column अलग-अलग random बनाया जाए (एक आम shortcut), तो कोई असली segment नहीं होता; silhouette 0.1–0.2 के आसपास रहता है और जो भी "profiles" छापें वे सिर्फ़ noise हैं। Algorithm को types कभी नहीं बताए जाते।

真实银行数据是隐私数据,所以我们用模拟数据 —— 但其中内置了 4 种隐藏的客户类型。如果每一列都独立随机生成(常见的偷懒做法),就不存在真正的客户群;轮廓系数只有 0.1–0.2 左右,打印出来的“画像”只是噪声。算法从不知道这些类型。

Step 1 — Load and ExploreStep 1 — Load करें और देखें第 1 步 — 加载并查看

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)

# Simulated bank customers from 4 hidden behaviour types.
# (Real data would come from the bank; the algorithm never sees 'types'.)
types = {          #  age  income  credit  products  monthly_txns  count
    'professional': (45,  85000,   745,     4,        55,          180),
    'budget':       (42,  32000,   600,     2,        20,          220),
    'digital':      (29,  52000,   690,     3,        75,          200),
    'pre_retire':   (60,  50000,   665,     2,        14,          200),
}
parts = []
for name, (age, inc, cred, prod, txn, m) in types.items():
    parts.append(pd.DataFrame({
        'age':           rng.normal(age, 4, m).round().clip(21, 75),
        'annual_income': rng.normal(inc, inc * 0.12, m).round(-2),
        'credit_score':  rng.normal(cred, 25, m).round().clip(300, 850),
        'num_products':  rng.poisson(prod, m).clip(1, 8),
        'monthly_txns':  rng.normal(txn, 6, m).round().clip(1, None),
    }))
df = pd.concat(parts, ignore_index=True).sample(frac=1, random_state=42).reset_index(drop=True)

print(df.describe().round(1).loc[['count', 'mean', 'std', 'min', 'max']])
OUTPUT
age annual_income credit_score num_products monthly_txns count 800.0 800.0 800.0 800.0 800.0 mean 43.7 53173.2 671.8 2.7 40.3 std 11.5 20339.7 57.7 1.7 25.7 min 21.0 20300.0 535.0 1.0 1.0 max 71.0 114600.0 810.0 8.0 91.0

Step 2 — Preprocess and Choose KStep 2 — Preprocess करें और K चुनें第 2 步 — 预处理并选择 K

# Scale all features to zero mean, unit variance
scaler  = StandardScaler()
X_scaled = scaler.fit_transform(df)

# Build Ward linkage matrix
Z = linkage(X_scaled, method='ward')

# Test K from 2 to 8
results = []
for k in range(2, 9):
    labels = fcluster(Z, t=k, criterion='maxclust')
    sil    = silhouette_score(X_scaled, labels)
    results.append({'k': k, 'silhouette': round(sil, 4)})

best = max(results, key=lambda x: x['silhouette'])
print(f"{'K':>4}  {'Silhouette':>12}")
for r in results:
    star = ' ← BEST' if r['k'] == best['k'] else ''
    print(f"  {r['k']:>2}  {r['silhouette']:>12.4f}{star}")
OUTPUT
K Silhouette 2 0.4433 3 0.4532 4 0.4666 ← BEST 5 0.4554 6 0.4424 7 0.4200 8 0.3942

K = 4 has the highest silhouette (0.47), but K = 3 and 5 are close. That is normal for real customer data: the silhouette says "about 3–5 groups", and the dendrogram gap plus business sense pick the final K. A silhouette around 0.45 means real but overlapping groups.

K = 4 का silhouette सबसे ऊँचा है (0.47), पर K = 3 और 5 पास हैं। असली customer data में यह आम है: silhouette कहता है "लगभग 3–5 groups", और dendrogram gap व business की समझ आख़िरी K चुनते हैं। लगभग 0.45 का silhouette मतलब असली पर कुछ overlap वाले groups.

K = 4 的轮廓系数最高(0.47),但 K = 3 和 5 也很接近。这在真实客户数据中很常见:轮廓系数告诉你“大约 3–5 组”,再由树状图间隙和业务判断决定最终的 K。0.45 左右的轮廓系数意味着组是真实存在的,但有一定重叠。

Step 3 — Final Clustering (K = 4) and Segment ProfilesStep 3 — Final Clustering (K = 4) और Segment Profiles第 3 步 — 最终聚类(K = 4)与客户群画像

# Apply final model with K=4
hac = AgglomerativeClustering(n_clusters=4, linkage='ward')
df['segment'] = hac.fit_predict(X_scaled)

# Profile each segment with mean values
profile = df.groupby('segment').agg(
    count=('age', 'size'),
    avg_age=('age', 'mean'),
    avg_income=('annual_income', 'mean'),
    avg_credit=('credit_score', 'mean'),
    avg_products=('num_products', 'mean'),
    avg_txns=('monthly_txns', 'mean')
).round(1)

print(profile.to_string())
OUTPUT
count avg_age avg_income avg_credit avg_products avg_txns segment 0 180 44.8 85391.1 744.6 3.9 54.5 1 219 41.5 31392.2 599.7 2.1 20.4 2 200 29.2 51865.5 691.1 3.0 75.1 3 201 59.5 49354.2 665.8 2.1 14.6

Step 4 — Interpret and Name the SegmentsStep 4 — Segments समझें और नाम दें第 4 步 — 解读并命名客户群

SegmentSegment客户群Nameनाम名称ProfileProfile画像Recommended productsसुझाए गए products推荐产品
0High-Value ProfessionalsHigh-Value Professionals高价值专业人士Age ~45, income ~£85K, credit ~745, ~4 products, ~55 txns/monthAge ~45, income ~£85K, credit ~745, ~4 products, ~55 txns/महीना约 45 岁,收入约 £85K,信用分约 745,约 4 个产品,每月约 55 笔交易Premium cards, wealth management, mortgage top-upsPremium cards, wealth management, mortgage top-ups高端信用卡、财富管理、房贷加额
1Budget-Conscious AdultsBudget-Conscious Adults精打细算型Age ~42, income ~£31K, credit ~600, ~2 products, ~20 txns/monthAge ~42, income ~£31K, credit ~600, ~2 products, ~20 txns/महीना约 42 岁,收入约 £31K,信用分约 600,约 2 个产品,每月约 20 笔交易Savings accounts, budgeting tools, credit-builder productsSavings accounts, budgeting tools, credit-builder products储蓄账户、预算工具、信用修复类产品
2Digital-Native Young EarnersDigital-Native Young Earners数字原生年轻族Age ~29, income ~£52K, credit ~691, ~3 products, ~75 txns/monthAge ~29, income ~£52K, credit ~691, ~3 products, ~75 txns/महीना约 29 岁,收入约 £52K,信用分约 691,约 3 个产品,每月约 75 笔交易Mobile-app features, cashback cards, starter investmentsMobile-app features, cashback cards, starter investments手机银行功能、返现卡、入门投资产品
3Pre-Retirement, Low ActivityPre-Retirement, Low Activity临近退休、低活跃Age ~60, income ~£49K, credit ~666, ~2 products, ~15 txns/monthAge ~60, income ~£49K, credit ~666, ~2 products, ~15 txns/महीना约 60 岁,收入约 £49K,信用分约 666,约 2 个产品,每月约 15 笔交易Retirement savings, fixed deposits, low-fee accountsRetirement savings, fixed deposits, low-fee accounts养老储蓄、定期存款、低费率账户
🏪 SEGMENT PROFILES (EACH FEATURE SCALED 0–1 ACROSS SEGMENTS)SEGMENT PROFILES (हर FEATURE SEGMENTS में 0–1 पर SCALE)客户群画像(每个特征在各群之间缩放到 0–1)
Segment profiles AgeAge年龄 IncomeIncome收入 CreditCredit信用分 ProductsProducts产品数 Txns / monthTxns / महीना月交易数 0: High-Value Professionals0: High-Value Professionals0: 高价值专业人士 1: Budget-Conscious Adults1: Budget-Conscious Adults1: 精打细算型 2: Digital-Native Young Earners2: Digital-Native Young Earners2: 数字原生年轻族 3: Pre-Retirement, Low Activity3: Pre-Retirement, Low Activity3: 临近退休、低活跃

Built from the real output above. Segment 0 leads on income, credit and products; segment 2 leads on transactions; segment 3 is the oldest and least active.

ऊपर के असली output से बना। Segment 0 income, credit और products में आगे है; segment 2 transactions में; segment 3 सबसे उम्रदराज़ और सबसे कम active है।

根据上面的真实输出绘制。客户群 0 在收入、信用分和产品数上领先;客户群 2 在交易次数上领先;客户群 3 年龄最大、最不活跃。

🌟
Case Study 01 — Key TakeawaysCase Study 01 — मुख्य बातें案例 01 — 要点

Ward linkage on scaled features recovered the 4 customer types almost exactly (segment sizes 180 / 219 / 200 / 201 vs the true 180 / 220 / 200 / 200). The silhouette pointed to K = 4, but only narrowly — so the final choice also used the business story. Each segment now has a clear profile the bank can act on.

Scaled features पर Ward linkage ने 4 customer types लगभग बिल्कुल सही पकड़ लिए (segment sizes 180 / 219 / 200 / 201, असली 180 / 220 / 200 / 200)। Silhouette ने K = 4 बताया, पर थोड़े ही अंतर से — इसलिए आख़िरी फ़ैसले में business की कहानी भी देखी गई। अब हर segment का साफ़ profile है जिस पर bank काम कर सकता है।

在缩放后的特征上使用 Ward 连接,几乎完全还原了 4 种客户类型(各群大小 180 / 219 / 200 / 201,真实为 180 / 220 / 200 / 200)。 轮廓系数指向 K = 4,但优势很小 —— 所以最终决定还参考了业务逻辑。现在每个客户群都有了银行可以据此行动的清晰画像。


Case Study 02Case Study 02案例 02

🧬 Gene Expression Clustering in BioinformaticsBioinformatics में Gene Expression Clustering生物信息学中的基因表达聚类

Discovering Co-expressed Gene Familiesसाथ-साथ Express होने वाले Gene Families खोजना发现共表达的基因家族
A bioinformatics lab measures the expression of 50 genes on 8 days (D0 to D28) after a treatment. Genes that are co-expressed — rising and falling together — often work in the same biological pathway.

Goal: find groups of co-expressed genes with hierarchical clustering, using average linkage and correlation distance, and show them as a clustered heatmap — the standard picture in genomics.
एक bioinformatics lab किसी treatment के बाद 8 दिनों (D0 से D28) पर 50 genes का expression मापती है। जो genes co-expressed हैं — साथ-साथ बढ़ते और घटते हैं — वे अक्सर एक ही biological pathway में काम करते हैं।

लक्ष्य: average linkage और correlation distance के साथ hierarchical clustering से co-expressed genes के groups खोजना, और उन्हें clustered heatmap के रूप में दिखाना — genomics की standard तस्वीर।
一个生物信息学实验室在某种处理后的 8 个时间点(D0 到 D28)测量了 50 个基因的表达量。共表达的基因 —— 同升同降 —— 往往参与同一条生物通路。

目标:用平均连接和相关距离做层次聚类,找出共表达的基因组,并以聚类热图展示 —— 这是基因组学中的标准图。
🧬
Why Correlation Distance in Genomics?Genomics में Correlation Distance क्यों?为什么基因组学用相关距离?

Two genes can follow the same up-and-down pattern while one is simply "louder" (higher numbers). What matters biologically is the shape: do they rise and fall together? Correlation distance = 1 − Pearson r. 0 = same shape, 1 = unrelated, 2 = exact opposite. The simulator below shows what goes wrong with Euclidean distance.

दो genes एक ही ऊपर-नीचे वाले pattern पर चल सकते हैं जबकि एक बस "तेज़" हो (बड़े numbers)। Biology में आकार मायने रखता है: क्या वे साथ बढ़ते-घटते हैं? Correlation distance = 1 − Pearson r. 0 = वही आकार, 1 = कोई संबंध नहीं, 2 = बिल्कुल उल्टा। नीचे का simulator दिखाता है कि Euclidean distance से क्या गड़बड़ होती है।

两个基因可以遵循同样的升降模式,而其中一个只是“更响”(数值更大)。生物学上重要的是形状:它们是否同升同降? 相关距离 = 1 − Pearson r。0 = 形状相同,1 = 无关,2 = 完全相反。下面的模拟器展示了用欧氏距离会出什么问题。

LIVELIVE互动Clustered Heatmap — Euclidean vs Correlation DistanceClustered Heatmap — Euclidean vs Correlation Distance聚类热图 — 欧氏距离 vs 相关距离

Each row is a gene, each column a day; colour = expression. The left strip shows the true pattern of each gene, the right strip the group found (average linkage, cut into 3). Some genes are louder than others on purpose.

हर row एक gene है, हर column एक दिन; रंग = expression. बाईं पट्टी हर gene का असली pattern दिखाती है, दाईं पट्टी मिला हुआ group (average linkage, 3 में काटा)। कुछ genes जान-बूझकर बाकियों से तेज़ हैं।

每行是一个基因,每列是一天;颜色 = 表达量。左边的色条是每个基因的真实模式,右边的色条是找到的组(平均连接,切成 3 组)。有些基因被故意设置得比其他基因“更响”。

Genes in the right groupसही group में genes分对组的基因
—

Step 1 — Simulate Gene Expression DataStep 1 — Gene Expression Data simulate करें第 1 步 — 模拟基因表达数据

import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from scipy.spatial.distance   import pdist, squareform
from sklearn.metrics           import silhouette_score
import matplotlib.pyplot       as plt
import seaborn                  as sns

np.random.seed(99)

conditions = ['D0', 'D1', 'D2', 'D4', 'D7', 'D14', 'D21', 'D28']

# Create 3 co-expression groups of ~17 genes each
# Group A: genes that peak early then drop off
base_A = np.array([3.0, 5.2, 7.8, 9.1, 6.4, 3.5, 1.8, 1.2])
# Group B: genes that rise late and stay high
base_B = np.array([1.0, 1.2, 1.5, 4.8, 6.2, 7.1, 7.4, 7.9])
# Group C: genes that are switched off step by step
base_C = np.array([8.5, 7.2, 5.1, 3.3, 2.1, 1.5, 1.0, 0.8])

rows = []
for i in range(17):
    rows.append(base_A + np.random.normal(0, 0.4, 8))
for i in range(17):
    rows.append(base_B + np.random.normal(0, 0.4, 8))
for i in range(16):
    rows.append(base_C + np.random.normal(0, 0.4, 8))

gene_names = [f"GENE_{i+1:02d}" for i in range(50)]
expr = pd.DataFrame(rows, index=gene_names, columns=conditions)

print("Expression matrix shape:", expr.shape)
print(expr.head(3).round(2))
OUTPUT
Expression matrix shape: (50, 8) D0 D1 D2 D4 D7 D14 D21 D28 GENE_01 2.94 6.02 7.91 9.63 6.34 3.47 2.10 1.53 GENE_02 2.95 4.25 7.73 9.37 6.41 3.68 1.91 0.63 GENE_03 3.35 4.97 7.60 9.34 6.11 3.60 1.46 1.12

Step 2 — Correlation Distance MatrixStep 2 — Correlation Distance Matrix第 2 步 — 相关距离矩阵

# 1 − Pearson correlation as distance between genes
corr_dist = pdist(expr.values, metric='correlation')
corr_matrix = squareform(corr_dist)

print("Distance matrix shape:", corr_matrix.shape)
print(f"Min dist: {corr_dist.min():.4f}  |  Max dist: {corr_dist.max():.4f}")
print(f"Median dist: {np.median(corr_dist):.4f}")
OUTPUT
Distance matrix shape: (50, 50) Min dist: 0.0018 | Max dist: 1.9852 Median dist: 0.8040

Step 3 — Cluster Genes with Average LinkageStep 3 — Average Linkage से Genes cluster करें第 3 步 — 用平均连接对基因聚类

# Average linkage on precomputed correlation distances
Z_genes = linkage(corr_dist, method='average')

# Find optimal K via silhouette
best_k, best_sil = 2, -1
for k in range(2, 8):
    labels = fcluster(Z_genes, t=k, criterion='maxclust')
    sil    = silhouette_score(corr_matrix, labels, metric='precomputed')
    if sil > best_sil:
        best_k, best_sil = k, sil
    print(f"  K={k}  silhouette={sil:.4f}")

print(f"\nOptimal K = {best_k}  (silhouette = {best_sil:.4f})")

# Apply final clustering
gene_labels = fcluster(Z_genes, t=best_k, criterion='maxclust')
expr['cluster'] = gene_labels
OUTPUT
K=2 silhouette=0.8410 K=3 silhouette=0.9819 K=4 silhouette=0.7907 K=5 silhouette=0.6029 K=6 silhouette=0.5849 K=7 silhouette=0.3791 Optimal K = 3 (silhouette = 0.9819)

Step 4 — Biological InterpretationStep 4 — Biological व्याख्या第 4 步 — 生物学解读

for c in sorted(expr['cluster'].unique()):
    genes_in = expr[expr['cluster'] == c].drop('cluster', axis=1)
    mean_expr = genes_in.mean()
    print(f"\n── Cluster {c}  ({len(genes_in)} genes) ──────────────")
    print("Mean expression per timepoint:")
    for cond, val in mean_expr.items():
        bar = '■' * int(val)
        print(f"  {cond:>4}: {bar:<12} {val:.2f}")
    print(f"  Genes: {', '.join(genes_in.index[:5].tolist())} ...")
# Picture: clustered heatmap with the same dendrogram on the rows
# sns.clustermap(expr.drop(columns="cluster"), row_linkage=Z_genes, col_cluster=False, cmap="viridis")
OUTPUT
── Cluster 1 (17 genes) ────────────── Mean expression per timepoint: D0: 0.98 D1: ■ 1.13 D2: ■ 1.44 D4: ■■■■ 4.65 D7: ■■■■■■ 6.17 D14: ■■■■■■■ 7.03 D21: ■■■■■■■ 7.41 D28: ■■■■■■■■ 8.05 Genes: GENE_18, GENE_19, GENE_20, GENE_21, GENE_22 ... ── Cluster 2 (17 genes) ────────────── Mean expression per timepoint: D0: ■■■ 3.17 D1: ■■■■■ 5.30 D2: ■■■■■■■ 7.97 D4: ■■■■■■■■■ 9.26 D7: ■■■■■■ 6.29 D14: ■■■ 3.61 D21: ■ 1.64 D28: ■ 1.21 Genes: GENE_01, GENE_02, GENE_03, GENE_04, GENE_05 ... ── Cluster 3 (16 genes) ────────────── Mean expression per timepoint: D0: ■■■■■■■■ 8.57 D1: ■■■■■■■ 7.15 D2: ■■■■■ 5.20 D4: ■■■ 3.24 D7: ■■ 2.27 D14: ■ 1.48 D21: ■ 1.02 D28: 0.88 Genes: GENE_35, GENE_36, GENE_37, GENE_38, GENE_39 ...

Note: fcluster numbers clusters 1, 2, 3 in its own order, so "Cluster 1" here is the late-rising group (genes 18–34), not genes 1–17. Always read the profile, never assume the number.

ध्यान दें: fcluster clusters को अपने क्रम में 1, 2, 3 number देता है, इसलिए यहाँ "Cluster 1" देर से बढ़ने वाला group है (genes 18–34), genes 1–17 नहीं। हमेशा profile पढ़ें, number पर भरोसा न करें।

注意:fcluster 按自己的顺序给簇编号 1、2、3,所以这里的“Cluster 1”是后期上升组(基因 18–34),而不是基因 1–17。一定要看画像,不要想当然地看编号。

ClusterCluster簇Expression patternExpression pattern表达模式Possible biological meaningसंभावित biological मतलब可能的生物学含义Next stepअगला कदम下一步
1 (17 genes)Late, sustained — low until D2, then rises and stays highदेर से, टिकाऊ — D2 तक कम, फिर बढ़कर ऊँचा रहता है后期持续型 —— D2 前很低,之后上升并保持高位Long-term adaptation; possible resistance pathwayलंबी अवधि का adaptation; संभावित resistance pathway长期适应;可能的耐药通路Monitor for resistanceResistance पर नज़र रखें监测耐药性
2 (17 genes)Early response — peaks at D4, then fallsशुरुआती प्रतिक्रिया — D4 पर peak, फिर गिरावट早期响应型 —— D4 达峰后下降Acute response to the treatmentTreatment पर तुरंत प्रतिक्रिया对处理的急性响应Check for acute toxicity markersAcute toxicity markers जाँचें检查急性毒性标志物
3 (16 genes)Switched off — high at D0, falls steadilyबंद होते हुए — D0 पर ऊँचा, लगातार गिरता逐渐关闭型 —— D0 很高,随后持续下降Genes suppressed by the treatmentTreatment से दबाए गए genes被处理抑制的基因Check for off-target suppressionOff-target suppression जाँचें检查脱靶抑制
🧬
Case Study 02 — Key TakeawaysCase Study 02 — मुख्य बातें案例 02 — 要点

Correlation distance with average linkage separated the 50 genes into 3 co-expression clusters with a silhouette of 0.98 — almost perfect, because the simulated patterns are very clean (real data is noisier). The interpretations above are hypotheses for the lab to test, not conclusions. This "clustered heatmap" workflow (for example seaborn.clustermap) is a standard tool for RNA-seq and microarray data.

Average linkage के साथ correlation distance ने 50 genes को 0.98 silhouette के साथ 3 co-expression clusters में बाँटा — लगभग perfect, क्योंकि simulated patterns बहुत साफ़ हैं (असली data में ज़्यादा noise होता है)। ऊपर की व्याख्याएँ lab के जाँचने के लिए hypotheses हैं, निष्कर्ष नहीं। यह "clustered heatmap" workflow (जैसे seaborn.clustermap) RNA-seq और microarray data का standard औज़ार है।

相关距离加平均连接,把 50 个基因分成了 3 个共表达簇,轮廓系数 0.98 —— 几乎完美,因为模拟的模式非常干净(真实数据噪声更大)。 上面的解读是供实验室验证的假设,而不是结论。这种“聚类热图”流程(例如 seaborn.clustermap)是 RNA-seq 和芯片数据分析的标准工具。


SectionSection第 13 节

scikit-learn API Quick Referencescikit-learn API Quick Referencescikit-learn API 速查

Run on the scaled bank data from Case Study 01:

Case Study 01 के scaled bank data पर चलाया गया:

在案例 01 缩放后的银行数据上运行:

from sklearn.cluster import AgglomerativeClustering

# Full parameter reference
model = AgglomerativeClustering(
    n_clusters=4,          # int or None (if distance_threshold used)
    metric='euclidean',    # 'euclidean','manhattan','cosine','precomputed'
    linkage='ward',        # 'ward','complete','average','single'
    distance_threshold=None, # set this instead of n_clusters to cut by distance
    connectivity=None,     # connectivity matrix (e.g. from kneighbors_graph)
    compute_full_tree='auto',# 'auto', True, False
    compute_distances=False  # set True if you need .distances_ attribute
)

labels = model.fit_predict(X_scaled)

# Useful post-fit attributes
print("n_clusters_ : ", model.n_clusters_)    # actual number of clusters
print("n_leaves_   : ", model.n_leaves_)      # number of leaves (= n samples)
print("n_connected_: ", model.n_connected_components_) # connectivity components
OUTPUT
n_clusters_ : 4 n_leaves_ : 800 n_connected_: 1
📌 Choosing Between scikit-learn and SciPyscikit-learn और SciPy में से चुनना在 scikit-learn 与 SciPy 之间选择
scikit-learn
AgglomerativeClustering — fits into Pipelines and returns flat labels. No dendrogram plot of its own (set compute_distances=True if you want to build one from children_ and distances_). AgglomerativeClustering — Pipelines में फ़िट होता है और flat labels लौटाता है। अपना dendrogram plot नहीं (अगर children_ और distances_ से बनाना हो तो compute_distances=True set करें)। AgglomerativeClustering —— 可放入 Pipeline,返回平铺的标签。自己不画树状图(如需用 children_ 和 distances_ 自行构建,设置 compute_distances=True)。
SciPy
linkage + dendrogram + fcluster — best for exploring. Gives the full merge history (Z), plots the dendrogram, and lets you try many cuts without re-running. linkage + dendrogram + fcluster — exploration के लिए सबसे अच्छा। पूरा merge इतिहास (Z) देता है, dendrogram plot करता है, और दोबारा चलाए बिना कई cuts आज़माने देता है। linkage + dendrogram + fcluster —— 最适合探索分析。给出完整合并历史(Z),能画树状图,不重新运行就能尝试多种切法。
Best practiceBest practice最佳实践
Explore with SciPy (dendrogram + silhouette) to choose K, then use scikit-learn for the final model in your pipeline. Note: AgglomerativeClustering has no predict() for new rows — to label new data, train a classifier on the cluster labels or assign new rows to the nearest cluster centre. SciPy से explore करें (dendrogram + silhouette) और K चुनें, फिर pipeline के final model के लिए scikit-learn इस्तेमाल करें। ध्यान दें: AgglomerativeClustering में नई rows के लिए predict() नहीं है — नए data को label देने के लिए cluster labels पर classifier train करें या नई rows को सबसे पास वाले cluster centre को दें। 先用 SciPy 探索(树状图 + 轮廓系数)确定 K,再在流水线中用 scikit-learn 作为最终模型。注意:AgglomerativeClustering 没有针对新数据的 predict() —— 要给新数据打标签,可以用簇标签训练一个分类器,或把新数据分给最近的簇中心。

SectionSection第 14 节

Golden Rules — Hierarchical ClusteringGolden Rules — Hierarchical Clustering黄金法则 — 层次聚类

🌲 Non-Negotiable Rules for Hierarchical ClusteringHierarchical Clustering के ज़रूरी नियम层次聚类必须遵守的规则
1
Always scale features first. Run StandardScaler before computing distances. Unscaled features let large-range columns control the result — the cause of most "bad" clusterings.
हमेशा पहले features scale करें। दूरियाँ निकालने से पहले StandardScaler चलाएँ। बिना scale के बड़ी range वाले columns नतीजे पर कब्ज़ा कर लेते हैं — ज़्यादातर "ख़राब" clusterings की यही वजह है।
永远先缩放特征。计算距离前运行 StandardScaler。不缩放,取值范围大的列就会主导结果 —— 大多数“糟糕”聚类都源于此。
2
Default to Ward linkage with Euclidean distance for most tabular data. Switch only for a reason: average linkage for correlation or cosine distance, single linkage for curved shapes with clear gaps.
ज़्यादातर tabular data के लिए default में Euclidean distance के साथ Ward linkage लें। सिर्फ़ किसी वजह से बदलें: correlation या cosine distance के लिए average linkage, साफ़ gaps वाले मुड़े आकारों के लिए single linkage.
大多数表格数据默认使用 Ward 连接 + 欧氏距离。只有在有理由时才更换:相关或余弦距离用平均连接,间隙清晰的弯曲形状用单连接。
3
Always plot the dendrogram before choosing K. Look for the biggest gap first, then confirm with the silhouette score for K = 2 to 10.
K चुनने से पहले हमेशा dendrogram plot करें। पहले सबसे बड़ा gap देखें, फिर K = 2 से 10 के silhouette score से पुष्टि करें।
选择 K 之前一定要画树状图。先找最大间隙,再用 K = 2 到 10 的轮廓系数确认。
4
Use correlation distance for profile data. In genomics, finance and sensor data the shape of the signal matters, not its size. Use pdist(X, metric="correlation") with linkage(..., method="average").
Profile data के लिए correlation distance इस्तेमाल करें। Genomics, finance और sensor data में signal का आकार मायने रखता है, उसका size नहीं। pdist(X, metric="correlation") को linkage(..., method="average") के साथ इस्तेमाल करें।
曲线类数据用相关距离。在基因组学、金融和传感器数据中,重要的是信号的形状而不是大小。使用 pdist(X, metric="correlation") 配合 linkage(..., method="average")。
5
Never cluster raw text or raw categories. Turn text into TF-IDF vectors (then use cosine distance with average linkage), and one-hot encode categories, before clustering.
कच्चे text या कच्ची categories को कभी cluster न करें। Clustering से पहले text को TF-IDF vectors में बदलें (फिर average linkage के साथ cosine distance), और categories को one-hot encode करें।
永远不要直接对原始文本或原始类别聚类。聚类前先把文本转成 TF-IDF 向量(然后用余弦距离 + 平均连接),并对类别做 one-hot 编码。
6
For large data, change strategy. Above a few tens of thousands of rows, cluster a random sample of 5,000–10,000 rows to choose K and understand the structure, then run K-Means on the full data, starting from the sample's cluster centres.
बड़े data के लिए तरीका बदलें। कुछ दसियों हज़ार rows से ऊपर, K चुनने और ढाँचा समझने के लिए 5,000–10,000 rows का random sample cluster करें, फिर sample के cluster centres से शुरू करके पूरे data पर K-Means चलाएँ।
大数据要换策略。超过几万行时,先对 5,000–10,000 行的随机样本聚类,确定 K 并理解结构,然后以样本得到的簇中心为起点,在全量数据上运行 K-Means。
7
Report quality numbers next to the business story. A silhouette and a Davies-Bouldin index give objective evidence that the clusters are real. Be honest when they are modest (like 0.47 in Case Study 01).
Business कहानी के साथ quality numbers भी बताएँ। Silhouette और Davies-Bouldin index इस बात का objective सबूत देते हैं कि clusters असली हैं। जब वे साधारण हों (जैसे Case Study 01 में 0.47) तो ईमानदारी से बताएँ।
在业务故事旁边报告质量指标。轮廓系数和 Davies-Bouldin 指数是簇真实存在的客观证据。指标一般时(如案例 01 的 0.47)要如实说明。
You have completed Unsupervised Learning. View all sections →