Velamuvi AIAcademy

Lesson 1 of 8 · No Labels

What Is Unsupervised Learning?

What unsupervised learning finds in unlabelled data: groups, structure, compression and outliers, why results are hard to judge, and the scikit-learn workflow.

  • 18 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what learning without labels means, and the kinds of structure it can still find
  • Compare unsupervised and supervised learning: data, goal, code and checking
  • Explain why unsupervised results are hard to evaluate, and how to check them anyway
  • Name real uses of clustering, dimensionality reduction and anomaly detection
  • Follow the scikit-learn workflow: scale first, then fit, transform, fit_predict and predict

The idea in plain words

In supervised learning, every training example came with the right answer, the label y, and training meant finding a rule that reproduces those answers. In unsupervised learning you have only the features X. There is no answer to copy, so the goal changes. Instead of predicting a known target, you look for structure in the data itself: which examples resemble each other, which features move together, and which examples don't fit in.

Most data in the world has no labels: website logs, purchase histories, sensor readings, photos, documents. Labels cost time and money, as you saw in Learning From Labels, while unlabelled data piles up for free. Unsupervised learning is how you make sense of it, and it often comes first in a project, before anyone knows what to predict.

You met a tiny example in Types of Machine Learning, where a loop split monthly spending into small and big spenders. This course turns that idea into a toolkit:

PartLessons
No LabelsWhat unsupervised learning is, clustering, dimensionality reduction
TechniquesPrincipal component analysis, t-SNE and UMAP, anomaly detection, association rules
ProjectSegmenting customers from their shopping data

What you can learn without labels

Without labels, you can still ask the data four kinds of question, plus one about things that happen together:

You look forThe questionMain methodsExample
Groups (clustering)Which examples are similar to each other?k-means, hierarchical clustering, DBSCANCustomer segments, topics in news articles
StructureWhich features move together, and how many numbers really describe an example?PCA, t-SNE, UMAPA 2-D map of documents, each described by hundreds of numbers
CompressionCan each example be stored in fewer numbers and rebuilt closely?PCA, autoencodersSmaller images and sensor logs
Outliers (anomaly detection)Which examples don't fit the usual pattern?Isolation forest, distance to the nearest groupCard fraud, a failing machine
AssociationsWhich things tend to happen together?Association rulesShoppers who buy pasta often buy sauce

Finding structure and compressing are two sides of dimensionality reduction: describing each example with fewer numbers. The next three sections show groups, structure, compression and outliers on one small set of customers.

Groups: customers nobody labelled

A shop records two numbers for each of 150 customers: visits per month and monthly spend. Nobody has said which customers are which kind. Ask k-means, the most common clustering method, to split them into three groups. The StandardScaler in front puts both features on a similar scale first; the workflow section explains why.

Try it yourselfPython
import numpy as np
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
# 150 customers, two features each. Nobody has labelled them.
visits = np.concatenate([rng.normal(2, 0.6, 60), rng.normal(8, 1.5, 50), rng.normal(4, 1, 40)])
spend = np.concatenate([rng.normal(40, 10, 60), rng.normal(120, 25, 50), rng.normal(400, 60, 40)])
X = np.column_stack([visits, spend])       # one row per customer

model = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=0))
groups = model.fit_predict(X)              # a group number for every customer

for g in range(3):
    members = X[groups == g]
    print(f"group {g}: {len(members):>2} customers, "
          f"{members[:, 0].mean():.1f} visits and {members[:, 1].mean():.0f} spent a month on average")
Output
group 0: 48 customers, 8.2 visits and 119 spent a month on average
group 1: 61 customers, 2.1 visits and 40 spent a month on average
group 2: 41 customers, 4.1 visits and 377 spent a month on average

