Session 11 · Learning without labels

Session 11: Learning without labels

Which stocks move together, and is the ledger diversified? Find groups and hidden factors in data that come with no answers.

Data Science and Advanced Programming · UNIL · 2026

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Where sessions 9 and 10 left us

1 · modela line, a probability,
a tree
→
2 · losssquared error,
log loss
→
3 · minimisea formula, or
gradient descent
→
4 · testagainst the
known answers

Every model so far was supervised: each training day came with the answer, Apple's return or "bad day", and the loss measured how far the model was from it.

Today the answers are gone. The data are just numbers, with no to predict. Steps 1 to 3 survive in a new form; step 4 becomes the hard part.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

A question with no labels

ticker shares price value
AAPL 10 190.50 1905.00
NESN 4 102.30 409.20
VOO 2 512.00 1024.00

Apple is 57 % of the ledger. The risk manager asks: is this portfolio diversified? Which stocks move together, and which do not?

No file says "these stocks belong together". There is nothing to predict, only 1249 days of returns. Finding structure without answers is unsupervised learning.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Today

  1. Learning without labels
  2. What does "similar" mean?
  3. k-means
  4. Judging groups without answers
  5. Gaussian mixtures
  6. Hierarchical clustering
  7. DBSCAN: groups and outliers
  8. Principal components
  9. Back to the ledger

Parts 3 to 7 find groups of stocks. Part 8 finds the few hidden factors that move all of them.

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The data: universe.csv

Daily returns, in %, of 34 large stocks and VOO, 2022-01-18 to 2026-10-30:

Date,AAPL,MSFT,NESN,NVDA,GOOGL,…,GME,VOO 2022-01-18,… … (1249 days)
  • VOO is the market of sessions 9 and 10, unchanged.
  • The 34 stocks are simulated from that market, plus a shared factor for each sector and each stock's own noise (make_universe.py, fixed seed). AAPL, MSFT and NESN keep their betas of session 9.

Simulated data have one advantage today: we know the true sectors, and can check whether a method finds them, without telling it.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
cluster.py
1import pandas as pd
2from sklearn.cluster import KMeans
3from sklearn.preprocessing import StandardScaler
4
5returns = pd.read_csv("universe.csv", index_col="Date")
6market = returns["VOO"]
7stocks = returns.drop(columns=["VOO", "GME"]) # GME: Part 7
8
9features = pd.DataFrame(index=stocks.columns)
10for t in stocks.columns:
11 beta = stocks[t].cov(market) / market.var() # session 9
12 features.loc[t, "beta"] = beta
13 features.loc[t, "vol"] = stocks[t].std()
14
15Z = StandardScaler().fit_transform(features) # sd 1 each
16model = KMeans(n_clusters=5, n_init=10, random_state=0)
17features["group"] = model.fit(Z).labels_
18
19for g in range(5):
20 members = features[features["group"] == g].index
21 print("group", g, ":", " ".join(members))
$ python cluster.py
not run yet

Read it cold

Two minutes, on your own.

  • Lines 9–13 describe every stock with two numbers. Which two? Where have you seen the first?
  • Line 15 rescales them. Why might that matter here?
  • Line 16 asks for 5 groups. Nothing in the file says which stock is in which sector. Predict: will Apple and Microsoft end up together?
Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
cluster.py
1import pandas as pd
2from sklearn.cluster import KMeans
3from sklearn.preprocessing import StandardScaler
4
5returns = pd.read_csv("universe.csv", index_col="Date")
6market = returns["VOO"]
7stocks = returns.drop(columns=["VOO", "GME"]) # GME: Part 7
8
9features = pd.DataFrame(index=stocks.columns)
10for t in stocks.columns:
11 beta = stocks[t].cov(market) / market.var() # session 9
12 features.loc[t, "beta"] = beta
13 features.loc[t, "vol"] = stocks[t].std()
14
15Z = StandardScaler().fit_transform(features) # sd 1 each
16model = KMeans(n_clusters=5, n_init=10, random_state=0)
17features["group"] = model.fit(Z).labels_
18
19for g in range(5):
20 members = features[features["group"] == g].index
21 print("group", g, ":", " ".join(members))
$ python cluster.py
group 0 : NESN KO PG PEP ULVR CL DGE
group 1 : AAPL NVDA GOOGL META AMZN ORCL V
group 2 : XOM CVX SHEL BP TTE COP
group 3 : MSFT UBSG JPM BAC GS HSBA BNPwith the banks?
group 4 : ROG NOVN PFE JNJ MRK AZN

What it prints

Five groups of stocks, found without being told any sector.

  • Four of them look like real sectors: staples, energy, pharma, and a tech group with Apple.
  • Microsoft sits with the banks.

Is that a mistake? What exactly did the method group by, and how would we know whether a grouping is any good? This session answers both.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 1

Learning without labels

No one gives us the answers. What can we still learn from the data?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The same data, with and without labels

Supervised and unsupervised

Left: each point has its class, as the bad days did. Right: no classes; the eye still sees three groups. Can an algorithm?

supervised unsupervised
data features and answers features only
goal predict for new cases find structure in
judged by error on a test set harder: no answers to compare with
Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Two kinds of structure

Two kinds of structure

Groups: clustering. Split the cases into groups: alike inside a group, different across groups (left).

  • Which stocks behave alike? Which customers, which patients, which days?

Few hidden factors: dimension reduction. Many columns often move because of a few common causes. Find them, and describe each case with fewer numbers (right: two columns, one direction).

  • 34 return series, but much of their movement is "the market went up".

Parts 3 to 7 cluster; Part 8 reduces dimensions.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Four unsupervised tasks

