Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Unsupervised Learning – Clustering

Unsupervised Learning - Clustering

Imagine you walk into a huge library where all the books are piled on the floor in a chaotic mess. Your task is not to read every book (that would take too much time), but to sort them into piles based on their topics — for example: science fiction, historical biographies, cooking recipes. In this process, you don't have a ready-made classification list telling you which category each book belongs to; you rely entirely on features such as the book's content, cover, and thickness,spontaneouslydiscovering these groups.

In machine learning,Clustering does exactly the same thing. It is aUnsupervised learningmethod whose goal is to discover the inherent structure and groupings in data that has not been pre-labeled with answers (that is, without "labels").


What are unsupervised learning and clustering?

Before we begin, let's quickly distinguish the two major paradigms of machine learning:

The core idea of clustering: Divide the samples in a dataset into severalmutually disjointsubsets (called clusters or groups), so that samples within the same cluster aresimilarto each other, while samples in different clusters aredissimilar。

Here, similarity is usually measured mathematically bydistance(such as Euclidean distance).

The closer the distance, the higher the similarity.


Classic clustering algorithm: K-Means

K-Means is one of the most famous and widely used clustering algorithms; its idea is intuitive and its implementation is relatively simple.

Algorithm principles and steps

We can imagine the K-Means process as electing representatives and redrawing districts:

  1. Determine the number of clusters K: First, you need to decide how many classes you want to divide the data into. This value K must be specified in advance; it is a key parameter of K-Means.
  2. Initialize the representatives (centroids): Randomly select K points in the data space as the initial "center points" of each cluster, which we callcentroids。
  3. Assign residents (samples): Calculate the distance from each sample point in the dataset to the K centroids. Following the principle of "nearer ones belong together," assign each sample to the cluster whose centroid isclosestto it. In this way, all samples are divided into K clusters.
  4. Re-elect new representatives (update centroids): Now each cluster has a batch of samples. Recompute the centroid of each cluster; the new centroid is theMean(mean point) of all sample points in that cluster.
  5. Iteration and convergence: Repeat steps 3 (assignment) and 4 (update) until the centroid positions no longer change significantly (that is, the algorithm has converged). At this point, the cluster assignment of each sample no longer changes.

Code Examples and Practice

Let's use Python's scikit-learn library and a simple dataset to demonstrate K-Means.

Example

Import the necessary libraries

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

make_blobs

from

sklearn.

cluster

import

KMeans

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

1. Create an artificial dataset

We generate 300 sample points that naturally cluster around 4 centers (for easy observation)

X

,

y_true

=

make_blobs

(

n_samples

=

300

,

centers

=

4

,

cluster_std

=

0.60

,

random_state

=

0

)

X is the feature data, and y_true is the true class label (only used for the final comparison; the clustering algorithm does not use it)

2. Visualize the raw data

plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

s

=

50

)

s is the point size

plt.

title

(

"Raw unlabeled data"

)

plt.

show

(

)

3. Apply K-Means clustering

Specify 4 clusters

kmeans

=

KMeans

(

n_clusters

=

4

,

random_state

=

0

,

n_init

=

'auto'

)

Fit the model and predict the cluster label for each sample

y_kmeans

=

kmeans.

fit_predict

(

X

)

4. Get the centroid coordinates

centroids

=

kmeans.

cluster_centers_

5. Visualize the clustering result

plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

c

=

y_kmeans

,

s

=

50

,

cmap

=

'viridis'

)

Use different colors to mark sample points from different clusters

plt.

scatter

(

centroids

[

:

,

0

]

,

centroids

[

:

,

1

]

,

c

=

'red'

,

s

=

200

,

alpha

=

0.8

,

marker

=

'X'

)

Mark the centroid positions with large red crosses; alpha is the transparency

plt.

title

(

"K-Means clustering result (K=4)"

)

plt.

show

(

)

Print the predicted cluster labels of the first 10 samples

print

(

"Cluster labels of the first 10 samples:"

,

y_kmeans

[

:

10

]

)

Print the centroid coordinates

print

(

"Centroid coordinates of the four clusters:\n"

,

centroids

)

Code Analysis:

Run this code, and you will see two plots. The first is a chaotic mess of points, while the second is clearly divided into four colored groups with red X marks at the centers. This is the magic of K-Means!

前10个样本的簇标签: [1 2 0 2 1 1 3 0 2 2]

Centroid coordinates of four clusters:

 [[ 0.94973532  4.41906906]

 [ 1.98258281  0.86771314]

 [-1.37324398  7.75368871]

 [-1.58438467  2.83081263]]

Raw unlabeled data:

K-Means clustering result:


How to choose the best K value?

In the example above, because we knew the data was generated around 4 centers, we easily set K=4. But in the real world, we often don't know how many classes the data should be divided into. How do we choose K?

A commonly used method is "the elbow method". The idea is: as the number of clusters K increases, the average distance from each sample point to its cluster's centroid (calleddistortionor inertia) decreases. When K is less than the true number of clusters, increasing K greatly reduces this distance; once K reaches the true number of clusters, further increasing K causes the reduction to drop sharply. This inflection point is like the joint of an elbow, and the corresponding K value is a good choice.

Example

Elbow method example: Calculate inertia for different K values

inertias

=

[

]

K_range

=

range

(

1

,

11

)

Test K from 1 to 10

for

k

in

K_range:

    kmeans

=

KMeans

(

n_clusters

=

k

,

random_state

=

0

,

n_init

=

'auto'

)

    kmeans.

fit

(

X

)

    inertias.

append

(

kmeans.

inertia_

)

The inertia_ attribute is the SSE

Plot the elbow curve

plt.

plot

(

K_range

,

inertias

,

'bo-'

)

plt.

xlabel

(

'Number of clusters K'

)

plt.

ylabel

(

'Inertia (SSE)'

)

plt.

title

(

'Using the elbow method to find the best K value'

)

plt.

axvline

(

x

=

4

,

color

=

'r'

,

linestyle

=

'--'

,

alpha

=

0.5

)

Mark the K=4 we already know

plt.

show

(

)

Looking at the generated curve, you will find that near K=4, the curve's decline slows markedly, forming an "elbow," which suggests that K=4 is a reasonable choice.


Applications of clustering

Clustering is a powerful exploratory data analysis tool with extremely wide applications:

  1. Customer segmentation: In e-commerce or marketing, cluster customers based on their purchasing behavior and demographics, dividing them into groups such as "high-value customers" and "price-sensitive customers" to implement precision marketing.
  2. Image segmentation: Cluster pixels in an image based on color and texture, which can be used to simplify images and identify foreground and background.
  3. Anomaly detection: Normal data points usually form dense clusters, while outliers are far from the center of any cluster. Clustering can be used to discover these outliers.
  4. Document categorization: Cluster news articles or research papers to automatically discover hot topics or research areas.
  5. Social network analysis: In social networks, by clustering users' relationships and interactions, we can discover communities or circles.

Practical exercises and summary

Exercise 1: Try different K values Modify the n_clusters parameter in the K-Means example code above, setting it to 2, 3, 5, and 8 respectively. Observe the clustering result plots and feel the impact of K value selection on the results.

Exercise 2: Use a real dataset Try using scikit-learn built-in iris(Iris) dataset for clustering. Although this dataset is usually used for classification, you can ignore its labels and use only the feature data (sepal and petal length and width) for K-Means clustering, then compare the clustering results with the true labels to see how it turns out.

Example

from

sklearn

import

datasets

iris

=

datasets.

load_iris

(

)

X_iris

=

iris.

data

Using feature data only