The program saw only two numbers per customer. It was never told that this shop has occasional shoppers, regulars and big spenders, yet the three groups it found fit that description: one group visits about twice a month and spends little, one visits often, and one visits now and then but spends a lot. (The data was generated with groups of 60, 50 and 40, so a few customers on the borders ended up in a neighbouring group.) The group numbers 0, 1 and 2 are only names. Another run could number the same groups differently. Giving a group its meaning, such as "regulars", is your job, by looking at what its members have in common.

Structure and compression: fewer numbers per customer

Suppose the shop also records minutes spent on its website and items bought. That makes four features, but minutes mostly follow visits, and items mostly follow spend. Principal component analysis (PCA) finds new directions in the data and measures how much of the variation lies along each one:

Try it yourselfPython
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
visits = np.concatenate([rng.normal(2, 0.6, 60), rng.normal(8, 1.5, 50), rng.normal(4, 1, 40)])
spend = np.concatenate([rng.normal(40, 10, 60), rng.normal(120, 25, 50), rng.normal(400, 60, 40)])
minutes = visits * 6 + rng.normal(0, 2, 150)        # time on the website: moves with visits
items = spend / 15 + rng.normal(0, 1, 150)          # items bought: moves with spend
X = np.column_stack([visits, spend, minutes, items])

X_scaled = StandardScaler().fit_transform(X)
pca = PCA().fit(X_scaled)
shares = pca.explained_variance_ratio_
print("share of the variation along each new direction:", np.round(shares, 3))
print(f"keeping 2 of 4 numbers per customer keeps {shares[:2].sum():.1%} of it")
Output
share of the variation along each new direction: [0.558 0.439 0.002 0.001]
keeping 2 of 4 numbers per customer keeps 99.7% of it

Almost all the variation lies along two directions. That is structure: these four columns really describe two hidden factors, how often a customer comes and how much they spend. It is also compression: store two numbers per customer instead of four and you lose only 0.3% of the variation. The Principal Component Analysis lesson shows how these directions are found and how to rebuild the original columns from them.

Outliers: customers who fit no group

Once you know the groups, an unusual customer is one that is far from all of them. Add three odd customers to the shop and measure each customer's distance to the nearest group centre:

Try it yourselfPython
import numpy as np
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
visits = np.concatenate([rng.normal(2, 0.6, 60), rng.normal(8, 1.5, 50), rng.normal(4, 1, 40)])
spend = np.concatenate([rng.normal(40, 10, 60), rng.normal(120, 25, 50), rng.normal(400, 60, 40)])
X = np.column_stack([visits, spend])
X = np.vstack([X, [[25, 30], [1, 900], [15, 600]]])   # three unusual customers join

model = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=0)).fit(X)
distance = model.transform(X).min(axis=1)    # distance to the nearest group centre

for i in np.argsort(distance)[::-1][:4]:     # the four most unusual customers
    print(f"customer {i}: {X[i, 0]:4.1f} visits, {X[i, 1]:5.0f} spent, distance {distance[i]:.1f}")
Output
customer 150: 25.0 visits,    30 spent, distance 5.0
customer 152: 15.0 visits,   600 spent, distance 3.5
customer 151:  1.0 visits,   900 spent, distance 3.3
customer 69:  4.7 visits,   197 spent, distance 1.2

For k-means, transform returns each row's distance to every group centre (in scaled units), so the smallest of them is the distance to the nearest group. The three newcomers top the list: 25 visits with almost no spending, 15 visits with big spending, and a single huge order. The fourth is an ordinary customer at the edge of a group. A score like this only ranks customers; you decide where "unusual" begins. Anomaly Detection covers methods built for this job.

How it differs from supervised learning

Supervised learningUnsupervised learning
DataFeatures X and labels yFeatures X only
GoalPredict the label of new examplesDescribe the data: groups, directions, outliers
Trainingfit(X, y)fit(X)
OutputA predicted class or numberGroup numbers, new features or scores
CheckingCompare predictions with true labels on a test setNo answer key, so only indirect checks