Unsupervised learning is everywhere

  • A shop wants to know what kinds of customers it has, to treat them differently.
  • A botanist measures flowers and asks how many species there are.
  • An image is 64 numbers: can two describe it well enough to see it?
  • A card network looks for payments unlike all others, without a list of past frauds.

The next three slides look at the first three. The fourth, outliers, comes back in Part 7.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Customers of a shop (simulated)

Customers: which groups?

300 customers (simulated), each described by how often they come and how much they spend per month.

  • Three groups stand out: frequent small spenders, occasional big spenders, and very frequent mid-range buyers.
  • Nobody labelled them. A marketing team finds such segments first, and names them afterwards.

This is the typical use of clustering: describe a population by a few types.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Iris flowers (scikit-learn's iris data)

Flowers: how many species?

150 real iris flowers, measured in 1936 (load_iris in scikit-learn): four lengths in cm per flower.

  • Left: what an algorithm sees: no species, only measurements.
  • Right: the three groups k-means (Part 3) finds.

The small flowers at the bottom left are one species, cleanly found. The other two species overlap, and no method separates them perfectly from these measurements alone. Groups found without labels are only as clear as the data allow.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Handwritten digits (scikit-learn's digits data)

Images: 64 numbers down to 2

The 1797 handwritten digits of session 10, each 64 pixel values, squeezed to two numbers by principal components (Part 8). The colours and labels are added afterwards, for us.

  • 0, 4 and 6 sit in their own regions: two numbers keep much of what makes them different.
  • Others overlap: two numbers lose a lot.

Dimension reduction lets you look at data with many columns, and gives later models fewer, more informative inputs.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Judging without answers

In sessions 9 and 10, every model was judged against the truth on a test year. Without labels there is no truth to compare with. Three replacements, used today:

  • Internal measures: are the groups tight and far apart? (Part 4)
  • Stability: does the same method give the same groups on other days, or from another start? (Parts 3 and 9)
  • Meaning: does an expert recognise the groups? Here: are they sectors?

And because our stocks are simulated, we also have what real life never gives: the true sectors, to check against at the end.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 2

What does "similar" mean?

Before grouping stocks, we must say when two stocks are alike.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

Every clustering method groups "similar" cases. But a stock is 1249 returns: in which sense are two stocks similar?

  • Same risk profile: they react to the market by the same amount and move about as much. Two numbers per stock, from session 9.
  • Same movements: they go up and down on the same days. A correlation for each pair of stocks.

These are different questions, and they give different groups. Parts 3 to 5 use the risk profile; Part 6 uses the movements.

Choosing the features is choosing what "similar" means. No algorithm makes that choice for you.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
33 stocks, two numbers each (GME aside, Part 7)

Two numbers per stock

Lines 9–13 of the script.

  • Beta (session 9): the slope of the stock's returns on the market's. Above 1: it amplifies the market.
  • Volatility: the standard deviation of its daily returns, in %.

Apple: beta 1.28, volatility 1.63 %. Nestlé: 0.56 and 0.88 %.

Even without colours, the eye sees groups: low and calm at the bottom left, a band of high-beta stocks on the right, a volatile group at the top.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Standardise (session 10)

A common unit, again

Line 15 of the script. Beta and volatility are on different scales. A distance in the raw plane would weigh them by their units, not by how much they vary.

After standardising, each feature has mean 0 and standard deviation 1. Apple is 1.56 standard deviations above the average beta, 0.87 above the average volatility.

From here on, "distance between two stocks" means the Euclidean distance of session 10, in these standardised units.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 3

k-means

Put the stocks into k groups, each around a centre. Where should the centres go?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

We want to split the 33 stocks into groups, say , so that stocks in the same group are close together.

  • There is no label to learn from, so no loss of the kind we had: no "prediction minus truth".
  • The number of ways to split 33 stocks into 5 groups is larger than . Trying them all is out of the question.

We need: a number that says how good a split is, and a procedure that makes it small. The recipe of sessions 9 and 10, without the answers.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Distortion

: stock (two standardised numbers); : the centres; : the group of stock

A loss without answers

Give each group a centre, a point in the plane. 1 Each stock is measured against the centre of its own group.

is the squared Euclidean distance of session 10: the sum of squared differences, feature by feature. , the distortion or inertia, adds them up over all stocks.

  • Small : tight groups. Session 9's squared errors, with the centre as "prediction".

Smallest wins. To choose: the groups and the centres .

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Minimise J in turns

Repeat 1 and 2 until no stock changes group.

Two easy problems instead of one hard one

Choosing groups and centres together is hard. Each alone is easy:

1 If the centres are fixed, the best group for each stock is its nearest centre. means "the that makes it smallest".

2 If the groups are fixed, the best centre of each group is its mean: the point with the smallest sum of squared distances (session 9: least squares gives the mean).

k-means alternates the two, from random starting centres. This is Lloyd's algorithm (1957).

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
k-means on the 33 stocks, standardised

k-means in pictures

The crosses are the centres; each stock takes the colour of its nearest one.

  • Start: five stocks picked at random serve as centres. Two of them are in the same corner, so one real group is split and two are merged.
  • After 1 and 2 steps: the centres move to the middle of their groups, and stocks switch to closer centres.
  • Converged: nothing changes any more. fell from 22.47 to 3.10.
Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
kmeans_scratch.py
1import numpy as np
2import pandas as pd
3
4returns = pd.read_csv("universe.csv", index_col="Date")
5market = returns["VOO"]
6stocks = returns.drop(columns=["VOO", "GME"])
7beta = stocks.corrwith(market) * stocks.std() / market.std()
8X = np.column_stack([beta, stocks.std()])
9Z = (X - X.mean(axis=0)) / X.std(axis=0)
10
11rng = np.random.default_rng(0)
12centres = Z[rng.choice(len(Z), size=5, replace=False)]
13for step in range(1, 11):
14 d = ((Z[:, None] - centres[None]) ** 2).sum(axis=2)
15 group = d.argmin(axis=1) # 1. nearest centre
16 J = d.min(axis=1).sum() # distortion
17 for g in range(5): # 2. move centres
18 centres[g] = Z[group == g].mean(axis=0)
19 print("step", step, " J =", round(J, 2))
$ python kmeans_scratch.py
step 1 J = 22.47
step 2 J = 7.82
step 3 J = 4.57
step 4 J = 3.1
step 5 J = 3.1
step 6 J = 3.1
step 7 J = 3.1
step 8 J = 3.1
step 9 J = 3.1
step 10 J = 3.1

k-means, by hand

The whole method is lines 13–18.

  • Line 12: five stocks, drawn at random, are the first centres.
  • Line 14: squared distance from every stock to every centre, all at once: a table of 33 rows and 5 columns.
  • Line 15, step 1: each stock takes its nearest centre.
  • Line 18, step 2: each centre moves to the mean of its stocks.

falls at every step and stops after four: 22.47, 7.82, 4.57, 3.1. Each step can only lower : assigning to the nearest centre cannot increase any distance, and the mean is the best centre for a fixed group.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The five groups

What k-means found

Lines 15–21 of the script, with scikit-learn's KMeans: .

  • Staples (bottom left), pharma, energy (top), and a high-beta tech group, as expected.
  • Microsoft (beta 1.14, volatility 1.47 %) lands with the banks, and Visa with tech.

Not a bug: in the plane of beta and volatility, Microsoft is closer to the banks. k-means answered the question we asked, "same risk profile", not "same business". Part 6 asks the other question.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
k-means on the shop's 300 customers (simulated)

k-means elsewhere: customer types

The customers of Part 1, standardised, .

  • 151 regulars: about 4 visits, CHF 300 a month.
  • 88 big spenders: 12 visits, CHF 924.
  • 61 frequent shoppers: 24 visits, CHF 467.

Each centre is a typical customer of its group: a summary a marketing team can act on, one offer per type. The names are ours; k-means only gives the groups.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Two starts, two answers

Different starts, different answers

k-means always stops at a split that no single step can improve. That split need not be the best one.

  • Left: start 0 reaches .
  • Right: start 9 is stuck at a much worse split: two real groups share a centre, and one group is cut in two.

The remedy is simple: run it many times from different starts and keep the smallest . That is n_init=10 on line 16 of the script.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
How many groups?

Choosing k

always falls when grows: with 33 groups, every stock is its own centre and . So alone cannot choose .

  • Left, the elbow: by . Look for where adding a group stops paying much: here around or (6.34, then 3.08).
  • Right, the silhouette (Part 4): highest around to .

The measures point to a range, not a number. In practice is chosen with them and with what the groups mean: five sectors, here.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

k-means, summed up

strengths weaknesses
simple, fast, millions of points you must choose
easy to explain: "nearest centre" different starts, different answers
centres summarise each group groups are round, of similar size
every stock must join a group, outliers too

The last weakness is why GME is set aside on line 7. With it, k-means spends a whole group on a single stock. Part 7 handles outliers properly.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 4

Judging groups without answers

Is a grouping good? Without labels, what can we measure?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

Part 1 named three ways to judge without answers: internal measures, stability, meaning. Stability we met in Part 3 (restarts). This part makes the internal measures precise.

  • measures how tight the groups are, but it always improves with more groups.
  • A good grouping should also have groups far apart: a stock should be much closer to its own group than to any other.

We need a measure that combines both, for each stock and for the whole grouping.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Silhouette of one stock

: average distance to the other stocks of its group. : average distance to the stocks of the nearest other group.

The silhouette

For each stock, compare how close it is to its own group with how close it is to the next best group.

  • near 1: much closer to its own group. Well placed.
  • near 0: on the border between two groups.
  • below 0: closer to another group. Probably in the wrong one.

The average silhouette over all stocks judges the whole grouping: 0.66 for the five groups of k-means. Above about 0.5 is usually read as a clear structure.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The five groups against the true sectors

Here we can check against the truth

Our stocks are simulated, so we can check once, after the fact. Rows: the five groups; columns: the true sectors.

31 of 33 stocks (94 %) are in a group dominated by their own sector: the purity.

Misplaced: Microsoft (a bank's risk profile) and Visa (with tech). In beta and volatility they do look like those groups: the features limit what can be found.

Internal measures say groups are clear; only meaning says what they are.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 5

Gaussian mixtures

Microsoft sits between two groups. Can a stock belong partly to both?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Volatility of the 33 stocks

The problem

Take one feature, volatility. The ticks at the bottom are the 33 stocks.

  • Most stocks are clearly in a calm, a middle or a volatile group.
  • Microsoft, at 1.47 %, is near the edge between the middle and volatile groups.

k-means gives a hard answer: Microsoft is in exactly one group. Often we want a soft one: "probably volatile, possibly middle". A probability for each group, like the classifiers of session 10, but without labels.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
A mixture of bell curves

: share of stocks in group ; , : the group's mean and standard deviation

A model of how the data arose

Imagine each stock was made in two steps: first its group is drawn, then its volatility, from that group's bell curve.

1 : the chance a stock comes from group , the mixing weight.

2 Group 's bell curve, the normal density of session 9, with its own mean and spread.

The data's density is the weighted sum: a Gaussian mixture model (GMM). Unlike k-means, this is a model of the data, so it has a likelihood (session 9).

GMM: Gaussian mixture model. Gaussian: normal.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Membership: Bayes' rule

From the model to soft groups

1 The probability that stock came from group , given its volatility : its membership in group , also called its responsibility.

Numerator: how likely group is to produce this volatility, times how common group is. Denominator: the same for all groups, so the memberships add up to 1.

If we knew the groups' parameters, memberships would be one line of arithmetic. But the parameters are what we want to learn.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Expectation-maximisation

The same trick as k-means: alternate

Again, two easy problems instead of one hard one:

  • E-step: with the parameters fixed, compute every stock's memberships (last slide).
  • M-step: with the memberships fixed, update each group's share, mean and spread: averages weighted by membership.

This is the EM algorithm (1977). Each round can only raise the likelihood, as k-means could only lower ; and it too can stop at a local best.

EM: expectation–maximisation. E-step: expectation step. M-step: maximisation step.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
EM on the 33 volatilities

EM in pictures

Each curve is one group's weighted bell curve; the ticks are the stocks.

  • Start: three wide curves at guessed places.
  • After 3 rounds: each curve has moved towards a group of stocks and narrowed.
  • Converged: a calm group around 0.88 %, a middle group around 1.25 %, a volatile group around 1.67 %, with weights 0.21, 0.36 and 0.43.

EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
em_scratch.py
1import numpy as np
2import pandas as pd
3
4returns = pd.read_csv("universe.csv", index_col="Date")
5vol = returns.drop(columns=["VOO", "GME"]).std()
6x = vol.to_numpy() # one number a stock
7
8def normal(x, mu, sd): # the bell curve
9 z = (x - mu) / sd
10 return np.exp(-z ** 2 / 2) / (sd * np.sqrt(2 * np.pi))
11
12mu = np.array([0.8, 1.2, 1.9]) # three first guesses
13sd = np.array([0.3, 0.3, 0.3])
14w = np.array([1 / 3, 1 / 3, 1 / 3]) # mixing weights
15for step in range(100):
16 dens = w * normal(x[:, None], mu, sd) # E-step
17 r = dens / dens.sum(axis=1, keepdims=True) # memberships
18 n_k = r.sum(axis=0) # M-step
19 w = n_k / len(x)
20 mu = (r * x[:, None]).sum(axis=0) / n_k
21 dev = (x[:, None] - mu) ** 2
22 sd = np.sqrt((r * dev).sum(axis=0) / n_k)
23
24print("means:", mu.round(2), " sds:", sd.round(2))
25print("weights:", w.round(2))
26for t in ["NESN", "JPM", "MSFT", "AAPL"]:
27 i = list(vol.index).index(t)
28 print(t, round(x[i], 2), "memberships:", r[i].round(2))
$ python em_scratch.py
means: [0.88 1.25 1.67] sds: [0.03 0.08 0.12]
weights: [0.21 0.36 0.43]
NESN 0.88 memberships: [1. 0. 0.]
JPM 1.26 memberships: [0. 1. 0.]
MSFT 1.47 memberships: [0. 0.08 0.92]soft
AAPL 1.63 memberships: [0. 0. 1.]

EM, by hand

  • Lines 8–10: the normal density of session 9.
  • Lines 16–17, E-step: weighted densities, divided by their sum: one row of memberships per stock.
  • Lines 18–22, M-step: weights, means and spreads, each a membership-weighted average.

The output: Nestlé and JPMorgan belong to one group with near certainty. Microsoft: 92 % volatile, 8 % middle. A soft answer, which k-means cannot give.

EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Heights of 500 adults (simulated)

Mixtures elsewhere: heights

The classic example. Adult heights mix two groups, women and men, whose bell curves overlap. Nobody recorded who is who: only heights.

  • EM finds two groups: around 165.7 cm and 179.6 cm, both with a spread of about 6.4 cm.
  • A person of 172 cm belongs 63 % to the first group, 37 % to the second. A hard rule would have to guess.

Mixtures are used wherever a population is made of hidden types: customers, cells in a blood sample, calm and turbulent market periods.

EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

k-means is EM with hard memberships

k-means Gaussian mixture, by EM
membership 0 or 1: nearest centre a probability for each group
group shape round, all alike each its own spread (and, in 2D, its own tilt)
what it is a procedure that lowers a model of the data, with a likelihood
alternates assign ↔ move centres E-step ↔ M-step

Make all spreads equal and tiny: memberships become 0 or 1, the E-step becomes "nearest centre", the M-step "move to the mean". k-means is a limiting case of EM.

The number of groups is still hard to choose: with 33 stocks, the data cannot prove three groups beat one. Meaning decides.

EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 6

Hierarchical clustering

Which stocks move together, and at which level do groups join?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

The risk manager's question was about movements: if Apple falls, what else falls with it? Beta and volatility say how much a stock moves, not when.

  • Microsoft and the banks have similar risk profiles, but they need not fall on the same days.
  • What matters for diversification is the correlation between stocks (session 9): do they move together, day by day?

And how many groups? Instead of fixing , we would like to see the whole structure: small groups inside bigger ones.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Distance from correlation

Turning correlations into distances

Two stocks that always move together have correlation 1: distance 0. Unrelated stocks: correlation 0, distance 1.

With 34 stocks there are 561 pairs, each with its correlation over 1249 days. No features to choose: the distance comes straight from the returns.

Apple is closest to Microsoft, then to JPMorgan, then Nestlé, then Exxon.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Six stocks, returns minus the market

Building the tree from the bottom

Agglomerative clustering:

  1. Every stock is its own group.
  2. Merge the two closest groups.
  3. Repeat until one group is left, recording each merge's distance.

The record is a dendrogram. Left, six stocks: Coca-Cola and Nestlé merge first, then Apple and Microsoft, then Nvidia joins them. Cut it at any height: a grouping. One tree, every at once.

Step 2 needs a distance between groups: several definitions exist.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Distance between group A and group B

Linkage: how far apart are two groups?

Step 2 asks "which two groups are closest?". We know the distance between two stocks; a group holds several. Three common answers, for the same two groups A and B:

  • Single: the closest pair, one stock from each group: 2.1.
  • Complete: the farthest pair: 4.0.
  • Average: the mean over all 16 pairs: 3.0.

Same groups, three distances. Since step 2 merges the closest pair of groups, the choice changes which groups merge first, and so the whole tree.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The same points, cut into 2 groups

Why the choice matters

Two dense clouds, a thin bridge of points between them, and one point far above.

  • Single linkage needs just one close pair to merge. The bridge links the two clouds step by step: they become one group, and the far point is the other. This is chaining.
  • Complete linkage needs every pair to be close. Two compact groups, left and right; the bridge is split between them.

Single linkage follows chains and finds stragglers; complete linkage finds compact groups. Average sits between them, and is what we use for the stocks.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Average linkage, raw correlations

The dendrogram

Read it from the right: every stock starts alone; horizontal position is the distance at which groups join. Tickers are coloured by their true sector, which the method never saw.

  • Energy, pharma and staples each form a clean branch.
  • But tech and banks merge early into one big branch, and GME joins last.

Why would Apple and JPMorgan look so close? Both have high betas. On most days, both just follow the market.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Remove the market first (session 9)

The market hides the sectors

Every stock follows the market, so every pair of stocks is correlated. That shared part drowns the smaller sector movements.

1 Subtract each stock's beta times the market's return: what is left are its residuals (session 9), the part of its movement the market does not explain.

Between residuals, Apple and Microsoft are still related; Apple and JPMorgan, Nestlé or Exxon no longer are. What remains is the sector.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Average linkage, returns minus the market

The dendrogram, without the market

The same method on residual correlations.

  • Five clean branches: tech, banks, energy, pharma, staples, each coloured by one sector.
  • Microsoft is back with tech, Visa sits with the banks, and GME joins nothing until the very end.

Cut the tree at the dashed line: six groups, the five sectors and GME. Without being told any sector, the method recovered all of them, once the right question ("what moves together beyond the market?") was asked.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
hier_scratch.py
1import numpy as np
2import pandas as pd
3
4returns = pd.read_csv("universe.csv", index_col="Date")
5market = returns["VOO"]
6stocks = returns.drop(columns="VOO")
7resid = pd.DataFrame(index=stocks.index) # minus the market
8for t in stocks.columns:
9 beta = stocks[t].cov(market) / market.var() # session 9
10 resid[t] = stocks[t] - beta * market
11D = 1 - resid.corr() # distance table
12
13def closest_pair(groups):
14 """Closest pair of groups, by average linkage."""
15 best = (np.inf, 0, 0)
16 for i in range(len(groups)):
17 for j in range(i + 1, len(groups)):
18 block = D.loc[groups[i], groups[j]] # all pairs
19 d = block.to_numpy().mean()
20 if d < best[0]:
21 best = (d, i, j)
22 return best
23
24cut = 0.9 # the dendrogram's dashed line
25groups = [[t] for t in stocks.columns] # one per stock
26d, i, j = closest_pair(groups)
27while d < cut: # below the cut: merge
28 groups[i] = groups[i] + groups[j]
29 del groups[j]
30 d, i, j = closest_pair(groups)
31
32print(len(groups), "groups at cut", cut)
33for g in groups:
34 print(" ".join(g))
$ python hier_scratch.py
6 groups at cut 0.9
AAPL AMZN GOOGL META NVDA MSFT ORCL
NESN KO PG CL ULVR DGE PEP
UBSG HSBA JPM BAC BNP GS V
XOM CVX SHEL COP BP TTE
ROG NOVN JNJ PFE MRK AZN
GME

Hierarchical clustering, by hand

  • Lines 7–10: residuals, stock by stock: return minus beta times the market (session 9).
  • Line 11: distance = 1 − correlation, a table with a row and a column per stock.
  • Lines 13–22: closest_pair tries every pair of groups. D.loc[...] picks the rows of one group and the columns of the other: all their pairs; the mean is average linkage.
  • Line 25: one group per stock; a group is a list of tickers.
  • Lines 27–30: while the closest pair is below the cut (line 24, the dashed line), merge it and look again.

The number of groups is not chosen: it comes out of the cut. Six, the same as the dendrogram.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Correlations of the residuals

What the tree reveals in the data

Each picture is the 34 × 34 table of residual correlations; darker is higher.

  • Left: stocks in a random order. The structure is there, but invisible.
  • Right: the same table, with the stocks in the order of the dendrogram. Five dark blocks appear: the sectors.

Reordering by a dendrogram is a standard way to show structure in a correlation table, in finance and in genetics alike.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The ten digits, averaged (scikit-learn's digits data)

Trees elsewhere: which digits look alike?

Average the 1797 handwritten digits of each class: ten 8 × 8 images. Cluster them by the distance between their 64 pixels.

  • First merges: 1 and 8, then 3 and 9; 2 joins 1 and 8.
  • 0, 4 and 6 form their own branch, joined to the others last: their shapes are the most distinct.

The same tool draws family trees of species from their DNA, groups languages by shared words, and organises documents by topic.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 7

DBSCAN: groups and outliers

Density-based clustering (DBSCAN). GME fits nowhere. Can a method say so, instead of forcing it into a group?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

GME, the "meme stock", has volatility 4.68 %, about 5.0 standard deviations above the others. It is not part of any group.

  • k-means puts every stock in a group. With GME included, it spends a whole group on it, or drags a centre towards it.
  • Hierarchical clustering also puts it somewhere, if you cut low enough.

We want a method that finds groups as dense regions of points, and calls points in empty regions noise. Without being told how many groups there are.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Core, border and noise

Density, in two numbers

Choose a radius and a minimum count, min_samples.

  • Core point: at least min_samples points (itself included) within . It sits inside a dense region.
  • Border point: fewer neighbours, but within of a core point. The edge of a region.
  • Noise: neither. Nothing dense nearby.
Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The algorithm

  1. Find all core points.
  2. Connect core points that are within of each other: each connected set is a group.
  3. Attach each border point to the group of a nearby core point.
  4. Everything else is noise, label −1.

The number of groups is not chosen: it comes out. Groups can have any shape, even long and curved. This is DBSCAN (density-based spatial clustering of applications with noise, 1996).

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
DBSCAN on beta and volatility, GME included

DBSCAN on the stocks

min_samples = 3, standardised units, all 34 stocks.

  • GME is noise (the red cross): no stock is near it.
  • 3 groups: the calm stocks (staples with pharma), energy, and one long band of high-beta stocks (tech with banks).

Dense regions that touch become one group: DBSCAN cannot split the band of tech and banks, which k-means cut in the middle. Each method has its own idea of a group.

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
dbscan.py
1import pandas as pd
2from sklearn.cluster import DBSCAN
3from sklearn.preprocessing import StandardScaler
4
5returns = pd.read_csv("universe.csv", index_col="Date")
6market = returns["VOO"]
7stocks = returns.drop(columns="VOO") # GME included
8beta = stocks.corrwith(market) * stocks.std() / market.std()
9features = pd.DataFrame({"beta": beta, "vol": stocks.std()})
10Z = StandardScaler().fit_transform(features)
11
12print("eps, groups, noise")
13for eps in [0.3, 0.5, 0.8]:
14 labels = DBSCAN(eps=eps, min_samples=3).fit(Z).labels_
15 noise = features.index[labels == -1]
16 print(eps, labels.max() + 1, " ".join(noise))
$ python dbscan.py
eps, groups, noise
0.3 3 COP GME
0.5 3 GME
0.8 2 GME

The radius decides

Three values of , the same min_samples:

  • : Conoco (COP), the most volatile energy stock, is also called noise. Too strict.
  • : only GME.
  • : still only GME, but two groups merge: 2 groups.

DBSCAN trades the choice of for the choice of . With standardised features, values around 0.5 are a usual start; then look at what comes out.

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Card payments (simulated)

DBSCAN elsewhere: odd payments

403 card payments, each described by its amount and its distance from home, standardised. Three of them are planted frauds, far from the rest.

DBSCAN with and min_samples = 5 finds one dense group, the normal payments, and flags 5 points as noise: the 3 frauds, and 2 genuine but unusual payments.

That is how unsupervised fraud screening works: no list of past frauds, just "unlike everything else". A person then checks the few flagged cases.

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Four ways to group stocks

k-means Gaussian mixture hierarchical DBSCAN
you choose linkage, where to cut , min_samples
membership hard soft: probabilities hard, at every level hard, or noise
group shape round bell-shaped any any, follows density
outliers forced into a group forced, but with low probability join last flagged as noise
here risk profiles, 94 % pure MSFT 92 % volatile sectors, from movements GME as noise

No method is best everywhere: pick the one whose idea of a "group" fits your question.

DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

And many more clustering methods

Eight clustering algorithms on six toy data sets
  • Rows: six toy data sets. Columns: eight scikit-learn methods; gold frames: today's four.
  • Rings, moons: k-means and mixtures cut them in half: they look for round groups. Density-based methods follow the shapes.
  • Last row, no structure: most methods still return groups.
  • Black: noise.

DBSCAN: density-based spatial clustering of applications with noise; HDBSCAN: its hierarchical version; BIRCH: balanced iterative reducing and clustering using hierarchies.

After scikit-learn's example "Comparing different clustering algorithms on toy datasets" (BSD licence), redrawn with the same data and settings.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 8

Principal components

34 return series. How many things really move them?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

The problem

What drives the 34 stocks? Their 561 correlations are too many to read.

  • The dendrograms suggested an answer: one big common movement, the market, and a few sector movements.
  • To see the sectors, we removed the market by hand, using VOO. Can the 34 stock returns alone reveal the market, then the sectors, as factors: one number a day each?
  • And how much of the stocks' movement does each factor explain?

Principal component analysis (PCA) finds the few directions along which the data vary most.

PCA: principal component analysis.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Two stocks, one direction

Two numbers down to one

Each dot is a day: Apple's and Microsoft's returns, standardised. The cloud is long and thin, because the two stocks move together.

  • One direction, the dark line, carries most of the spread: "both up" or "both down".
  • Replace each day by its position along that line (gold): one number instead of two, and little is lost.

That direction is the first principal component (PC1): the direction in which the data spread the most. The second component is at a right angle to it, and carries what is left.

PC1: first principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Two stocks: the variance of a weighted sum

Which direction spreads the most?

A direction is a pair of weights of length 1. Each day gives one number, the weighted sum of the two standardised returns.

1 Its variance (session 9: variances add, plus twice the covariance) depends on the correlation .

  • Equal weights, : variance 1.71, the most. That is PC1: "both together", 85 % of the total of 2.
  • Opposite weights: 0.29, the least. That is PC2: "one against the other".

PC1, PC2: first and second principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The direction of largest spread

The first component, as a formula

With 34 stocks, the same question: which weights of length 1 give the weighted sum the largest variance? Written with the 34 × 34 correlation table , that variance is .

1 Weights of length 1: otherwise doubling them would inflate the spread for free.

2 The best satisfies : multiplying it by only stretches it. Such a is an eigenvector, its eigenvalue, and its variance. With two stocks: and 0.29.

np.linalg.eigh computes them in one line.

PC: principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Share of variance, each component

How much does each component explain?

34 standardised stocks have a total variance of 34. Each component carries a part of it, its eigenvalue.

  • PC1: 44.5 %. One number per day explains almost half of all the movement of 34 stocks.
  • PC2: 10.7 %, PC3: 6.2 %, then a long tail of small ones.

This bar chart is a scree plot, named after the rubble at the foot of a cliff: a steep drop, then flat.

PC1, PC2, PC3: first, second, third principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The first component

PC1 is the market

Left: PC1's weights on the 34 stocks, coloured by sector. All positive, all about the same size (0.12 to 0.21; GME only 0.08). PC1 is close to "the average of all stocks".

Right: PC1 on each day, against VOO's return: correlation 0.937.

PCA was never told about the market. It found it, as the biggest common movement in the data. This is why the raw dendrogram merged tech with banks.

PCA: principal component analysis.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Weights of the first six components

The next components are sectors

Columns: components. Rows: stocks, coloured by true sector. Red: positive weight, blue: negative.

  • PC1: every stock, the market.
  • PC2: only energy. PC3: only pharma. PC4: staples.
  • PC5: tech against banks: the two high-beta sectors, separated.
  • PC6: GME alone.

Each component after the first is a sector factor, found without any sector names.

PC1: first principal component. PC: principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
pca_scratch.py
1import numpy as np
2import pandas as pd
3from sklearn.decomposition import PCA
4
5returns = pd.read_csv("universe.csv", index_col="Date")
6stocks = returns.drop(columns="VOO")
7Z = ((stocks - stocks.mean()) / stocks.std()).to_numpy()
8
9C = Z.T @ Z / (len(Z) - 1) # 34 x 34 correlations
10values, vectors = np.linalg.eigh(C) # eigenvalues, ascending
11order = np.argsort(values)[::-1] # largest first
12values, vectors = values[order], vectors[:, order]
13share = values / values.sum()
14print("share of variance:", share[:5].round(3))
15
16pc1 = Z @ vectors[:, 0] # PC1 on each day
17pc1 = pc1 * np.sign(vectors[:, 0].sum()) # sign: up = up
18r = np.corrcoef(pc1, returns["VOO"])[0, 1]
19print("corr(PC1, VOO):", round(r, 3))
20
21ratio = PCA().fit(Z).explained_variance_ratio_
22print("scikit-learn:", ratio[:5].round(3))
$ python pca_scratch.py
share of variance: [0.445 0.107 0.062 0.056 0.044]
corr(PC1, VOO): 0.937
scikit-learn: [0.445 0.107 0.062 0.056 0.044]

PCA, by hand

  • Line 7: standardise every stock.
  • Line 9: the correlation table . @ is matrix multiplication: every column times every column, summed over days.
  • Line 10: its eigenvalues and eigenvectors.
  • Lines 11–14: sort them, largest first; each eigenvalue's share of the total.
  • Lines 16–19: PC1 on each day; its correlation with VOO.

Same shares as scikit-learn's PCA (line 21).

PCA: principal component analysis. PC1: first principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Variance explained, components kept

How many components to keep?

  • 1 component: 44.5 %; 3: 61 %.
  • 80 % needs 11 components, 90 % needs 20.

The first few components carry the common movements. After the sector factors, what is left is each stock's own news, which no common factor explains.

How many depends on the purpose: 5 or 6 to see the structure, many more to rebuild every stock closely.

PC: principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
One handwritten 3, rebuilt from k components

PCA elsewhere: compressing images

PCA on the 1797 digits: 64 pixels each. Keep components, then rebuild the image from those numbers alone.

  • With 1 or 2 components, a blur: only the most common stroke patterns.
  • With 10, the 3 is clear, from 10 numbers instead of 64.

The same idea compresses faces, sounds and survey answers: keep the few directions that carry most of the variation.

PCA: principal component analysis.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Daily changes of yield curves (simulated)

PCA in finance: yield curves

A yield curve: the interest rate for each maturity, from 3 months to 30 years. Every day, ten rates move. PCA on their daily changes:

  • PC1, level (89.8 %): all rates move up or down together.
  • PC2, slope (4.9 %): short rates against long ones.
  • PC3, curvature (0.9 %): the middle against both ends.

Three numbers a day describe the whole curve; bond desks hedge in these three factors.

PCA: principal component analysis. PC1, PC2, PC3: first, second, third principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Standardise before PCA

PCA looks for the largest variance. Without standardising, the most volatile stocks dominate.

  • GME alone carries 26 % of the total raw variance of the 34 stocks.
  • PCA on raw returns: the largest weight in PC1 goes to GME (0.52), against 0.08 after standardising.

On raw returns, "the main factor" is partly one meme stock. Standardise, unless all columns share a unit and their size is what you mean to study.

PCA: principal component analysis. PC1: first principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Part 9

Back to the ledger

Is the portfolio diversified, and what would change if it were?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The ledger, by group

What the groups say about the ledger

  • Apple is in the tech group in every method, by risk profile and by movements.
  • Nestlé is in the staples group: calm, low beta.
  • VOO is the market itself: PC1.
  • Microsoft has no shares in the ledger (session 6). Had it any, it would add more tech: its residuals move with Apple's.

So the ledger holds three things: the market (VOO, and the market part of Apple and Nestlé), tech (Apple), and a little of staples (Nestlé). No energy, no pharma, no banks.

PC1: first principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Daily variance of the ledger, and of one change

How much of the ledger's risk is the market?

The ledger's daily return is the value-weighted average of its positions. Its standard deviation: 1.23 % per day.

  • 75 % of its daily variance moves with PC1, the market.
  • Move half of the Apple position into energy and pharma (Exxon and Roche, equally): the standard deviation falls to 0.99 %, 19 % less.

The groups tell you where to diversify: into the clusters the portfolio does not hold yet.

PC1: first principal component.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
regimes.py
1import pandas as pd
2from sklearn.cluster import KMeans
3from sklearn.preprocessing import StandardScaler
4from sklearn.metrics import silhouette_score
5
6returns = pd.read_csv("universe.csv", index_col="Date")
7days = StandardScaler().fit_transform(returns[["VOO", "MSFT"]])
8
9model = KMeans(n_clusters=4, n_init=10, random_state=0)
10labels = model.fit(days).labels_
11for g in range(4):
12 print("regime", g, ":", (labels == g).sum(), "days")
13print("silhouette:", round(silhouette_score(days, labels), 2))
$ python regimes.py
regime 0 : 425 days
regime 1 : 432 days
regime 2 : 167 days
regime 3 : 225 days
silhouette: 0.35

Spot the lie

A classmate clusters days instead of stocks: each day described by VOO's and Microsoft's returns. k-means with finds four "market regimes", of 425, 432, 167 and 225 days.

The report: "The market switches between four regimes: calm, rally, sell-off, and mixed. We should change the portfolio with the regime."

No crash, no warning, four tidy groups. What is wrong?

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
The classmate's four regimes

The lie, explained

Right: the same days, uncoloured: one round cloud. No groups to find.

  • k-means always returns groups: it cut one blob into four slices.
  • Average silhouette 0.35, against 0.66 for the stocks.
  • A Gaussian mixture prefers one group: lower BIC (Bayesian information criterion) for 1 group, 6099, than for 4, 6231.

In make_history.py every day is drawn from the same distribution: no regimes exist.

BIC: Bayesian information criterion; lower is better.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

Before you trust a clustering

  • Plot first. Do you see groups at all, or one cloud?
  • Choose features on purpose. They decide what "similar" means: risk profile or co-movement.
  • Standardise features with different units, and before PCA.
  • Remove what dominates when it hides what you look for: here, the market.
  • Restart k-means and EM from many starts; compare or the likelihood.
  • Check the strength: silhouette, and whether a one-group model does as well.
  • Ask what the groups mean. An algorithm finds groups; only you can name them.

PCA: principal component analysis. EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
cluster.py
1import pandas as pd
2from sklearn.cluster import KMeans
3from sklearn.preprocessing import StandardScaler
4
5returns = pd.read_csv("universe.csv", index_col="Date")
6market = returns["VOO"]
7stocks = returns.drop(columns=["VOO", "GME"]) # GME: Part 7
8
9features = pd.DataFrame(index=stocks.columns)
10for t in stocks.columns:
11 beta = stocks[t].cov(market) / market.var() # session 9
12 features.loc[t, "beta"] = beta
13 features.loc[t, "vol"] = stocks[t].std()
14
15Z = StandardScaler().fit_transform(features) # sd 1 each
16model = KMeans(n_clusters=5, n_init=10, random_state=0)
17features["group"] = model.fit(Z).labels_
18
19for g in range(5):
20 members = features[features["group"] == g].index
21 print("group", g, ":", " ".join(members))
$ python cluster.py
group 0 : NESN KO PG PEP ULVR CL DGE
group 1 : AAPL NVDA GOOGL META AMZN ORCL V
group 2 : XOM CVX SHEL BP TTE COP
group 3 : MSFT UBSG JPM BAC GS HSBA BNP
group 4 : ROG NOVN PFE JNJ MRK AZN

Read it again

The script from the start of the session:

  • 9–13: two features per stock, beta and volatility: "similar" means "same risk profile" (Part 2)
  • 15: standardise, so both features count alike (Part 2)
  • 16: k-means with 5 groups and 10 starts; the best wins (Part 3)
  • 17–21: the groups. Microsoft with the banks: right for this question, wrong for co-movement (Parts 4 and 6)
Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels
Today, in five lines

Check yourself

  1. k-means gives with . Why is that not the best grouping?
  2. A stock has silhouette −0.2. What does that tell you?
  3. EM gives a stock memberships 0.5 and 0.5. Where is it?
  4. Why did tech and banks merge in the raw dendrogram, and not after removing the market?
  5. PC1 explains 45 % of the variance of 34 stocks. What would that number be if the stocks were unrelated?

PC1: first principal component. EM: expectation–maximisation.

Data Science and Advanced Programming · UNIL · 2026
Session 11 · Learning without labels

What you can now do

  • Tell supervised from unsupervised problems, and clustering from dimension reduction.
  • Choose features that say what "similar" means, and standardise them.
  • Run k-means, explain its two steps, restart it, and choose with the elbow and the silhouette.
  • Fit a Gaussian mixture by EM, and read soft memberships.
  • Build a dendrogram from correlations, remove a dominant factor first, and cut the tree.
  • Find groups and outliers with DBSCAN.
  • Find hidden factors with PCA, read their weights, and decide how many to keep.
  • Doubt groups that a method finds in a single cloud.

Next session: neural networks.

PCA: principal component analysis. EM: expectation–maximisation. DBSCAN: density-based spatial clustering of applications with noise.

Data Science and Advanced Programming · UNIL · 2026

GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.