The two often work together. Unsupervised steps prepare data for supervised models: PCA can shrink the features before a classifier, and a customer's group number can become a feature. In the other direction, a few labelled examples, if you have them, are a good way to check an unsupervised result.

Why evaluation is hard

A supervised model is easy to judge: the test set holds the right answers, so you compare. Unsupervised learning has no right answers to compare with, and three things make judging tricky:

  1. There can be several sensible answers. Customers can be grouped by how much they spend, by what they buy or by when they shop. Each grouping suits a different purpose.
  2. The algorithm always answers. Ask k-means for 4 groups and you get 4 groups, even when the data has none.
  3. Scores measure shape, not usefulness. A score can say that groups are compact and well separated, but not whether they help your business.

The second point is the dangerous one. The program below runs k-means six times, from six random starting points, on two datasets: one with 4 real groups, and one with points spread evenly over a disc, which has no groups at all:

Try it yourselfPython
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import adjusted_rand_score

X_groups, _ = make_blobs(n_samples=300, centers=4, random_state=3)   # 4 real groups

rng = np.random.default_rng(0)                   # 300 points spread evenly over a disc:
radius = 10 * np.sqrt(rng.uniform(0, 1, 300))    # no groups at all
angle = rng.uniform(0, 2 * np.pi, 300)
X_disc = np.column_stack([radius * np.cos(angle), radius * np.sin(angle)])

for name, X in [("4 real groups", X_groups), ("no groups", X_disc)]:
    runs = [KMeans(n_clusters=4, n_init=1, random_state=seed).fit_predict(X) for seed in range(6)]
    sizes = sorted(np.bincount(runs[0]).tolist())
    agreement = np.mean([adjusted_rand_score(runs[0], run) for run in runs[1:]])
    print(f"{name:<13}  group sizes {sizes}  agreement between runs {agreement:.2f}")
Output
4 real groups  group sizes [74, 75, 75, 76]  agreement between runs 1.00
no groups      group sizes [56, 72, 75, 97]  agreement between runs 0.66

Both datasets came back with four groups of believable sizes, and nothing in the result warns you that the disc has no groups. The warning comes from a stability check. The adjusted Rand index measures how alike two groupings are: 1 means identical (whatever the group numbers), and 0 means no more alike than chance. Real groups come back the same from every start (1.00). On the disc, each start draws the borders somewhere else (0.66), a sign that the groups are an artefact of the algorithm, not a property of the data.

In practice, people combine several kinds of evidence:

  • Internal scores: how compact and well separated the groups are, such as inertia and the silhouette score in Clustering Overview.
  • Stability: real structure survives new random starts and resampled rows.
  • Inspection: look at typical members of each group, or at the most unusual examples. Do they make sense to someone who knows the domain?
  • Usefulness: does the result help the real goal, such as a better campaign, a faster model or more fraud caught?
  • A few labels: if a small labelled sample exists, check the result against it.

The workflow in scikit-learn

  1. Choose the features. The method uses every column you give it, so drop IDs and columns that have nothing to do with your question.
  2. Scale. Most methods measure distances or variance, so a column with big numbers (spend in hundreds) drowns out one with small numbers (visits under 10). Put a StandardScaler first. Clustering Overview shows what goes wrong without it.
  3. Fit the method with fit(X). There is no y.
  4. Use the result with the methods in the table below.
  5. Check it, with the evidence listed above.
MethodWhat it doesExample
fit(X)Learns from X: column means, group centres, directionsscaler.fit(X)
transform(X)Turns rows into new numbers using what fit learnedScaled values, PCA coordinates, distances to centres
fit_transform(X)Fits, then transforms the same rowsPCA(n_components=2).fit_transform(X)
fit_predict(X)Fits, then returns a group number for each of the same rowsKMeans(n_clusters=3).fit_predict(X)
predict(X_new)Gives new rows a group, using the fitted modelkmeans.predict(X_new)

Not every method has every step. DBSCAN and agglomerative clustering can only label the rows they were fitted on, so they have fit_predict but no predict, and t-SNE has fit_transform but no transform for new rows. Here is the whole pattern on the shop's customers:

Try it yourselfPython
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
visits = np.concatenate([rng.normal(2, 0.6, 60), rng.normal(8, 1.5, 50), rng.normal(4, 1, 40)])
spend = np.concatenate([rng.normal(40, 10, 60), rng.normal(120, 25, 50), rng.normal(400, 60, 40)])
X = np.column_stack([visits, spend])

scaler = StandardScaler().fit(X)              # fit: learn each column's mean and spread
print(f"learned means: {scaler.mean_[0]:.1f} visits, {scaler.mean_[1]:.1f} spent")
scaled = scaler.transform(X)                  # transform: rescale with what fit learned
print(f"customer 0: {X[0, 0]:.1f} visits, {X[0, 1]:.1f} spent -> scaled {scaled[0, 0]:.2f}, {scaled[0, 1]:.2f}")

clusters = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=0))
groups = clusters.fit_predict(X)              # fit, then a group number for the same rows
new = np.array([[7, 110], [3, 450]])          # two customers who joined today
for (v, s), g in zip(new, clusters.predict(new)):   # predict: reuse the learned groups
    print(f"new customer ({v} visits, {s} spent) -> group {g}, average spend {X[groups == g, 1].mean():.0f}")

reducer = make_pipeline(StandardScaler(), PCA(n_components=1))
print("shape before:", X.shape, "after fit_transform:", reducer.fit_transform(X).shape)
Output
learned means: 4.6 visits, 157.3 spent
customer 0: 2.1 visits, 37.1 spent -> scaled -0.90, -0.83
new customer (7 visits, 110 spent) -> group 0, average spend 119
new customer (3 visits, 450 spent) -> group 2, average spend 377
shape before: (150, 2) after fit_transform: (150, 1)

The scaler learned each column's mean during fit and used it in transform: customer 0 is below average on both features, so both scaled values are negative. The clustering pipeline learned its groups once, and predict placed the two newcomers into them: a frequent visitor joins the regulars, and a big spender joins the big spenders. The last line squeezes two columns into one with PCA.

In Supervised Learning, the scaler was fitted on the training data only, so that the test data stayed unseen. The same rule applies whenever an unsupervised step feeds a supervised model, and the PCA lesson shows it inside a pipeline. When you are only exploring one dataset, fitting on all of it is fine: there is no test set to leak into.

Common mistakes

Practice

Practice exercise

Group ten customers, then place two new customers in the groups the model has already learned, without refitting it.

Your solutionPython
import numpy as np
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Visits per month and monthly spend of 10 customers (no labels)
X = np.array([[1, 30], [2, 45], [2, 35], [1, 50],
              [9, 110], [8, 130], [10, 120],
              [3, 420], [4, 380], [3, 460]])
new_customers = np.array([[9, 100], [2, 400]])

# 1. Make a pipeline: StandardScaler, then KMeans(n_clusters=3, n_init=10, random_state=0)
# 2. Fit it on X and get a group number for every customer in X
# 3. Place the two new customers in the learned groups (do not refit!)
# 4. For each new customer, print the size and average spend of its group in X, like:
# new customer 1 joins a group of 4 averaging 40 spend
Knowledge check

You run k-means with 4 clusters on your customer data and get 4 groups. What does that tell you?

Summary

  • Unsupervised learning works with features only, no labels, and looks for groups, structure, shorter descriptions (compression) and outliers.
  • It answers "what is in this data?" rather than "what is the label?", and often comes first in a project or prepares features for a supervised model.
  • Evaluation is hard: there is no answer key, several groupings can be sensible, and algorithms always return an answer, so check stability, inspect examples and test usefulness.
  • In scikit-learn: scale first, then fit(X); use transform for new features, fit_predict for the groups of the same rows, and predict to place new rows.

Next: Clustering Overview.

Finished reading? Tick it off to track your progress.