▚ The AI Engineer's Field Manual
Module 03b · Act II — ML Foundations

Unsupervised Learning, Experiment Tracking & Dashboards — Finding Groups Nobody Labelled

"A model that predicts is a tool. A model you can find again, a group you can name, and a dashboard someone else can open are a product."

~5 hours Builds on: Module 03 · scaling in Module 02 Tools: scikit-learn · MLflow · Weights & Biases · Streamlit Job-spec line it unlocks: "Applied ML: clustering, experiment tracking (MLflow / W&B), Streamlit"

01 · The hookThree Questions the Churn Model Could Not Answer

Field report · Customer Success, the week after the churn model shipped

"The churn scores are great. I call the top 300 every week and Marcus is happy. But when the board asks me 'what kinds of customers do we actually have?', I have nothing. I have 4,400 accounts and one number for each. I do not know whether we are one business or four. Nobody has ever labelled our customers. Where do I even start?"

— Priya Nair, Head of Customer Success at SaaSify

Where we are in the story: in Module 03 Marcus Vance, the CEO, asked for a ranking of accounts by churn risk, and we built it with XGBoost. That model needed a label for every customer: "left" or "stayed". Priya's question has no label at all, and that is the first problem of this module.

Priya is asking for segments: groups of customers who behave alike. Nobody can write the answer down in advance, because nobody knows it. The data has to tell us. That kind of learning, where the computer looks for structure in a table with no answer column, is called unsupervised learning.

Two more problems arrive in the same month, and they are the reason this module is not only about clustering. Dev Okafor, the senior data scientist, tells the team on Wednesday: "I cannot rebuild the churn model I showed Marcus last month. It scored 0.92 and I do not remember which learning rate, which depth, or which data." Then Priya says on Friday: "Please do not send me a notebook. My team does not run Python."

WEEK 1 · GROUPS 4,400 accounts 0 labels which kinds exist? WEEK 2 · MEMORY 6 sweep runs 0 written down which one scored 0.92? WEEK 3 · SHARING 1 CS team 0 who run Python needs a web page 1 2 3 each box is one section of this module
Fig. 3b.1 — Three problems that arrive in three weeks, in the story's own numbers. The churn model solved none of them.
  1. Groups. The table has 4,400 rows and no "customer type" column. Clustering, the first half of the module, invents the missing column from behaviour alone.
  2. Memory. Six training runs happened, with different settings, and none was written down. Experiment tracking is the practice of recording every run so the best one can be found again.
  3. Sharing. The people who need the answer do not run Python. A dashboard turns the result into a web page they can open and filter.
You already know this

Each problem has a software twin. Clustering is "group the log lines that look alike" without a list of known error types. Experiment tracking is version control and a build log for model training: commit hash, config, test results, build artifact. A dashboard is the internal admin page you built for the support team so they stopped asking you for SQL queries.

The new part is only the first one. Tracking and dashboards are engineering habits you already own, applied to a thing (a trained model) that is much harder to rebuild than a binary.

02 · The intuitionGroups Nobody Labelled: What "Unsupervised" Means

Unsupervised learning looks for patterns in data that has no answer column. Without it, every question that starts with "what kinds of…?" gets a shrug, because nobody can label the groups until someone has seen them.

Where we are in the story: Priya has 4,400 accounts and wants to know what kinds of customers they are. In Module 03 every row came with a verdict, churned or stayed, and the model learned to copy it. Here there is no verdict to copy. We first need to see exactly what is missing, and Fig. 3b.2 shows it with four real rows.

SUPERVISED: has an answer column Account Tenure Logins Seats Churn ACC-0000 42 18 10 0 ACC-0001 3 5 2 0 ACC-0002 56 17 14 0 ACC-0003 2 6 8 1 UNSUPERVISED: no answer column Account Tenure Logins Seats Segment ACC-0000 42 18 10 ? ACC-0001 3 5 2 ? ACC-0002 56 17 14 ? ACC-0003 2 6 8 ? 2 1 task: learn Churn from the other columns task: invent the Segment column same accounts, same behaviour columns; only the last column differs
Fig. 3b.2 — The same four SaaSify accounts as a supervised and an unsupervised task. The left table carries the answer (Churn, 0 or 1) the model must learn to predict; the right table carries a blank column the algorithm must fill in itself.
  1. Supervised: the answer is given. ACC-0003 has 2 months of tenure and Churn = 1, so the model can be graded: it predicts, we compare with the 1, and we correct it. This is Modules 02 and 03.
  2. Unsupervised: the answer is invented. The right-hand column is a question mark. There is no 1 or 0 to compare with, so there is no "accuracy". The algorithm groups rows that sit close together and numbers the groups. A human then decides whether the groups mean anything.

That last sentence matters most. A supervised model is graded against the truth. An unsupervised one has no truth to be graded against. It will always return groups, whether or not the data really contains groups. Everything in this module is a way of living with that fact: ways to ask for groups, ways to check them, and ways not to fool yourself with them.

When unsupervised is the right tool

Before we build anything, Marcus will ask a fair question: why not just ask Priya's team what the customer types are? The answer decides whether this module is worth doing, so here it is as a table.

Four jobs unsupervised learning does, in SaaSify terms
JobPlain questionSaaSify exampleTool in this module
ClusteringWhich rows resemble each other?"What kinds of customers do we have?"k-means, DBSCAN, HDBSCAN
Dimensionality reductionCan I draw these 6 columns on a flat screen?A map of all 4,400 accountsPCA
Anomaly detectionWhich rows look like nobody else?A bot account logging in 400 times a monthIsolation Forest
Association and densityWhich things occur together?Features that are always bought togetherNot covered here; see Module 13

Use it when you have a question about structure and no labels, or when labels exist but are too costly to collect. Do not use it when you do have the label you care about. If Priya wanted "who will leave", the right tool is Module 03's classifier, not clustering. Clustering is for exploring and for creating a vocabulary the business can use. It is a poor way of predicting.

k-means: the idea in one picture

Priya's question is a clustering question, so we start with the oldest and most used algorithm for it, k-means. Real accounts have six columns, which cannot be drawn, so we first use six made-up accounts with two columns each (logins per week and seats paid for). Fig. 3b.3 is the entire algorithm.

k-means needs one number from you before it starts: k, how many groups you want. It then keeps one point per group, called its centre (the average position of the group's members). It repeats two moves until nothing changes. Assign: give every account to the nearest centre. Update: move each centre to the average of the accounts it just received.

start: centres on B and C A B C D E F step 1: assign, then move A B C D E F step 2: converged A B C D E F centres (3, 2), (2, 4) 1 (2.5, 1.5), (7.25, 7.75) 2 (2.33, 2.33), (9, 9) 3
Fig. 3b.3 — k-means on six accounts with k = 2. Diamonds are centres, dots are accounts A to F. Panel 1 starts with both centres on the left-hand accounts B and C. Panel 2 assigns and moves. Panel 3 has converged: the centres sit at (2.33, 2.33) and (9, 9) and nothing moves again.
  1. A bad start, on purpose. Both centres start among the three small accounts, at B (3, 2) and C (2, 4). Account D (9, 8) is 8.49 from B and 8.06 from C, so it joins C's group. So do E and F. The starting guess is poor, and the algorithm still recovers.
  2. Assign, then move. After the first assignment, group one is A and B (centre moves to 2.5, 1.5) and group two is C, D, E, F (centre moves to 7.25, 7.75). The second centre is dragged far from C, which is now the odd one out.
  3. Converged. In the next step C is closer to the left centre (2.55 away) than to the right one (6.45 away), so it switches sides. The centres become (2.33, 2.33) and (9, 9). Another round changes nothing, so the algorithm stops.

The next box asks you to play the algorithm with a pencil before you see any code. Do not worry if "nearest" feels vague: it means ordinary straight-line distance, the same as measuring on a map. The code section after it builds exactly this, one move at a time.

BE the k-means algorithm

Take the six accounts below. Your centres start on B and C. Do one full round with a pencil: assign every account to its nearest centre, then compute the new centres. Use straight-line distance, √(Δx² + Δy²) (square root of the x gap squared plus the y gap squared).

  1. A = (2, 1), B = (3, 2), C = (2, 4)
  2. D = (9, 8), E = (10, 9), F = (8, 10)
  3. Centre 1 = B = (3, 2); centre 2 = C = (2, 4)

Which accounts join centre 1, which join centre 2, and where do the two centres move?

Check your answer

Assign. A is 1.41 from B and 3.00 from C, so A goes to centre 1. B is 0 from itself, so centre 1. C is 2.24 from B and 0 from itself, so centre 2. D is 8.49 from B and 8.06 from C, so centre 2. E is 9.90 from B and 9.43 from C, so centre 2. F is 9.43 from B and 8.49 from C, so centre 2.

Update. Group 1 is A and B: the mean of x is (2 + 3) / 2 = 2.5 and the mean of y is (1 + 2) / 2 = 1.5, so the centre moves to (2.5, 1.5). Group 2 is C, D, E, F: mean x is (2 + 9 + 10 + 8) / 4 = 7.25 and mean y is (4 + 8 + 9 + 10) / 4 = 7.75, so the centre moves to (7.25, 7.75).

You just ran one full round. The lesson: C, an account that looks small, got dragged into the big group by a bad start. The next round fixes it, which is why the algorithm repeats.

Pick k centres.

Assign every point to its nearest one.

Move each centre to the mean of its points.

Repeat until nothing moves.

Pick: the two diamonds in panel 1 of Fig. 3b.3. Assign: the colours of the dots in panel 2. Move: the diamonds jumping from panel 1 to panel 2 and then panel 3. Repeat: panel 3 equals the next step, so stop.

Questions you might be asking now

Three slow answers about the six accounts of Fig. 3b.3. The same six rows are used in every answer: A (2, 1), B (3, 2), C (2, 4), D (9, 8), E (10, 9), F (8, 10), with logins per week first and seats second.

What is a "centre" exactly? Is it one of my accounts?

No. A centre is an imaginary point: the average position of the group's members. It usually does not match any real account.

Look at the final left-hand group, A, B and C. Its centre is worked out one column at a time:

  1. Average the logins. (2 + 3 + 2) / 3 = 7 / 3 = 2.33.
  2. Average the seats. (1 + 2 + 4) / 3 = 7 / 3 = 2.33.
  3. Read the result. The centre is (2.33, 2.33). No account has 2.33 logins and 2.33 seats. The centre describes "the typical small account", not a real one.
The same word in two jobs
Centre (k-means)Medoid (a cousin)
Is it a real account?No, an averageYes, the most central real one
Used byscikit-learn KMeansk-medoids (not in core scikit-learn)

A centre is the average of its group, so it can sit where no customer sits. That is why Priya's team will later read it as a profile, "the typical power team", rather than as a customer.

How is "distance" calculated? Show me with numbers.

Distance is the straight-line length between two points, from Pythagoras. For two columns: square the gap in each, add them, take the square root.

Take account A (2, 1) and the starting centre B (3, 2), then the starting centre C (2, 4):

  1. Gap in logins, A to B. 2 − 3 = −1. Square it: (−1)² = 1. Squaring removes the minus sign, so a gap on the left counts the same as a gap on the right.
  2. Gap in seats, A to B. 1 − 2 = −1, squared 1.
  3. Add and root. √(1 + 1) = √2 = 1.41. A is 1.41 from B.
  4. Same for A to C. Logins gap 2 − 2 = 0, seats gap 1 − 4 = −3, squared 9. √(0 + 9) = 3.00.
  5. Compare. 1.41 is smaller than 3.00, so A joins B's group. This is the "assign" move.

The same rule works with six columns: square six gaps, add six numbers, take one square root. That is exactly what the code in the next section does with one line of NumPy.

Distance is square each gap, add them up, take the root, and the nearest centre wins. Nothing smarter is going on.

Is clustering the same as classification?

No. Classification learns from labelled examples and predicts a label you already defined. Clustering has no examples and invents the groups.

Classification (Module 03) against clustering (this module), on SaaSify
ClassificationClustering
InputRows plus a Churn labelRows only
Who defines the groups?You did: "left" and "stayed"The algorithm, from distances
How do you grade it?Compare with the truth: AUC 0.94No truth; silhouette, plus human judgement
Group namesGivenNumbers (0, 1, 2, 3) until a human names them

Classification answers a question you wrote. Clustering proposes a question you had not thought to ask.

03 · Build it yourselfk-means in NumPy: Six Accounts, Then 4,400

We write k-means ourselves, in about 60 lines of NumPy, so that "assign then move" is a thing you have typed rather than a thing you have read. Without this, clustering stays a black box that returns numbers called "labels".

Where we are in the story: Priya's question needs a clustering, and Fig. 3b.3 showed the algorithm on six made-up accounts. Dev's rule on the data science team is "never use a tool you cannot rebuild on a whiteboard". So before reaching for scikit-learn we build the same loop, in five small chunks, and check it against the library.

The ten lines below come from the finished file, which you have not seen. Guess what each does before opening the answers. Every line is explained again in the step-by-step lists of the chunks that follow, so a blank row here is not a failure.

Sharpen your pencil

Ten lines from kmeans_from_scratch.py. Three are annotated. In the blank rows, write what the line does in plain English.

points = np.array([[2.0, 1.0], [3.0, 2.0], ...])builds a 6-row, 2-column table: logins and seats for six accounts
gap = points[:, None, :] - centres[None, :, :]
return np.sqrt((gap ** 2).sum(axis=2))squares each gap, adds the two columns, takes the root: straight-line distance
return distances(points, centres).argmin(axis=1)for each account, the number of its nearest centre
members = points[labels == j]
if len(members):
new[j] = members.mean(axis=0)
if np.allclose(new, centres):
inertia = (d[np.arange(len(points)), labels] ** 2).sum()
X = (X - X.mean(axis=0)) / X.std(axis=0)
Check your answers
gap = points[:, None, :] - centres[None, :, :]subtracts every centre from every account in one step, giving a block of gaps: 6 accounts by k centres by 2 columns
members = points[labels == j]keeps only the accounts currently labelled j: the members of group j
if len(members):skips the update if a group is empty, because the average of nothing does not exist; the centre then stays where it was
new[j] = members.mean(axis=0)moves centre j to the column-by-column average of its members
if np.allclose(new, centres):asks "did the centres move by essentially nothing?" If yes, the loop stops: converged
inertia = (d[np.arange(len(points)), labels] ** 2).sum()takes each account's distance to its own centre, squares it and adds them all: how tight the groups are, lower is tighter
X = (X - X.mean(axis=0)) / X.std(axis=0)scales each column to mean 0 and spread 1 so that no column dominates the distance (explained in the next section)

If you guessed the gap line and the mask line, you already understand the two moves the program is made of.

Sharpen your pencil: the number the loop reports

Chunk 4 will print an inertia of 9.33 for the final grouping of Fig. 3b.3. Check it by hand. Final centres: left (2.33, 2.33) for A, B, C; right (9, 9) for D, E, F. For each account, square its x gap and y gap, add them (this is the distance squared, no root needed), then add all six.

A (2, 1) to (2.33, 2.33)0.33² + 1.33² = 0.11 + 1.78 = 1.89
B (3, 2) to (2.33, 2.33)
C (2, 4) to (2.33, 2.33)
D (9, 8) to (9, 9)
E (10, 9) to (9, 9)
F (8, 10) to (9, 9)
total
Check your answers
B (3, 2) to (2.33, 2.33)0.67² + 0.33² = 0.44 + 0.11 = 0.56
C (2, 4) to (2.33, 2.33)0.33² + 1.67² = 0.11 + 2.78 = 2.89
D (9, 8) to (9, 9)0² + 1² = 1
E (10, 9) to (9, 9)1² + 0² = 1
F (8, 10) to (9, 9)1² + 1² = 2
total1.89 + 0.56 + 2.89 + 1 + 1 + 2 = 9.33 (exactly 9⅓)

The inertia is the quantity k-means tries to make small. Every assign and update move can only lower it or leave it the same, which is why the loop is guaranteed to stop.

Build it in chunks

We build kmeans_from_scratch.py in five chunks. Chunk 1 to 4 use the six accounts of Fig. 3b.3; chunk 5 checks the result and tries SaaSify. Each chunk runs on its own (the files kmeans_chunk1.py to kmeans_chunk5.py in the code folder are the cumulative programs).

  1. Chunk 1 — put six accounts in a table and measure the distance from each to each centre

    Everything in k-means is a distance, so the distance function comes first. Nothing is grouped yet, but you can already check the numbers against the follow-up answer above.

    Step-by-step: what chunk 1 does, in plain English
    1. import numpy as np loads NumPy, the library for tables of numbers.
    2. points is a 6-row, 2-column table: each row is one account, column 0 is logins per week, column 1 is seats. names only labels them for people.
    3. distances takes the points and the centres. points[:, None, :] adds an empty middle axis, so subtracting centres[None, :, :] gives every point minus every centre in one go: a 6 by k by 2 block of gaps.
    4. (gap ** 2).sum(axis=2) squares each gap and adds the two columns together. np.sqrt finishes Pythagoras. The result is a 6 by k table: row = account, column = centre.
    5. The try-it lines choose B and C as the starting centres (points[[1, 2]] picks rows 1 and 2) and print the table.
    kmeans_from_scratch.py — chunk 1runs offline
    # ── chunk 1: six accounts, and "how far is a point from a centre?" ──
    # pip install "numpy>=2.5,<2.6"
    import numpy as np
    
    # Six accounts. Column 0 = logins per week, column 1 = seats paid for.
    points = np.array([[2.0, 1.0], [3.0, 2.0], [2.0, 4.0],
                       [9.0, 8.0], [10.0, 9.0], [8.0, 10.0]])
    names = ["A", "B", "C", "D", "E", "F"]
    
    
    def distances(points, centres):
        """Straight-line distance from every point (rows) to every centre (columns)."""
        gap = points[:, None, :] - centres[None, :, :]      # shape (6, k, 2): point minus centre
        return np.sqrt((gap ** 2).sum(axis=2))              # Pythagoras on each pair
    
    # try it
    centres = points[[1, 2]].copy()          # start with B and C as the two centres (a deliberately bad start)
    print("centres:", centres.tolist())
    print(np.round(distances(points, centres), 2))

    None as an index (a new empty axis) and the sum over axis=2. Together they let NumPy compare every point with every centre without a Python loop.

    Run python3 kmeans_chunk1.py. Row B shows 0.00 against the first centre, and row A shows 1.41 and 3.00, the same numbers as the follow-up answer above.

    terminalactual output
    centres: [[3.0, 2.0], [2.0, 4.0]]
    [[1.41 3.  ]
     [0.   2.24]
     [2.24 0.  ]
     [8.49 8.06]
     [9.9  9.43]
     [9.43 8.49]]
  2. Chunk 2 — give every account to its nearest centre

    With distances in hand, the assign move is one line. It runs on its own: it reuses chunk 1 and prints which group each account joined.

    Step-by-step: what chunk 2 does, in plain English
    1. assign calls distances from chunk 1 to get the 6 by k table.
    2. .argmin(axis=1) looks along each row and returns the position of the smallest number: the index of the nearest centre.
    3. The try-it lines start from B and C again and print one label (0 or 1) per account.
    kmeans_from_scratch.py — chunk 2runs offline
    # ── chunk 2: assign every point to its nearest centre ──
    def assign(points, centres):
        return distances(points, centres).argmin(axis=1)    # index of the closest centre, per point
    
    # try it
    centres = points[[1, 2]].copy()          # same bad start as chunk 1: B and C
    labels = assign(points, centres)
    print("labels:", labels.tolist())

    argmin returns the position of the smallest value, not the value itself.

    Run python3 kmeans_chunk2.py. A and B get label 0 and C, D, E, F get label 1, matching the pencil exercise.

    terminalactual output
    labels: [0, 0, 1, 1, 1, 1]
  3. Chunk 3 — move each centre to the average of its accounts

    This is the update move. After it, one full round of the algorithm exists, and you can run it by hand and compare.

    Step-by-step: what chunk 3 does, in plain English
    1. update copies the old centres, so an unchanged centre stays unchanged.
    2. for j in range(len(centres)) visits each group in turn.
    3. points[labels == j] keeps only the rows whose label is j: the members of group j.
    4. if len(members) guards against an empty group. The mean of no numbers is undefined, so an empty group keeps its old centre.
    5. members.mean(axis=0) averages down each column, which gives the new centre.
    kmeans_from_scratch.py — chunk 3runs offline
    # ── chunk 3: move each centre to the average of its points ──
    def update(points, labels, centres):
        new = centres.copy()
        for j in range(len(centres)):
            members = points[labels == j]
            if len(members):                                # an empty group keeps its old centre
                new[j] = members.mean(axis=0)
        return new
    
    # try it
    centres = points[[1, 2]].copy()
    labels = assign(points, centres)
    centres = update(points, labels, centres)
    print("moved centres:", np.round(centres, 2).tolist())

    Boolean masks: labels == j is a row of True and False that picks out rows.

    Run python3 kmeans_chunk3.py. The centres move to (2.5, 1.5) and (7.25, 7.75), the pencil answer.

    terminalactual output
    moved centres: [[2.5, 1.5], [7.25, 7.75]]
  4. Chunk 4 — repeat until nothing moves, and score the result

    One round is not a result. Chunk 4 loops assign and update, stops when the centres stop moving, and reports the inertia, the total squared distance from each account to its own centre.

    Step-by-step: what chunk 4 does, in plain English
    1. kmeans loops at most max_iter times, a safety stop in case it never settles.
    2. Each pass assigns, then updates, then prints (if verbose) what happened.
    3. np.allclose(new, centres) asks whether the centres moved by essentially nothing. If so, break leaves the loop.
    4. Otherwise the new centres replace the old ones and the loop runs again.
    5. After the loop, inertia picks each account's distance to its own centre with d[np.arange(len(points)), labels], squares them and adds them.
    kmeans_from_scratch.py — chunk 4runs offline
    # ── chunk 4: repeat until nothing moves, and score the result ──
    def kmeans(points, centres, max_iter=50, verbose=True):
        centres = centres.copy()
        for step in range(1, max_iter + 1):
            labels = assign(points, centres)
            new = update(points, labels, centres)
            if verbose:
                print(f"step {step}: labels={labels.tolist()} centres={np.round(new, 2).tolist()}")
            if np.allclose(new, centres):                   # nothing moved: converged
                break
            centres = new
        d = distances(points, centres)
        inertia = (d[np.arange(len(points)), labels] ** 2).sum()   # total squared distance to own centre
        return labels, centres, inertia
    
    # try it
    labels, centres, inertia = kmeans(points, points[[1, 2]])
    print("inertia:", round(float(inertia), 2))

    np.allclose compares two tables with a tiny tolerance, because floating-point numbers are rarely exactly equal.

    Run python3 kmeans_chunk4.py. Three steps print, the last two are identical, and the inertia is 9.33.

    terminalactual output
    step 1: labels=[0, 0, 1, 1, 1, 1] centres=[[2.5, 1.5], [7.25, 7.75]]
    step 2: labels=[0, 0, 0, 1, 1, 1] centres=[[2.33, 2.33], [9.0, 9.0]]
    step 3: labels=[0, 0, 0, 1, 1, 1] centres=[[2.33, 2.33], [9.0, 9.0]]
    inertia: 9.33
  5. Chunk 5 — check against scikit-learn, then try it on SaaSify's 4,400 accounts

    A from-scratch program is only worth trusting once it agrees with the library. Then we point it at real-sized data to see that it is the same loop.

    Step-by-step: what chunk 5 does, in plain English
    1. KMeans(n_clusters=2, init=points[[1, 2]], n_init=1) asks scikit-learn to start from the same two centres as ours, once.
    2. The print line shows its labels and inertia, which should equal ours.
    3. generate_accounts() builds SaaSify's 4,400 accounts. We take logins and seats, and scale each column to mean 0 and spread 1. The next section explains why scaling matters.
    4. rng.choice(len(X), 4, replace=False) picks four random accounts as the starting centres, and kmeans(X, start, verbose=False) runs our loop silently.
    5. np.bincount(lab) counts how many accounts landed in each group.
    kmeans_from_scratch.py — chunk 5runs offline
    # ── chunk 5: check against scikit-learn, then try it on SaaSify ──
    from sklearn.cluster import KMeans
    from saasify_accounts import generate_accounts
    
    # try it
    km = KMeans(n_clusters=2, init=points[[1, 2]], n_init=1).fit(points)
    print("sklearn labels :", km.labels_.tolist(), " inertia:", round(float(km.inertia_), 2))
    
    df = generate_accounts()
    X = df[["LoginFrequency", "Seats"]].to_numpy(dtype=float)
    X = (X - X.mean(axis=0)) / X.std(axis=0)                # scale first, so no column dominates (page: "Stumble 2")
    rng = np.random.default_rng(0)
    start = X[rng.choice(len(X), 4, replace=False)]
    lab, cen, inertia = kmeans(X, start, verbose=False)
    print("SaaSify 4 groups, group sizes:", np.bincount(lab).tolist(), " inertia:", round(float(inertia), 1))

    init= and n_init= in scikit-learn: where the centres start, and how many restarts to try.

    Run python3 kmeans_chunk5.py from code/03b-unsupervised-tracking/ (it imports saasify_accounts.py). scikit-learn prints the same labels and inertia 9.33. SaaSify splits into four groups of 1,055, 937, 976 and 1,432 accounts.

    terminalactual output
    sklearn labels : [0, 0, 0, 1, 1, 1]  inertia: 9.33
    SaaSify 4 groups, group sizes: [1055, 937, 976, 1432]  inertia: 1026.9

The whole program

Chunk 1 is the first block (imports, points, distances); chunk 2 is assign; chunk 3 is update; chunk 4 is kmeans; chunk 5 is the scikit-learn check and the SaaSify run. Only the if __name__ block at the bottom is new: it joins the try-it lines of chunks 4 and 5.

kmeans_from_scratch.pyruns offline
"""k-means from scratch: six accounts first, then SaaSify's 4,400. Built in five chunks on the page."""
# ── chunk 1: six accounts, and "how far is a point from a centre?" ──
# pip install "numpy>=2.5,<2.6"
import numpy as np

# Six accounts. Column 0 = logins per week, column 1 = seats paid for.
points = np.array([[2.0, 1.0], [3.0, 2.0], [2.0, 4.0],
                   [9.0, 8.0], [10.0, 9.0], [8.0, 10.0]])
names = ["A", "B", "C", "D", "E", "F"]


def distances(points, centres):
    """Straight-line distance from every point (rows) to every centre (columns)."""
    gap = points[:, None, :] - centres[None, :, :]      # shape (6, k, 2): point minus centre
    return np.sqrt((gap ** 2).sum(axis=2))              # Pythagoras on each pair

# ── chunk 2: assign every point to its nearest centre ──
def assign(points, centres):
    return distances(points, centres).argmin(axis=1)    # index of the closest centre, per point

# ── chunk 3: move each centre to the average of its points ──
def update(points, labels, centres):
    new = centres.copy()
    for j in range(len(centres)):
        members = points[labels == j]
        if len(members):                                # an empty group keeps its old centre
            new[j] = members.mean(axis=0)
    return new

# ── chunk 4: repeat until nothing moves, and score the result ──
def kmeans(points, centres, max_iter=50, verbose=True):
    centres = centres.copy()
    for step in range(1, max_iter + 1):
        labels = assign(points, centres)
        new = update(points, labels, centres)
        if verbose:
            print(f"step {step}: labels={labels.tolist()} centres={np.round(new, 2).tolist()}")
        if np.allclose(new, centres):                   # nothing moved: converged
            break
        centres = new
    d = distances(points, centres)
    inertia = (d[np.arange(len(points)), labels] ** 2).sum()   # total squared distance to own centre
    return labels, centres, inertia

# ── chunk 5: check against scikit-learn, then try it on SaaSify ──
from sklearn.cluster import KMeans
from saasify_accounts import generate_accounts

if __name__ == "__main__":
    labels, centres, inertia = kmeans(points, points[[1, 2]])
    print("inertia:", round(float(inertia), 2))

    km = KMeans(n_clusters=2, init=points[[1, 2]], n_init=1).fit(points)
    print("sklearn labels :", km.labels_.tolist(), " inertia:", round(float(km.inertia_), 2))

    df = generate_accounts()
    X = df[["LoginFrequency", "Seats"]].to_numpy(dtype=float)
    X = (X - X.mean(axis=0)) / X.std(axis=0)                # scale first, so no column dominates (page: "Stumble 2")
    rng = np.random.default_rng(0)
    start = X[rng.choice(len(X), 4, replace=False)]
    lab, cen, inertia = kmeans(X, start, verbose=False)
    print("SaaSify 4 groups, group sizes:", np.bincount(lab).tolist(), " inertia:", round(float(inertia), 1))

Read the output. The first three lines are the three steps of Fig. 3b.3 in text. Step 1 gives labels 0, 0, 1, 1, 1, 1 (panel 2), step 2 gives 0, 0, 0, 1, 1, 1 (panel 3), and step 3 repeats it, which is the stop signal. The inertia of 9.33 is the number you worked out by hand. scikit-learn agrees on both the labels and the 9.33.

The last line is the same loop on the real table. SaaSify's 4,400 accounts split into groups of 1,055, 937, 976 and 1,432 with the random starting points we chose. Whether those groups mean anything, and whether a different random start would give different ones, are the questions of the next section.

output of kmeans_from_scratch.pyactual output
step 1: labels=[0, 0, 1, 1, 1, 1] centres=[[2.5, 1.5], [7.25, 7.75]]
step 2: labels=[0, 0, 0, 1, 1, 1] centres=[[2.33, 2.33], [9.0, 9.0]]
step 3: labels=[0, 0, 0, 1, 1, 1] centres=[[2.33, 2.33], [9.0, 9.0]]
inertia: 9.33
sklearn labels : [0, 0, 0, 1, 1, 1]  inertia: 9.33
SaaSify 4 groups, group sizes: [1055, 937, 976, 1432]  inertia: 1026.9

"scikit-learn does this in one line. Why did I just write 60 lines of NumPy?"

— a nine-year engineer who has never needed to implement a sort either

You will use the one line in production. The 60 lines buy you something else: when a segment looks strange you can ask the only useful debugging question, "which move produced this, assign or update, and what were the centres?" You also now know where k-means can go wrong: a bad start (chunk 4's loop only finds the nearest valley), unscaled columns (chunk 1's distance) and the fixed k.

The honest downside: this version is slow. It builds a 4,400 by k by 6 block on every pass and has no smart starting rule. scikit-learn uses k-means++ starting points and compiled code, so it is far faster on large tables. The from-scratch file is for understanding, never for shipping.

Quick reference: k-means

k
The number of groups. You choose it before running; the algorithm does not.
Centre (centroid)
The average position of a group's members. May not be a real account.
Assign
Give each point to its nearest centre, by straight-line distance.
Update
Move each centre to the mean of the points assigned to it.
Converged
A full round moved no centre. Inertia can only fall or stay equal each round, so this always happens.
Inertia
Sum of squared distances from every point to its own centre. Lower means tighter groups, and it always falls when k rises.
Local minimum
k-means finds the nearest good answer, not the best one; different starts can give different groupings.

04 · Watch it breakWhere k-means Breaks: How Many Groups, Which Scale, What Shape

k-means answers three questions you must settle yourself: how many groups, which columns count, and whether groups are round blobs. Get one wrong and it still returns a tidy answer, which is exactly what makes the mistake hard to see.

Where we are in the story: our five chunks produced four groups from SaaSify's accounts, but only because we typed 4. Priya will ask the obvious thing: "why four, and why should I believe them?" This section is the honest answer, in four stumbles, each with a number.

Stumble 1: how many groups? The elbow and the silhouette

Two measures help you choose k. Inertia (from the last section) says how tight the groups are. It always falls as k grows, because more centres means shorter distances, and with 4,400 groups it would be zero. So you look for the elbow: the k after which adding a group stops helping much.

The silhouette score asks a different question for every account: am I closer to my own group than to the next-nearest group? It runs from −1 (probably in the wrong group) through 0 (on the border) to +1 (clearly in the right group). Average it over all accounts and you have one number per k. Fig. 3b.4 shows both for SaaSify, measured by choose_k.py.

2 3 4 5 6 7 8 13,284 5,544 4,130 inertia (lower is tighter) k, the number of groups 1 0.45 2 0.46 3 0.48 4 0.41 5 0.36 6 0.28 7 0.23 8 silhouette (higher is cleaner) k, the number of groups 2
Fig. 3b.4 — Left: inertia for k = 2 to 8 on SaaSify's six scaled columns. Right: the average silhouette for the same k. Both point at k = 4 here, because the generator planted four types.
  1. The elbow at k = 4. Going from 3 groups to 4 cuts inertia from 8,517 to 5,544, a fall of 2,973. Going from 4 to 5 cuts it only by 484 (to 5,060). The line bends at 4 and then flattens.
  2. The silhouette peak at k = 4. The average silhouette is 0.483 at k = 4, higher than 0.456 at k = 3 and 0.408 at k = 5. It drops to 0.227 by k = 8, because extra groups split real groups in half.

Now the honesty. We planted four types, so the elbow is clean. In real data the elbow is often a gentle curve with no corner, and two analysts will point at different k. The silhouette is better but has its own weakness: it likes round, similar-size groups and is happy with k = 2 on almost anything shaped like a dumbbell. Treat both as advice, never as a verdict. The final choice is: how many segments can Priya's team act on?

Stumble 2: one big-number column swallows the others

The distance in chunk 1 adds up gaps in every column. If one column is measured in thousands and another in tens, the thousands decide everything. We saw this problem with gradient descent in Module 02; clustering has it worse, because there is no loss function to compensate.

To make it visible, add one column that product managers love: lifetime spend in dollars (tenure times monthly charge, up to about 10,000). Cluster once raw and once with StandardScaler, which turns every column into "how many standard deviations from average". Fig. 3b.5 shows the outcome, graded against the four hidden types by the adjusted Rand index (ARI, 1.0 = identical grouping, 0 = no better than chance).

column spread (standard deviation) Lifetime spend $ 1,949 Monthly charges $ 33.5 Feature adoption % 20.4 Logins per month 10.1 1 agreement with hidden types (ARI) 0.338 unscaled 0.933 scaled 2
Fig. 3b.5 — Left: the spread (standard deviation) of lifetime spend is 1,949, nearly 200 times that of logins (10.1). Right: k-means with k = 4 agrees with the hidden types at ARI 0.338 unscaled and 0.933 scaled.
  1. One column is 200 times wider. Lifetime spend varies by about 1,949 dollars from account to account, while logins vary by about 10. In a distance sum, a gap of 2,000 on one column drowns a gap of 20 on another. Effectively k-means clusters on spend alone.
  2. Scaling restores the other columns. After StandardScaler every column has spread 1, so each gets an equal vote. Agreement with the hidden types jumps from 0.338 to 0.933.

The fix is one line, applied before clustering, and it belongs inside a pipeline so the same scaling is applied to new accounts later. Note that scaling is a choice, not a law: a column you scale gets an equal vote, so scaling away a column's natural size can be wrong when "bigger spenders" really should count for more. State the choice in the notes of the run (the tracking section does this).

Stumble 3: groups that are not round blobs

Real customer groups are not always blobs. Churners who leave on day 30 and churners who leave on day 300 can form a curved ribbon in the data. k-means measures distance to a centre, so it can only draw straight cuts between centres: it carves space into round-ish cells. Fig. 3b.6 uses two crescent moons plus 20 scattered one-off points.

k-means, k=2: ARI 0.253 DBSCAN, eps 0.15: ARI 1.000 DBSCAN, eps 0.05: ARI 0.022 2 groups, cut straight 1 2 groups, 14 noise 2 28 groups, 237 noise 3
Fig. 3b.6 — 400 points in two crescents plus 20 scattered one-offs. Panel 1: k-means cuts both crescents with a straight line (ARI 0.253). Panel 2: DBSCAN follows the crescents and flags 14 points as noise (ARI 1.000). Panel 3: DBSCAN with a radius that is too small shatters them.
  1. k-means cuts through the shapes. Each colour is one centre's territory, and the boundary between two centres is a straight line. Each group ends up owning part of both crescents. ARI 0.253 is far from the perfect 1.0.
  2. DBSCAN follows the density. It links points that have neighbours within a small radius, so a curved ribbon of close points becomes one group. The red points are flagged as noise rather than forced into a group. ARI is 1.000 on the 400 real points.
  3. One wrong setting ruins it. With the radius 0.05 instead of 0.15, DBSCAN finds 28 groups and calls 237 points noise (ARI 0.022). The radius, called eps, is the price of DBSCAN, which the toolbox section fixes with HDBSCAN.
Fireside chat

Tonight's talk: Inertia and Silhouette argue over the question, "Which of us should choose k?"

Inertia
Silhouette

I am the objective. k-means exists to minimise me. In Fig. 3b.4 my line falls from 13,284 at k = 2 to 5,544 at k = 4. I am cheap, I come free with every fit, and I have a clean formula.

Inertia is the total squared distance to the group centres, the very number k-means lowers; it appears in the left panel of Fig. 3b.4.

And you fall forever. At k = 4,400 you are zero and perfectly useless. I come back down after k = 4: 0.483, then 0.408, then 0.227. I can tell you that you went too far.

Silhouette rises and then falls, so it has a best k; inertia only falls, so it needs a human to spot the bend.

I am fast. You compare every account with every other, so you are slow on a million rows: scikit-learn needs sample_size to keep you affordable. And you love round blobs, which is a prejudice.

Silhouette costs time that grows with the square of the number of accounts, so the page samples 2,000 accounts; it also favours compact, similar-size groups.

Fair. But on pure noise I still get 0.10, while real groups get 0.48. Let us ask Priya how many groups she can staff, and meet again after the noise test.

On six columns of random noise the silhouette stays near 0.10 for every k; the over-reading section measures that. A low silhouette is a warning that no real groups exist.

Stumble 4: the answer depends on where you start

k-means only finds the nearest good answer. Different random starting centres can end in different groupings, because the loop settles into the first valley it reaches. Twenty one-start runs on SaaSify make the point in numbers.

inertia of 20 single-start k-means runs on SaaSify (k = 4), best to worst 5.5k 5.5k 5.5k 5.5k 5.5k 5.5k 5.5k 5.5k 5.5k 5.5k 8.2k 8.2k 8.2k 8.2k 8.3k 8.3k 8.3k 9.8k 9.8k 9.8k runs sorted by inertia; the 10 green bars reached the best answer, 5,544 1 2
Fig. 3b.7 — The inertia of 20 k-means fits with k = 4, each with one random start (seeds 0 to 19), sorted. Ten reach 5,544; the other ten stop at 8,222 to 9,817.
  1. Half the starts find the best answer. Ten of the 20 bars are 5,544, the lowest inertia found. They agree with the hidden types at ARI 0.935.
  2. Half the starts get stuck. The other ten stop at inertia 8,222 to 9,817, and their ARI falls to as low as 0.589. A single run would have given you a coin-flip between a good and a poor segmentation.

The fix is built into scikit-learn. n_init=10 runs the whole algorithm ten times from different starts and keeps the one with the lowest inertia. The default starting rule, k-means++, also spreads the first centres apart on purpose. Every scikit-learn k-means call in this module sets n_init=10 and random_state=0, so reruns agree.

Questions you might be asking now

Three slow answers about choosing k. The same six accounts as before are used: group one is A (2, 1), B (3, 2), C (2, 4) and group two is D (9, 8), E (10, 9), F (8, 10).

What exactly is the silhouette score, and how is it calculated for one account?

For one account it is (b − a) / max(a, b), where a is the average distance to its own group-mates and b is the average distance to the nearest other group. Near +1 means clearly in the right group.

Work it out for account A, using the distances in Fig. 3b.8:

  1. Distances to its own group. A to B is 1.41 and A to C is 3.00. Their average is (1.41 + 3.00) / 2 = 2.21. Call this a.
  2. Distances to the other group. A to D is 9.90, A to E is 11.31 and A to F is 10.82. Their average is 10.68. Call this b.
  3. Compare. (b − a) = 10.68 − 2.21 = 8.47. Divide by the bigger of the two, max(a, b) = 10.68, which gives 0.793.
  4. Average over all six. The six scores are 0.793, 0.803, 0.698, 0.793, 0.821 and 0.767, so the silhouette of the whole clustering is 0.779.
account A (2, 1): how far to its own group, how far to the other group to B 1.41 to C 3.00 to D 9.90 to E 11.31 to F 10.82 a = 2.21 b = 10.68 silhouette(A) = (10.68 - 2.21) / 10.68 = 0.793 1 2
Fig. 3b.8 — Account A's distances to its own group (green bars) and to the other group (red bars), with their averages as dashed lines. The silhouette is the gap between the lines divided by the larger one.
  1. The own-group average a = 2.21. Two short bars, 1.41 (to B) and 3.00 (to C). Small a means A is snug with its group.
  2. The other-group average b = 10.68. Three long bars. Large b means the other group is far away. A big gap between the lines gives a silhouette near 1.

The honest limit: this works on any grouping you hand it, good or bad. A silhouette of 0.779 on six well-separated points is flattering; on SaaSify's real table, the best k scores 0.483, and a table of pure noise still scores about 0.10.

Silhouette per account is how much closer it is to its own group than to the next one, as a fraction between −1 and 1.

Why does inertia always fall when I add a group? Is lower always better?

Adding a centre can never make any account farther from its nearest centre, so inertia can only drop or stay equal. Lower is better only when you compare the same k.

Take the six accounts. With k = 2 the inertia is 9.33. With k = 3, split the left group by making C its own centre:

  1. Old total, k = 2. 1.89 (A) + 0.56 (B) + 2.89 (C) + 1 + 1 + 2 = 9.33.
  2. New centres, k = 3. A and B share a centre at (2.5, 1.5); C sits alone at (2, 4); D, E, F stay at (9, 9).
  3. New total. A is 0.5² + 0.5² = 0.5 away squared, B is 0.5² + 0.5² = 0.5, C is 0, plus 4 from the right group. Total 5.0, down from 9.33.

At k = 6 every account has its own centre and the total is 0. A perfect score for a useless result, which is why the elbow is read as "where does it stop falling quickly", and why silhouette is added to catch the over-split.

Inertia always falls with k; look for where the fall slows, not where it is lowest.

Will k-means give me the same groups if I run it twice?

Not unless you fix the random start. With a single random start, ten out of 20 runs on SaaSify found the best grouping and ten did not (Fig. 3b.7).

20 single-start runs against ten-restart runs, SaaSify, k = 4
SettingInertia rangeAgreement with hidden types (ARI)Reproducible?
n_init=1, 20 different seeds5,544 to 9,8170.589 to 0.935Only if the seed is fixed
n_init=10, random_state=05,5440.935Yes, same every run

Always set n_init=10 and random_state; a segmentation that changes on every run cannot be given a name.

Quick reference: the four k-means stumbles

Choosing k
Plot inertia (look for the elbow) and silhouette (look for the peak) for k = 2 to 8. Both are advice; the final choice is how many segments the business can use.
Silhouette
(b − a) / max(a, b) per account: −1 wrong group, 0 border, +1 clearly right. Costs time that grows with the square of the number of accounts.
Scaling
Use StandardScaler before any distance-based method. On SaaSify, unscaled lifetime spend dropped agreement from 0.933 to 0.338.
Shapes
k-means draws straight boundaries between centres. Curved or very uneven groups need a density method such as DBSCAN or HDBSCAN.
Starts
One random start finds the best answer about half the time. n_init=10 and a fixed random_state fix it.

05 · The industry toolThe Clustering Toolbox: Shapes, Maps, Oddballs and Names

Real customer work needs four tools beyond plain k-means: a method that finds curved groups and ignores strays, a way to draw six columns on a flat screen, a detector for accounts that fit nowhere, and a discipline for naming groups without lying. Without them, segmentation is a slide with colours on it.

Where we are in the story: Fig. 3b.6 showed k-means failing on curves, and Priya has a second need that is not a grouping at all: she wants to see the 4,400 accounts, and to spot "weird" ones before they pollute any average. This section builds each tool on a tiny example first, then on SaaSify, then ends with the part that matters most to Priya, the names.

DBSCAN and HDBSCAN: groups defined by density

DBSCAN (density-based spatial clustering) does not use centres. It asks of every point: how many neighbours are within a radius eps? If at least min_samples are, the point is a core point, and core points that are near each other join the same group. Points near a core point but with few neighbours of their own join as edges. Points near nothing are labelled -1: noise.

That gives it three powers k-means lacks: it follows curved shapes (panel 2 of Fig. 3b.6), it chooses the number of groups itself, and it admits that some points belong nowhere. It costs you eps, which is hard to pick and ruins everything when wrong, and it uses one eps for the whole table, so groups of very different density get treated badly.

DBSCAN on the two crescents: eps = 0.15, min_samples = 5 1 2 3 points within 0.15 1 core: 11 points inside 5 or more: a core point 2 edge: 4 points inside fewer than 5 3 noise: 2 points inside fewer than 5 noise points (red) join no group
Fig. 3b.9 — Three points of the crescent data, each with a circle of radius eps = 0.15. The count beside each marker is how many points (itself included) fall inside its circle; the rule is 5 or more for a core point.
  1. A core point. 11 points lie inside its circle, so it is a core point. Core points that overlap each other chain together, and that chain is how a whole curved crescent becomes one group.
  2. An edge point. Only 4 points are inside its circle, fewer than 5, so it is not a core point. It sits within reach of a core point, so it still joins that group, as its edge.
  3. A noise point. Just 2 points are in its circle (itself and one other) and no core point is within reach. DBSCAN labels it -1 and refuses to put it in a group.

HDBSCAN (hierarchical DBSCAN) tries every eps at once and keeps the groups that stay stable across a range. You give it only min_cluster_size: the smallest group worth naming. scikit-learn includes it as sklearn.cluster.HDBSCAN since version 1.3 (we use 1.9.1), so you no longer need the separate hdbscan package for ordinary work.

The program below uses the same measure (ARI, the adjusted Rand index) that you met in Fig. 3b.5: 1.0 means the same grouping as the truth, 0 means no better than chance. Read each printed line as "how well did this method recover the two crescents?".

Step-by-step: what shapes_dbscan.py does, in plain English
  1. make_moons generates 400 points in two interlocking crescents, and truth records which crescent each belongs to.
  2. 20 random points scattered over the whole area are appended and marked -1, meaning "belongs to no group".
  3. report counts the groups found, counts points labelled -1 (noise), and grades the 400 real points with the adjusted Rand index.
  4. Five runs: k-means with k = 2; DBSCAN with a good eps (0.15), a too-small one (0.05) and a too-big one (0.5); and HDBSCAN, which has no eps to choose.
  5. copy=True silences a scikit-learn warning about a default that is changing in version 1.10.
shapes_dbscan.pyruns offline
# pip install "scikit-learn>=1.9,<2" "numpy>=2.5,<2.6"     # sklearn.cluster.HDBSCAN is built in since 1.3
"""k-means on two crescent-shaped groups, then DBSCAN and HDBSCAN on the same points."""
import numpy as np
from sklearn.cluster import DBSCAN, HDBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score

X, truth = make_moons(n_samples=400, noise=0.06, random_state=0)
# 20 scattered "one-off" points that belong to no group
rng = np.random.default_rng(0)
X = np.vstack([X, rng.uniform([-1.5, -1.0], [2.5, 1.5], size=(20, 2))])
truth = np.concatenate([truth, np.full(20, -1)])

def report(name, labels):
    groups = sorted(set(labels) - {-1})
    noise = int((labels == -1).sum())
    ari = adjusted_rand_score(truth[truth >= 0], labels[:400])
    print(f"{name:22} groups={len(groups)} noise_points={noise:3d}  ARI on the 400 real points={ari:.3f}")

report("k-means (k=2)", KMeans(2, n_init=10, random_state=0).fit_predict(X))
report("DBSCAN eps=0.15", DBSCAN(eps=0.15, min_samples=5).fit_predict(X))
report("DBSCAN eps=0.05 (too small)", DBSCAN(eps=0.05, min_samples=5).fit_predict(X))
report("DBSCAN eps=0.5 (too big)", DBSCAN(eps=0.5, min_samples=5).fit_predict(X))
report("HDBSCAN (no eps)", HDBSCAN(min_cluster_size=20, copy=True).fit_predict(X))
output of shapes_dbscan.pyactual output
k-means (k=2)          groups=2 noise_points=  0  ARI on the 400 real points=0.253
DBSCAN eps=0.15        groups=2 noise_points= 14  ARI on the 400 real points=1.000
DBSCAN eps=0.05 (too small) groups=28 noise_points=237  ARI on the 400 real points=0.022
DBSCAN eps=0.5 (too big) groups=1 noise_points=  6  ARI on the 400 real points=0.000
HDBSCAN (no eps)       groups=2 noise_points= 22  ARI on the 400 real points=0.966

Read the output. Line 1 repeats Fig. 3b.6: k-means with k = 2 scores 0.253. Line 2 shows DBSCAN with eps 0.15: two groups, 14 points flagged as noise, ARI 1.000. Lines 3 and 4 are the price of DBSCAN: eps 0.05 gives 28 groups and 237 noise points, eps 0.5 merges everything into one group. Line 5 is HDBSCAN with no eps at all: two groups, 22 noise points, ARI 0.966, slightly less perfect but far safer.

PCA: drawing six columns on a flat screen

Where we are in the story: Priya cannot look at six columns. She can look at two. PCA (principal component analysis) finds the two directions along which the accounts spread out the most, and draws every account by its position along those two. We start with just two columns to see the idea, then do all six.

Take logins and seats. In SaaSify they move together: the correlation is 0.861, so accounts with many seats log in a lot. Points lie along a diagonal band. PCA finds that diagonal as its first axis, (0.707, 0.707), meaning "equal parts logins and seats". That one axis carries 93% of all the variation, and the remaining 7% sits across the band. If you kept only the first axis, you would lose 7% and halve the columns.

With six columns the same idea runs in six dimensions. The three ways to compute it in pca_by_hand.py give identical numbers, so PCA is not magic: it is the eigen-decomposition of the covariance table (the "hood" section gives the math). Fig. 3b.10 shows the result for SaaSify.

variance each axis carries 61% PC1 19% PC2 12% PC3 3% PC4 2.3% PC5 2.1% PC6 first two axes: 61.3% + 19.3% = 80.6% 1 every account, squeezed to two axes PC1 (61.3%) to the right = less active, smaller accounts 2
Fig. 3b.10 — Left: the share of variation carried by each of the six PCA axes (61%, 19%, 12%, 3%, 2%, 2%). Right: 900 of the 4,400 accounts drawn by their position on the first two axes, coloured by the hidden type (red: stuck onboarding, orange: loyal legacy, green: quiet small, blue: power team).
  1. Two axes carry 80.6%. PC1 holds 61.3% of the variation and PC2 another 19.3%. The remaining four together hold under 20%, so a two-dimensional picture loses less than a fifth of the story. This is the explained variance.
  2. The groups are visible. The four types separate into distinct clouds, even though PCA was never told about them. PC1 is mostly activity and size: logins, adoption and seats all load at about −0.48. PC2 is mostly tickets (+0.73) against tenure (−0.60): new accounts with many support tickets sit high.

Read the map with care. An axis is a blend of columns, not a column. Distances on the map are only approximately the real distances. PCA draws straight-line shadows, so curved structure gets squashed. For that, tools like t-SNE and UMAP draw non-linear maps, which look beautiful and are easy to over-read: the sizes of gaps and the sizes of blobs on a t-SNE picture mean nothing. Use PCA for explaining and checking, UMAP for exploring.

PC1: activity and size -0.22 Tenure -0.46 MthlyCharges +0.17 SupportTickets -0.49 Login -0.49 FeatureAdoption -0.48 Seats PC2: tickets against tenure -0.60 Tenure +0.27 MthlyCharges +0.73 SupportTickets +0.06 Login +0.03 FeatureAdoption +0.18 Seats bar to the left = negative loading, to the right = positive 1 2
Fig. 3b.11 — What the first two PCA axes are made of. Each bar is one column's weight (loading) on the axis, from pca_by_hand.py.
  1. PC1 is "how much the account does". Logins (−0.49), feature adoption (−0.49), seats (−0.48) and monthly charge (−0.46) all pull the same way. The sign is arbitrary: an account far to the left of the map is big and active, far to the right small and quiet.
  2. PC2 is "new and complaining". Tickets (+0.73) pull up and tenure (−0.60) pulls down, so an account with many tickets and a short history sits high on the map. This is the stuck-in-onboarding cloud of Fig. 3b.10.
Step-by-step: what pca_by_hand.py does, in plain English
  1. Load the 4,400 accounts and scale the six columns, so each has mean 0 and spread 1 (PCA needs centred data).
  2. np.cov(X, rowvar=False) builds the 6 by 6 covariance table: for every pair of columns, how much they rise and fall together.
  3. np.linalg.eigh returns the eigenvectors (the new axes) and eigenvalues (how much spread each axis carries). We sort them largest first.
  4. Dividing each eigenvalue by their total gives the share of all the variation each axis explains.
  5. np.linalg.svd(X) does the same job on the data directly. The squared singular values divided by their total match the first answer.
  6. PCA(n_components=2) is scikit-learn's version. Its two shares match the first two numbers above.
  7. X @ vecs[:, :2] projects every account onto the first two axes: two coordinates per account, ready to plot. np.abs ignores the sign flips the algorithms are free to choose.
  8. The last lines print what each axis is made of (loadings) and where each hidden type lands on the map.
pca_by_hand.pyruns offline
# pip install "scikit-learn>=1.9,<2" "numpy>=2.5,<2.6"
"""PCA three ways on SaaSify: from the covariance matrix, from SVD, and with scikit-learn."""
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

from saasify_accounts import NUM_COLS, generate_accounts

df = generate_accounts()
X = StandardScaler().fit_transform(df[NUM_COLS].to_numpy(dtype=float))   # centred, unit spread

# 1. covariance matrix -> its eigenvectors are the new axes, eigenvalues are how much each carries
cov = np.cov(X, rowvar=False)                         # 6 x 6: how every column moves with every other
vals, vecs = np.linalg.eigh(cov)                      # eigh = eigen-decomposition for symmetric matrices
order = np.argsort(vals)[::-1]                        # biggest first
vals, vecs = vals[order], vecs[:, order]
print("explained variance ratio (covariance):", np.round(vals / vals.sum(), 3).tolist())

# 2. SVD of the data itself gives the same answer without ever building the covariance matrix
U, S, Vt = np.linalg.svd(X, full_matrices=False)
print("explained variance ratio (SVD)       :", np.round(S**2 / (S**2).sum(), 3).tolist())

# 3. scikit-learn
pca = PCA(n_components=2).fit(X)
print("explained variance ratio (sklearn)   :", np.round(pca.explained_variance_ratio_, 3).tolist())

# The 2-d picture: project every account onto the first two axes
mine = X @ vecs[:, :2]
same = np.allclose(np.abs(mine), np.abs(pca.transform(X)), atol=1e-8)       # axes may flip sign, so compare sizes
print("my 2-d coordinates match sklearn's (up to sign):", same)

print("\nwhat each axis is made of (loadings):")
for i in range(2):
    pairs = sorted(zip(NUM_COLS, vecs[:, i]), key=lambda p: -abs(p[1]))
    print(f"  PC{i+1}: " + ", ".join(f"{n} {w:+.2f}" for n, w in pairs[:4]))
for i, t in enumerate(["power team", "quiet small", "stuck onboarding", "loyal legacy"]):
    m = df["TrueType"] == t
    print(f"  {t:17} mean position = ({mine[m,0].mean():+.2f}, {mine[m,1].mean():+.2f})")
output of pca_by_hand.pyactual output
explained variance ratio (covariance): [0.613, 0.193, 0.118, 0.032, 0.023, 0.021]
explained variance ratio (SVD)       : [0.613, 0.193, 0.118, 0.032, 0.023, 0.021]
explained variance ratio (sklearn)   : [0.613, 0.193]
my 2-d coordinates match sklearn's (up to sign): True

what each axis is made of (loadings):
  PC1: LoginFrequency -0.49, FeatureAdoption -0.49, Seats -0.48, MonthlyCharges -0.46
  PC2: SupportTickets +0.73, TenureMonths -0.60, MonthlyCharges +0.27, Seats +0.18
  power team        mean position = (-2.99, +0.50)
  quiet small       mean position = (+1.61, -0.48)
  stuck onboarding  mean position = (+1.70, +1.86)
  loyal legacy      mean position = (-0.67, -0.77)

Read the output. Lines 1 to 3 are the same numbers from three methods: covariance, SVD and scikit-learn all give 0.613 and 0.193 for the first two axes, which is the proof the by-hand code is right. Line 4 confirms the coordinates agree up to sign. The loadings show what each axis is made of. The last four lines give the average position of each hidden type: power teams sit far to the left at (−2.99, 0.50), the stuck-onboarding accounts are top right at (1.70, 1.86).

Isolation Forest: the account that fits nowhere

Sometimes the useful finding is not a group but a stranger. Isolation Forest works by randomly cutting the table: pick a column at random, pick a random cut value between that column's smallest and biggest value, and keep cutting. An ordinary account sits in a crowd and takes many cuts to separate from its neighbours. A strange account is alone, so a few cuts isolate it. The average number of cuts is the score.

We plant 12 fake bot accounts (400 logins a month in a table where the real average is about 12) and see whether it finds them.

Step-by-step: what anomalies.py does, in plain English
  1. Build 12 fake bot accounts: one month of tenure, the cheapest plan, no tickets and 400 logins a month, far beyond any real account.
  2. Stack them under the real accounts and scale all six columns together.
  3. IsolationForest(n_estimators=200, contamination=0.005) grows 200 random trees. contamination says what share of rows to flag, and here we expect about half a percent.
  4. predict returns -1 for flagged rows. score_samples returns a score; we negate it so that higher means odder.
  5. Count how many of the last 12 rows (the bots) were flagged, then list the three oddest accounts.
  6. depth asks each of the 200 trees how many cuts it took to reach one account (decision_path lists the nodes visited, minus the root) and averages them. We do it for a bot and for an account with a median number of logins.
anomalies.pyruns offline
# pip install "scikit-learn>=1.9,<2" "numpy>=2.5,<2.6" "pandas>=3,<4"
"""Isolation Forest: find accounts that look like nobody else."""
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler

from saasify_accounts import NUM_COLS, generate_accounts

df = generate_accounts()

# ── plant 12 accounts that look like nobody else (a bot signing up and hammering the product) ──
odd = pd.DataFrame({"AccountID": [f"BOT-{i}" for i in range(12)], "TenureMonths": 1, "MonthlyCharges": 20.0,
                    "SupportTickets": 0, "LoginFrequency": 400, "FeatureAdoption": 3.0, "Seats": 1})
both = pd.concat([df[["AccountID"] + NUM_COLS], odd], ignore_index=True)
Xs = StandardScaler().fit_transform(both[NUM_COLS])
iso = IsolationForest(n_estimators=200, contamination=0.005, random_state=0).fit(Xs)
flag = iso.predict(Xs) == -1                                   # -1 means "odd"
score = -iso.score_samples(Xs)                                 # higher = easier to isolate = odder
print("flagged", int(flag.sum()), "accounts; planted bots caught:", int(flag[-12:].sum()), "of 12")
top = both.assign(oddness=score).sort_values("oddness", ascending=False).head(3)
print(top[["AccountID", "LoginFrequency", "oddness"]].round(3).to_string(index=False))

# ── how many random cuts does it take to isolate one account? (average over the 200 trees) ──
def depth(model, X, row):
    total = 0
    for tree in model.estimators_:
        total += tree.decision_path(X[row:row + 1]).sum() - 1      # nodes visited, minus the root
    return total / len(model.estimators_)

bot, typical = len(df), int(both["LoginFrequency"].sub(both["LoginFrequency"].median()).abs().argmin())
print("average cuts to isolate a bot account   :", round(depth(iso, Xs[:, :], bot), 1))
print("average cuts to isolate a typical account:", round(depth(iso, Xs[:, :], typical), 1))
output of anomalies.pyactual output
flagged 23 accounts; planted bots caught: 12 of 12
AccountID  LoginFrequency  oddness
   BOT-11             400    0.678
    BOT-8             400    0.678
    BOT-9             400    0.678
average cuts to isolate a bot account   : 5.1
average cuts to isolate a typical account: 7.9

Read the output. It flagged 23 accounts, and all 12 planted bots are among them (the three shown have the highest oddness, 0.678). The other 11 flagged accounts are real, merely unusual. That number is not a discovery but a setting: contamination=0.005 told it to flag about half a percent, so about 22 rows. Choose the flag rate by how many accounts a human can review, and review before acting.

average random cuts needed to isolate one account (200 trees) planted bot (400 logins) 5.1 typical account (12 logins) 7.9 trees stop at 8 cuts 1 2 fewer cuts = easier to isolate = odder
Fig. 3b.12 — The last two output lines as bars: the average number of random cuts that isolates a bot (5.1) and a typical account (7.9).
  1. The bot is isolated early. On average 5.1 cuts put an account with 400 logins on its own, because almost every random cut lands between it and the crowd.
  2. The typical account sits against the limit. It needs 7.9 cuts on average. Each tree stops growing at 8 cuts (a depth limit scikit-learn sets from the sample size), so the typical account runs into that ceiling, and the real gap is wider than the bars show.

From numbered groups to named segments, and the danger of over-reading them

Where we are in the story: we now have groups labelled 0, 1, 2 and 3. Priya cannot say "group 2" to the board. She needs names, and naming is where clustering becomes a business artefact, and where a mistake looks most convincing. The names come from the average account of each group, in real units, as in the table below (produced in the next section by segment_and_track.py).

The average account of each group, real units, with the name a human gave it and the churn rate that name hides
NameAccountsTenure (months)Monthly chargeTicketsLoginsSeatsReal churn
Power teams99927.4$118.61.228.225.04.6%
Loyal veterans1,11453.4$84.11.814.011.10.6%
Quiet small teams1,72820.1$40.01.54.94.12.0%
Stuck in onboarding5594.0$72.06.34.15.951.0%

The names follow a simple rule: look at what is most extreme about each group's average account and name it for that, in a word the business already uses. Power teams have the most logins. The stuck-in-onboarding group has the shortest tenure and the most tickets. Notice what the names do not contain: the churn column, which was not used to build the groups, shows 51% of stuck-in-onboarding accounts leaving against 0.6% of loyal veterans. A segmentation that separates churn this sharply, without ever seeing it, is worth acting on.

real churn rate of each segment (the churn column was never used to make them) Stuck in onboarding (559) 51.0% Power teams (999) 4.6% Quiet small teams (1,728) 2.0% Loyal veterans (1,114) 0.6% 1 2
Fig. 3b.14 — The real churn rate of each named segment, from the table above. Account counts are in brackets.
  1. One segment is on fire. 51.0% of the 559 stuck-in-onboarding accounts left, against 4.6% of power teams, 2.0% of quiet small teams and 0.6% of loyal veterans. The overall rate is 8.45%.
  2. The check is outside the clustering. The groups were built without the churn column, so this difference is evidence that the segments describe something real, the fourth check of the bubble below.

Now the danger. Run k-means on pure noise and the algorithm still returns groups, and you could name those too. The only warning is the silhouette.

Step-by-step: what noise_segments.py does, in plain English
  1. Make 4,400 rows of six random columns: pure noise with no real groups.
  2. Run k-means for k = 2 to 5 and compute the silhouette of each result.
  3. Run k-means with k = 4 on SaaSify's six real columns and compute its silhouette, for comparison.
noise_segments.pyruns offline
# pip install "scikit-learn>=1.9,<2" "numpy>=2.5,<2.6"
"""The danger: k-means on pure noise still hands back tidy groups, with a low silhouette as the only warning."""
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

from saasify_accounts import NUM_COLS, generate_accounts

df = generate_accounts()

# ── six columns of nothing, versus SaaSify's real six columns ──
rng = np.random.default_rng(1)
noise = rng.normal(size=(4400, 6))                            # six columns of nothing
for k in (2, 3, 4, 5):
    km = KMeans(k, n_init=10, random_state=0).fit(noise)
    print(f"noise  k={k}  silhouette={silhouette_score(noise, km.labels_, sample_size=2000, random_state=0):.3f}")
Xr = StandardScaler().fit_transform(df[NUM_COLS])
km = KMeans(4, n_init=10, random_state=0).fit(Xr)
print(f"real   k=4  silhouette={silhouette_score(Xr, km.labels_, sample_size=2000, random_state=0):.3f}")
output of noise_segments.pyactual output
noise  k=2  silhouette=0.112
noise  k=3  silhouette=0.105
noise  k=4  silhouette=0.102
noise  k=5  silhouette=0.106
real   k=4  silhouette=0.483

Read the output. Four fits on six columns of nothing give silhouettes of 0.112, 0.105, 0.102 and 0.106: all near 0.10. The real SaaSify table scores 0.483. A silhouette near 0.1 means "these groups are borders drawn through one cloud". A table full of random numbers produced "segments" that a hurried analyst could have named Heavy, Light, Medium and Occasional.

average silhouette: pure noise against the real table 0.112 noise k=2 0.105 noise k=3 0.102 noise k=4 0.106 noise k=5 0.483 SaaSify k=4 0.25 1 2
Fig. 3b.13 — Silhouette of k-means on random noise (four bars, 0.102 to 0.112) against SaaSify's real table (0.483), with the rule-of-thumb line at 0.25.
  1. Noise sits near 0.10 whatever k you pick. The four red bars are all between 0.102 and 0.112. The algorithm returned tidy groups every time. Only this number says they are empty.
  2. Real structure clears the line. The green bar is 0.483, well above the dashed 0.25 line that practitioners commonly treat as "some real structure". Below that line, treat groups as borders, not types.

"If the algorithm always hands me groups, how do I know the segments are real and not just a nice story?"

— Marcus Vance, who has seen a lot of consultant slides

You cannot prove it, but you can run four checks, and a segmentation that survives all four is worth a name. Is the silhouette clearly above about 0.25 (0.48 here, against 0.10 for noise)? Is it stable (different seeds, bootstrap samples and k = 3 or 5 give mostly the same groups)? Do the groups differ on something the clustering never saw, such as churn (0.6% against 51% here)? And can a person say what to do differently for each?

The honest downside: even a passing segmentation is a summary, not a law of nature. Customers move between segments, the cut between "quiet small" and "loyal veteran" is a line the algorithm drew, and the names can make a manager treat a fuzzy border as a wall. Re-run quarterly, and keep the numbers next to the names.

Anatomy of the clustering call — the one line to know by heart
labels = KMeans(1
    n_clusters=4,2
    n_init=10,3
    random_state=0,4
).fit_predict(X)5
  1. KMeans. The estimator class from sklearn.cluster. Mistake: calling it on a table with text columns; every column must be numbers, usually scaled.
  2. n_clusters. The k. Mistake: treating the elbow as the answer. It is an input to your judgement, not a result.
  3. n_init. How many restarts to try, keeping the best. Mistake: leaving it at 1 and getting a different segmentation each run (Fig. 3b.7).
  4. random_state. Fixes the random starts. Mistake: omitting it, so tomorrow's segments differ from today's and nobody can compare.
  5. .fit_predict(X). Fits and returns one label per row in one go. Mistake: passing unscaled X, or including the churn column, which would build groups out of the answer.
Decision table: which unsupervised tool for which question
ToolChoose whenAvoid whenSetting you must choose
k-meansRoughly round groups, big tables, you need a fixed number of segments and a centre profileCurved groups, strays, groups of very different sizek
DBSCANCurved groups, noise to ignore, similar densitiesGroups of very different density; you cannot guess a distance scaleeps, min_samples
HDBSCANCurved groups, noise, different densities, no idea what eps should beYou must have every point in a group (it labels strays -1)min_cluster_size
PCADraw or compress many numeric columns; check a clusteringThe structure is curved; you need column-level meaningNumber of components
Isolation ForestSpot odd rows without labelled examplesYou need to know why a row is odd without extra workcontamination

Quick reference: the clustering toolbox

DBSCAN
Groups = dense regions. Core point: at least min_samples neighbours within eps. Label -1 = noise.
HDBSCAN
DBSCAN over every eps, keeping stable groups. Only min_cluster_size to choose. In scikit-learn since 1.3.
PCA
New axes ordered by the spread they carry. SaaSify: 61.3% and 19.3% for the first two. Needs scaled columns.
Explained variance
The share of total spread an axis keeps. Keep enough axes for about 80% when compressing.
Isolation Forest
Random cuts isolate odd rows quickly; fewer cuts means odder. contamination sets the flag rate.
Naming
Name a group by its most extreme average column, in the business's own words. Check silhouette (> ~0.25), stability, an outside column (churn) and an action for each name.
Noise test
k-means on random noise scores a silhouette near 0.10. Below ~0.25, treat the groups as borders, not types.

06 · Experiment trackingMLflow and Weights & Biases: Never Lose the Best Run Again

Experiment tracking writes down every training run: what settings went in, what scores came out, and which files were saved. Without it, "the model that scored 0.92 last month" is a memory, and memories cannot be re-run.

Where we are in the story: Dev Okafor's problem from Fig. 3b.1, marker 2. Last month's best churn model scored 0.92 and nobody can rebuild it. This is not carelessness. A sweep of six settings produces six models and six numbers, and by Friday nobody remembers which was which. We fix it before it happens again.

What a run has to remember

A run is one training attempt. To rebuild it later you need five things, and the table says what MLflow calls each.

What one run records, in MLflow's words, with SaaSify examples
MLflow wordPlain meaningExample from our sweep
Parameter (param)A setting you chose before traininglearning_rate = 0.1, max_depth = 3
MetricA number the run produced, can be logged many timesval_auc = 0.9194
ArtifactA file the run savedthe trained model, a segment table, a chart
TagA free-text label for finding runs latermodel_uri, "who ran this", a git commit
ExperimentA named folder of related runssaasify-churn-sweep

One more idea sits above runs. The model registry gives a trained model a stable name, numbered versions and movable labels called aliases. Serving code loads models:/saasify-churn@champion and never has to know which run produced it. Promoting a better model is moving the alias, and rolling back is moving it back. Module 12 shows a FastAPI service loading exactly such an alias; here we own the tracking.

EXPERIMENT · 6 runs saasify-churn-sweep xgb-lr0.1-d3 val 0.9194 xgb-lr0.02-d3 val 0.9189 xgb-lr0.05-d3 val 0.9176 xgb-lr0.05-d5 val 0.9171 +2 more, lowest 0.9144 BEST RUN xgb-lr0.1-d3 params: lr 0.1, depth 3 val_auc 0.9194 test_auc 0.9273 artifact: model/ tag: model_uri REGISTRY saasify-churn version 1 alias: champion serving loads: models:/saasify-churn @champion pick promote 1 2 3 one run = params in, metrics out, files saved; the registry gives one run's model a stable name
Fig. 3b.15 — The sweep of this section in MLflow's three layers. An experiment holds six runs. The best run by validation AUC (0.9194) is picked. Its model is promoted into the registry as version 1 with the alias champion.
  1. The experiment: six runs, six numbers. Three learning rates (0.02, 0.05, 0.1) times two depths (3, 5). Validation AUC runs from 0.9194 down to 0.9144. Every row is a query result, not a memory.
  2. The best run carries everything. Its settings (rate 0.1, depth 3), its scores (0.9194 on validation, 0.9273 on the test split) and its saved model. This is what Dev could not recover last month.
  3. The registry names it. Version 1 of saasify-churn, with the alias champion. A service that loads the alias gets this model today and the next champion tomorrow, without a deploy.

Where MLflow keeps it all

MLflow splits storage in two. Metadata (params, metrics, tags, registry entries) goes in a backend store. Artifacts (models, files) go in an artifact folder. For one person the backend can be a single SQLite file, as in our scripts: out/mlflow.db, no server and no sign-up. For a team you run mlflow server over PostgreSQL and S3, and the code changes by one line, the tracking URI.

One current detail: as of October 2026 the MLflow docs call the old default, a plain ./mlruns folder of files, a legacy backend in maintenance mode, and the model registry needs a database backend. So start with SQLite, not the file store. Our scripts also leave artifacts under mlruns/ next to where you run them. To browse the runs in a web page, run mlflow ui --backend-store-uri sqlite:///out/mlflow.db (not run here; it starts a web server).

"This is a spreadsheet with extra steps. I can just append a row to a CSV after each run."

— Dev Okafor, three weeks before the lost model

A CSV does record the score. What it cannot hold is the model file, the data version, the plot, two colleagues writing at once, or a query like "all runs with depth 3 sorted by validation AUC". Dev's CSV had the score 0.92 and no learning rate. MLflow records the settings in the same statement that starts the run, so forgetting is harder than remembering.

The honest downside: tracking is another thing to run and learn, and for a one-off analysis a CSV is the right call. MLflow pays back when more than one person trains, or when you retrain on a schedule, or when anyone will ever ask "why did we choose this model?".

Logging the churn sweep

Before the full sweep, here is the smallest possible run: one setting in, one number out, read back as a table. If you have understood these ten lines you have understood MLflow's core.

Step-by-step: what mlflow_hello.py does, in plain English
  1. Point MLflow at a SQLite file, out/mlflow.db, and name the experiment hello.
  2. with mlflow.start_run(...) opens one run and closes it automatically when the block ends.
  3. log_param records a setting you chose. log_metric records a number the run produced.
  4. search_runs reads the experiment's runs back as a pandas table, one row per run.
mlflow_hello.pyruns offline
# pip install "mlflow>=3,<4"        # runs offline, no server
"""The smallest possible MLflow run: one setting in, one number out, then read it back."""
from pathlib import Path

import mlflow

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)
mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")
mlflow.set_experiment("hello")

with mlflow.start_run(run_name="first-run"):
    mlflow.log_param("learning_rate", 0.1)       # a setting I chose
    mlflow.log_metric("val_auc", 0.9194)         # a number the run produced

print(mlflow.search_runs(experiment_names=["hello"])[["tags.mlflow.runName", "params.learning_rate", "metrics.val_auc"]].to_string(index=False))
output of mlflow_hello.pyactual output
tags.mlflow.runName params.learning_rate  metrics.val_auc
          first-run                  0.1           0.9194

The run name, the setting and the number all come back from the database. The sweep below is the same pattern repeated six times with a real model.

Here is the cure for Dev's problem. It reruns Module 03's churn model over three learning rates and two depths, logs each as a run, picks the best by validation AUC, and registers it. We choose by validation, not test, so the test slice stays an honest final check (the discipline from Module 03).

Step-by-step: what track_churn_sweep.py does, in plain English
  1. Import MLflow, itertools (to loop over every combination of two lists) and Module 03's helper functions load and make_xgb from churn_data.py in the code folder.
  2. Point MLflow at out/mlflow.db and name the experiment saasify-churn-sweep. load() builds Module 03's data, splits and preprocessing.
  3. Loop over three learning rates and two tree depths: six runs. Each with mlflow.start_run block is one run, named after its settings.
  4. Inside a run: build the model, set the depth, fit it with early stopping on the validation slice.
  5. log_params records the settings and the data size and seed. log_metrics records the validation AUC, the test AUC and the round where early stopping stopped.
  6. mlflow.xgboost.log_model saves the trained model as an artifact of the run, and a tag remembers where it is.
  7. After the loop, search_runs(..., order_by=["metrics.val_auc DESC"]) returns all six runs as a table, best first. We print it.
  8. The first row is the best run by validation AUC. register_model gives that run's model the name saasify-churn, and the alias champion is set to that version.
track_churn_sweep.pyruns offline
# pip install "mlflow>=3,<4" "xgboost>=3,<4" "scikit-learn>=1.9,<2" "pandas>=3,<4"      # verified Oct 2026
"""Log module 03's churn model as a sweep of MLflow runs, find the best one, and register it."""
import itertools
from pathlib import Path

import mlflow
from mlflow import MlflowClient
from sklearn.metrics import roc_auc_score

from churn_data import load, make_xgb

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)
mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")
mlflow.set_experiment("saasify-churn-sweep")
d = load()                                             # module 03's data, splits and preprocessing

for lr, depth in itertools.product([0.02, 0.05, 0.1], [3, 5]):
    with mlflow.start_run(run_name=f"xgb-lr{lr}-d{depth}"):
        model = make_xgb(d, learning_rate=lr, n_estimators=600).set_params(max_depth=depth)
        model.fit(d["Xt_tr"], d["y_tr"], eval_set=[(d["Xt_va"], d["y_va"])], verbose=False)
        mlflow.log_params({"learning_rate": lr, "max_depth": depth, "data_rows": len(d["df"]), "seed": 42})
        mlflow.log_metrics({"val_auc": roc_auc_score(d["y_va"], model.predict_proba(d["Xt_va"])[:, 1]),
                            "test_auc": roc_auc_score(d["y_te"], model.predict_proba(d["Xt_te"])[:, 1]),
                            "best_iteration": model.best_iteration})
        info = mlflow.xgboost.log_model(model.get_booster(), name="model")
        mlflow.set_tag("model_uri", info.model_uri)       # remember where this run's model lives

runs = mlflow.search_runs(experiment_names=["saasify-churn-sweep"], order_by=["metrics.val_auc DESC"])
cols = ["tags.mlflow.runName", "params.learning_rate", "params.max_depth", "metrics.val_auc", "metrics.test_auc"]
print(runs[cols].round(4).to_string(index=False))

best = runs.iloc[0]                                    # best by VALIDATION auc; the test column is only for reporting
version = mlflow.register_model(best["tags.model_uri"], "saasify-churn")
MlflowClient().set_registered_model_alias("saasify-churn", "champion", version.version)
print("registered", version.name, "version", version.version, "-> alias 'champion' (run", best["tags.mlflow.runName"] + ")")
output of track_churn_sweep.pyactual output
tags.mlflow.runName params.learning_rate params.max_depth  metrics.val_auc  metrics.test_auc
       xgb-lr0.1-d3                  0.1                3           0.9194            0.9273
      xgb-lr0.02-d3                 0.02                3           0.9189            0.9273
      xgb-lr0.05-d3                 0.05                3           0.9176            0.9261
      xgb-lr0.05-d5                 0.05                5           0.9171            0.9272
      xgb-lr0.02-d5                 0.02                5           0.9170            0.9265
       xgb-lr0.1-d5                  0.1                5           0.9144            0.9239
registered saasify-churn version 1 -> alias 'champion' (run xgb-lr0.1-d3)

Read the output. The table is the sweep, best row first: learning rate 0.1 with depth 3 wins on validation, 0.9194. Look at the gap between first and second, 0.9194 against 0.9189: 0.0005, far smaller than random variation from the data split. The honest reading is "depth 3 is slightly better than depth 5 in this setting, and the learning rate hardly matters". The tracking table lets you see that, instead of believing in a single winner. The last line is the registry: version 1, alias champion.

Dev's lost model is now a row. To reproduce it, read the params and rerun with the same data and seed. The test AUC 0.9273 of the winner is also the figure for Marcus's slide, with the run that produced it one click away.

Weights & Biases: the hosted alternative

MLflow is open source and you host it. Weights & Biases (W&B, "wandb") is a hosted service: you log from Python with a different API, and the dashboards, charts and sharing live on its servers. It is stronger on rich live charts and team collaboration. It is weaker if your data cannot leave your network, and it needs an account. The code below logs two of the same runs. Run it offline without any account, or remove one line and log in to sync it.

Step-by-step: what wandb_tracking.py does, in plain English
  1. Import wandb. The comment on line 1 says it needs an account and an API key for the hosted dashboard.
  2. os.environ.setdefault("WANDB_MODE", "offline") makes it write a local folder instead of calling the server. Delete that line, run wandb login, and the same code syncs to wandb.ai.
  3. wandb.init(project=..., name=..., config=...) opens a run with its settings, like start_run plus log_params.
  4. run.log({"val_auc": auc}) records a metric. run.finish() closes the run.
wandb_tracking.pyhosted run needs API key · offline run verified
# pip install "wandb>=0.22,<1"        # needs API key (WANDB_API_KEY) for the hosted dashboard
# Offline path: WANDB_MODE=offline python wandb_tracking.py   -> writes ./wandb/offline-run-*, no account needed
"""The same sweep idea in Weights & Biases: init a run, log config and metrics, finish."""
import os

import wandb

os.environ.setdefault("WANDB_MODE", "offline")           # remove this line (and log in) to sync to wandb.ai

for lr, depth, auc in [(0.1, 3, 0.9194), (0.05, 5, 0.9171)]:      # the numbers come from track_churn_sweep.py's table
    run = wandb.init(project="saasify-churn-sweep", name=f"xgb-lr{lr}-d{depth}",
                     config={"learning_rate": lr, "max_depth": depth}, dir="out")
    run.log({"val_auc": auc})
    run.finish()
    print("logged", run.name, "mode:", os.environ["WANDB_MODE"])
output of wandb_tracking.pyactual output (offline mode)
logged xgb-lr0.1-d3 mode: offline
logged xgb-lr0.05-d5 mode: offline

Read the output. Two runs logged in offline mode: W&B wrote its files into out/wandb/ and never called the server. Hosted mode, which needs an API key, is not run here. The API shape (init a run with a config, log metrics, finish) is the same idea as MLflow's: pick whichever your team already uses, and do not run both for the same project.

Putting it together: the segmentation pipeline, logged

Where we are in the story: Priya's segmentation question and Dev's tracking problem meet in one program. It loads the accounts, scales, clusters, names, scores churn risk and writes the whole run into MLflow, so that "which k and which columns gave these segments?" has an answer next quarter. Fig. 3b.16 is the pipeline; the table after it says what each stage is in the naive and the production version.

accounts 4,400 rows chunk 1 scale mean 0, sd 1 chunk 1 cluster k = 4 chunk 2 name 4 segments chunk 3 score AUC 0.942 chunk 4 log 1 MLflow run chunk 5 dashboard 395 at risk dashboard.py 1 2 3
Fig. 3b.16 — The pipeline of segment_and_track.py, with the real numbers each stage produces.
  1. Scale, then cluster. Scaling is the only step with no output of its own; it is what makes the cluster stage honest (Fig. 3b.5). The cluster stage gives four groups and a silhouette of 0.483.
  2. Name and score. The naming rule and the churn model both read the groups, and write a scored table: 4,400 rows, each with a segment name and a churn risk.
  3. Log and show. The last two stages save the run (MLflow) and display it (dashboard). Neither changes any number; they make the numbers findable and readable.
The same pipeline twice: the notebook version and the production version
StageIn the naive versionIn the production versionWhat flows out
LoadRead a CSV someone emailedgenerate_accounts(), or a SQL query as in Module 01d4,400 rows, 12 columns
ScaleEyeball the columns, skip scalingStandardScaler, fitted once6 columns of mean 0, spread 1
Clusterk picked from a tutorial, one startKMeans(k=4, n_init=10, random_state=0), k justified by silhouettea segment number per account
NameNames typed in by handname_segments, a rule that can be re-run"Power teams", "Stuck in onboarding", ...
ScoreTrain on all data, score the same data3-fold out-of-fold XGBoost riskschurn risk per account, AUC 0.942
LogA screenshot in SlackOne MLflow run: params, metrics, two artifactsa run id that can be found next quarter

Build it in chunks

We build segment_and_track.py in five chunks: features, scale, cluster, name, score, log. Every chunk runs on its own as segment_chunk1.py to segment_chunk5.py in the code folder (each adds its lines to the ones before it, and its try-it lines print what you should see).

  1. Chunk 1 — load the accounts and scale the behaviour columns

    Clustering starts where Fig. 3b.5 told us to: only behaviour columns, all scaled. We leave churn out on purpose, so the groups are made from how accounts act, not from how they ended.

    Step-by-step: what chunk 1 does, in plain English
    1. Import StandardScaler, pandas and our generate_accounts generator from the code folder.
    2. FEATURES lists the six behaviour columns used for distance. Churn is not in it.
    3. OUT is an out/ folder next to the script, created if missing. Everything the script saves lands there.
    4. StandardScaler().fit_transform(...) subtracts each column's mean and divides by its spread. The try-it line prints that every mean is 0 and every spread is 1.
    segment_and_track.py — chunk 1runs offline
    # ── chunk 1: load the accounts and scale the behaviour columns ──
    # pip install "scikit-learn>=1.9,<2" "pandas>=3,<4" "numpy>=2.5,<2.6" "xgboost>=3,<4" "mlflow>=3,<4"
    from pathlib import Path
    
    import numpy as np
    import pandas as pd
    from sklearn.preprocessing import StandardScaler
    
    from saasify_accounts import generate_accounts
    
    # Only columns that describe HOW an account behaves. Churn is deliberately left out:
    # we want groups of similar customers, not groups made of the answer.
    FEATURES = ["TenureMonths", "MonthlyCharges", "SupportTickets", "LoginFrequency", "FeatureAdoption", "Seats"]
    OUT = Path(__file__).parent / "out"
    OUT.mkdir(exist_ok=True)
    
    df = generate_accounts()
    X = StandardScaler().fit_transform(df[FEATURES])     # every column now has mean 0 and spread 1
    
    # try it
    print("accounts:", len(df), " scaled column means:", np.round(X.mean(axis=0), 2).tolist(), " spreads:", np.round(X.std(axis=0), 2).tolist())

    pathlib.Path(__file__).parent — a folder next to the script, so the program works from any directory.

    Run python3 segment_chunk1.py. It prints 4,400 accounts and six means of 0.0 with six spreads of 1.0.

    terminalactual output
    accounts: 4400  scaled column means: [0.0, -0.0, 0.0, 0.0, 0.0, -0.0]  spreads: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
  2. Chunk 2 — cluster with k-means and measure how clean the groups are

    Same call as the anatomy above. We keep the fitted model (km) because its inertia is worth logging later, and compute the silhouette so we can tell this clustering from noise.

    Step-by-step: what chunk 2 does, in plain English
    1. KMeans(n_clusters=K, n_init=10, random_state=0) fits four groups with ten restarts, and a fixed seed so reruns agree.
    2. df["Segment"] = km.labels_ writes the group number (0 to 3) into a new column of the table.
    3. silhouette_score(..., sample_size=2000) scores the grouping on a random 2,000 accounts, to keep it quick.
    segment_and_track.py — chunk 2runs offline
    # ── chunk 2: cluster ──
    from sklearn.cluster import KMeans
    from sklearn.metrics import silhouette_score
    
    K = 4
    km = KMeans(n_clusters=K, n_init=10, random_state=0).fit(X)
    df["Segment"] = km.labels_
    silhouette = silhouette_score(X, km.labels_, sample_size=2000, random_state=0)
    
    # try it
    print("group sizes:", df["Segment"].value_counts().sort_index().tolist(), " silhouette:", round(float(silhouette), 3))

    km.labels_ — a trailing underscore is scikit-learn's convention for "learned during fit".

    Run python3 segment_chunk2.py. Four group sizes (1,728, 999, 559, 1,114) and a silhouette of 0.483.

    terminalactual output
    group sizes: [1728, 999, 559, 1114]  silhouette: 0.483
  3. Chunk 3 — name the groups from their average accounts

    Group numbers mean nothing to Priya. The profile (the average account of each group, in real units) is what a human reads, and name_segments turns it into names by a rule, so the names are reproducible and not a mood.

    Step-by-step: what chunk 3 does, in plain English
    1. df.groupby("Segment")[FEATURES].mean() averages each column inside each group: the profile table.
    2. name_segments hands out names in order. The group with the most logins is "Power teams", and the one with the shortest tenure is "Stuck in onboarding".
    3. Of the groups left, the one with the longest tenure is "Loyal veterans", and the last one is "Quiet small teams". Each name is used once.
    4. df["Segment"].map(names) replaces numbers by names in a new column. The try-it line prints the profile with names as row labels.
    segment_and_track.py — chunk 3runs offline
    # ── chunk 3: turn numbered groups into named segments ──
    profile = df.groupby("Segment")[FEATURES].mean()          # the average account of each group, in real units
    
    
    def name_segments(profile):
        """Give each group the first name whose test it passes best. Order matters: each name is used once."""
        rules = [("Power teams", profile["LoginFrequency"].idxmax()),
                 ("Stuck in onboarding", profile["TenureMonths"].idxmin())]
        taken = {seg for _, seg in rules}
        rest = profile.drop(index=list(taken))
        rules.append(("Loyal veterans", rest["TenureMonths"].idxmax()))
        taken.add(rules[-1][1])
        rules.append(("Quiet small teams", next(s for s in profile.index if s not in taken)))
        return {seg: name for name, seg in rules}
    
    
    names = name_segments(profile)
    df["SegmentName"] = df["Segment"].map(names)
    
    # try it
    print(profile.rename(index=names).round(1).to_string())

    idxmax() / idxmin() — return the row label of the largest or smallest value.

    Run python3 segment_chunk3.py. A four-row profile: Power teams have 28.2 logins and 25.0 seats; Stuck in onboarding have 4.0 months of tenure and 6.3 tickets.

    terminalactual output
                         TenureMonths  MonthlyCharges  SupportTickets  LoginFrequency  FeatureAdoption  Seats
    Segment                                                                                                  
    Quiet small teams            20.1            40.0             1.5             4.9             11.7    4.1
    Power teams                  27.4           118.6             1.2            28.2             58.1   25.0
    Stuck in onboarding           4.0            72.0             6.3             4.1              9.4    5.9
    Loyal veterans               53.4            84.1             1.8            14.0             32.2   11.1
  4. Chunk 4 — add a churn risk to every account, using Module 03's model

    Priya needs both questions answered: which type, and how likely to leave. We train XGBoost, the Module 03 model, and score every account out of fold: three models each score the third of the accounts they never saw, so a risk is never a memorised answer.

    Step-by-step: what chunk 4 does, in plain English
    1. pd.get_dummies turns the text columns (contract type, tech support) into 0/1 columns so XGBoost can use them.
    2. XGBClassifier(...) is a small boosted-tree model: 150 trees of depth 4.
    3. cross_val_predict(..., cv=3, method="predict_proba") trains three models, each predicting the third it did not train on, and returns the probability of churn for every account.
    4. roc_auc_score grades the risks against real churn, and to_csv saves the scored table for the dashboard.
    5. The try-it lines print the AUC and then the real churn rate and average predicted risk of each named segment.
    segment_and_track.py — chunk 4runs offline
    # ── chunk 4: add a churn risk to every account ──
    from sklearn.metrics import roc_auc_score
    from sklearn.model_selection import cross_val_predict
    from xgboost import XGBClassifier
    
    model_X = pd.get_dummies(df[FEATURES + ["ContractType", "TechSupport"]], dtype=float)
    model = XGBClassifier(n_estimators=150, max_depth=4, learning_rate=0.08, n_jobs=2, random_state=0)
    # Out-of-fold: each account is scored by a model that never saw it, so risk is not just memory.
    df["ChurnRisk"] = cross_val_predict(model, model_X, df["Churn"], cv=3, method="predict_proba")[:, 1]
    auc = roc_auc_score(df["Churn"], df["ChurnRisk"])
    df.to_csv(OUT / "accounts_scored.csv", index=False)
    
    # try it
    print("churn AUC (3-fold out-of-fold):", round(float(auc), 3))
    print(df.groupby("SegmentName").agg(accounts=("AccountID", "size"), real_churn=("Churn", "mean"),
                                        mean_risk=("ChurnRisk", "mean")).round(3).to_string())

    cross_val_predict — a prediction for every row, made by a model that did not train on that row.

    Run python3 segment_chunk4.py. AUC 0.942. Stuck in onboarding: real churn 51.0%, mean risk 50.3%. Loyal veterans: 0.6% and 0.5%.

    terminalactual output
    churn AUC (3-fold out-of-fold): 0.942
                         accounts  real_churn  mean_risk
    SegmentName                                         
    Loyal veterans           1114       0.006      0.005
    Power teams               999       0.046      0.037
    Quiet small teams        1728       0.020      0.019
    Stuck in onboarding       559       0.510      0.503
  5. Chunk 5 — write the run into MLflow

    The last chunk makes the result findable. It records the settings, the quality numbers and the two result files in one run, in a local database file.

    Step-by-step: what chunk 5 does, in plain English
    1. mlflow.set_tracking_uri("sqlite:///...") points MLflow at a SQLite file in out/. No server is needed.
    2. mlflow.set_experiment names the folder of runs, and start_run opens one run as a with block, closed automatically.
    3. log_params records the settings (algorithm, k, scaler, feature list). log_metrics records the numbers (silhouette, inertia, churn AUC).
    4. log_artifact attaches files to the run: the segment profile and the scored accounts.
    5. The try-it lines read the run back with mlflow.search_runs, which returns a pandas table.
    segment_and_track.py — chunk 5runs offline
    # ── chunk 5: write the run into MLflow ──
    import mlflow
    
    mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")     # one local file, no server needed
    mlflow.set_experiment("saasify-segments")
    with mlflow.start_run(run_name=f"kmeans-k{K}"):
        mlflow.log_params({"algorithm": "kmeans", "k": K, "scaler": "StandardScaler", "features": ",".join(FEATURES)})
        mlflow.log_metrics({"silhouette": silhouette, "inertia": km.inertia_, "churn_auc": auc})
        profile.rename(index=names).round(2).to_csv(OUT / "segment_profile.csv")
        mlflow.log_artifact(str(OUT / "segment_profile.csv"))
        mlflow.log_artifact(str(OUT / "accounts_scored.csv"))
    
    # try it
    run = mlflow.search_runs(experiment_names=["saasify-segments"])
    print(run[["tags.mlflow.runName", "params.k", "metrics.silhouette", "metrics.churn_auc"]].round(3).to_string(index=False))

    mlflow.start_run() as a context manager, and mlflow.search_runs to query runs like a table.

    Run python3 segment_chunk5.py. One row: run name kmeans-k4, k 4, silhouette 0.483, churn_auc 0.942.

    terminalactual output
    tags.mlflow.runName params.k  metrics.silhouette  metrics.churn_auc
              kmeans-k4        4               0.483              0.942

The whole program

Chunk 1 is down to the X = StandardScaler()... line; chunk 2 is the KMeans block; chunk 3 is profile, name_segments and the names; chunk 4 is the XGBoost scoring block; chunk 5 is the MLflow block. The five printed lines at the bottom are the try-it lines of chunks 2 to 5.

segment_and_track.pyruns offline
"""segment_and_track.py: features -> scale -> cluster -> name -> churn risk -> log to MLflow. Five chunks on the page."""
# ── chunk 1: load the accounts and scale the behaviour columns ──
# pip install "scikit-learn>=1.9,<2" "pandas>=3,<4" "numpy>=2.5,<2.6" "xgboost>=3,<4" "mlflow>=3,<4"
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler

from saasify_accounts import generate_accounts

# Only columns that describe HOW an account behaves. Churn is deliberately left out:
# we want groups of similar customers, not groups made of the answer.
FEATURES = ["TenureMonths", "MonthlyCharges", "SupportTickets", "LoginFrequency", "FeatureAdoption", "Seats"]
OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)

df = generate_accounts()
X = StandardScaler().fit_transform(df[FEATURES])     # every column now has mean 0 and spread 1

# ── chunk 2: cluster ──
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

K = 4
km = KMeans(n_clusters=K, n_init=10, random_state=0).fit(X)
df["Segment"] = km.labels_
silhouette = silhouette_score(X, km.labels_, sample_size=2000, random_state=0)

# ── chunk 3: turn numbered groups into named segments ──
profile = df.groupby("Segment")[FEATURES].mean()          # the average account of each group, in real units


def name_segments(profile):
    """Give each group the first name whose test it passes best. Order matters: each name is used once."""
    rules = [("Power teams", profile["LoginFrequency"].idxmax()),
             ("Stuck in onboarding", profile["TenureMonths"].idxmin())]
    taken = {seg for _, seg in rules}
    rest = profile.drop(index=list(taken))
    rules.append(("Loyal veterans", rest["TenureMonths"].idxmax()))
    taken.add(rules[-1][1])
    rules.append(("Quiet small teams", next(s for s in profile.index if s not in taken)))
    return {seg: name for name, seg in rules}


names = name_segments(profile)
df["SegmentName"] = df["Segment"].map(names)

# ── chunk 4: add a churn risk to every account ──
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import cross_val_predict
from xgboost import XGBClassifier

model_X = pd.get_dummies(df[FEATURES + ["ContractType", "TechSupport"]], dtype=float)
model = XGBClassifier(n_estimators=150, max_depth=4, learning_rate=0.08, n_jobs=2, random_state=0)
# Out-of-fold: each account is scored by a model that never saw it, so risk is not just memory.
df["ChurnRisk"] = cross_val_predict(model, model_X, df["Churn"], cv=3, method="predict_proba")[:, 1]
auc = roc_auc_score(df["Churn"], df["ChurnRisk"])
df.to_csv(OUT / "accounts_scored.csv", index=False)

# ── chunk 5: write the run into MLflow ──
import mlflow

mlflow.set_tracking_uri(f"sqlite:///{OUT / 'mlflow.db'}")     # one local file, no server needed
mlflow.set_experiment("saasify-segments")
with mlflow.start_run(run_name=f"kmeans-k{K}"):
    mlflow.log_params({"algorithm": "kmeans", "k": K, "scaler": "StandardScaler", "features": ",".join(FEATURES)})
    mlflow.log_metrics({"silhouette": silhouette, "inertia": km.inertia_, "churn_auc": auc})
    profile.rename(index=names).round(2).to_csv(OUT / "segment_profile.csv")
    mlflow.log_artifact(str(OUT / "segment_profile.csv"))
    mlflow.log_artifact(str(OUT / "accounts_scored.csv"))

# ── what it prints ──
print("group sizes:", df["Segment"].value_counts().sort_index().tolist(), " silhouette:", round(float(silhouette), 3))
print(profile.rename(index=names).round(1).to_string())
print("churn AUC (3-fold out-of-fold):", round(float(auc), 3))
print(df.groupby("SegmentName").agg(accounts=("AccountID", "size"), real_churn=("Churn", "mean"),
                                    mean_risk=("ChurnRisk", "mean")).round(3).to_string())
run = mlflow.search_runs(experiment_names=["saasify-segments"])
print(run[["tags.mlflow.runName", "params.k", "metrics.silhouette", "metrics.churn_auc"]].round(3).to_string(index=False))
output of segment_and_track.pyactual output
group sizes: [1728, 999, 559, 1114]  silhouette: 0.483
                     TenureMonths  MonthlyCharges  SupportTickets  LoginFrequency  FeatureAdoption  Seats
Segment                                                                                                  
Quiet small teams            20.1            40.0             1.5             4.9             11.7    4.1
Power teams                  27.4           118.6             1.2            28.2             58.1   25.0
Stuck in onboarding           4.0            72.0             6.3             4.1              9.4    5.9
Loyal veterans               53.4            84.1             1.8            14.0             32.2   11.1
churn AUC (3-fold out-of-fold): 0.942
                     accounts  real_churn  mean_risk
SegmentName                                         
Loyal veterans           1114       0.006      0.005
Power teams               999       0.046      0.037
Quiet small teams        1728       0.020      0.019
Stuck in onboarding       559       0.510      0.503
tags.mlflow.runName params.k  metrics.silhouette  metrics.churn_auc
          kmeans-k4        4               0.483              0.942

Read the output. The first line is the cluster size and silhouette from chunk 2. The profile table is chunk 3: look at the row for Stuck in onboarding, with a tenure of 4.0 months, 6.3 tickets a month and only 4.1 logins, and compare it to Power teams with 28.2 logins and 25 seats.

The AUC of 0.942 grades the risk model, and the three-line table at the bottom of the churn block is what to show Marcus: real churn of 51% against a predicted average of 50.3% for the stuck accounts, 0.6% against 0.5% for the veterans. The last line is the MLflow run, found again by a query.

Quick reference: experiment tracking

Run
One training attempt: params in, metrics out, artifacts saved, in one record.
Param / metric / artifact / tag
A setting / a number produced / a saved file / a free label.
Experiment
A named folder of related runs; query it with mlflow.search_runs.
Registry, version, alias
A stable model name, numbered versions, and moveable labels such as champion. Needs a database backend.
Backend vs artifact store
Metadata goes in a database (SQLite for one person, PostgreSQL for a team); files go in a folder or object store such as S3.
Select on validation
Pick the best run by validation AUC and keep the test score for reporting.
W&B offline
WANDB_MODE=offline writes a local folder and needs no account. Hosted sync needs an API key.

07 · The dashboardStreamlit: A Web Page Instead of a Notebook

A dashboard is a web page that shows the results and lets a non-programmer filter them. Streamlit builds one from a plain Python script. Without it, results stay trapped in a notebook that only the data team can run.

Where we are in the story: Fig. 3b.1, marker 3. Priya's team has segments and churn risks and asked for "not a notebook". They need to see segments, see who is at risk, and filter without writing code. The scored table from the last section, out/accounts_scored.csv, is all the page needs.

SIDEBAR (chunk 3) Segments 4 chips, remove any Risk above 0.30 TITLE: who are our customers, and who is about to leave? Paying accounts 4,400 Average churn risk 8.1% Above 30% risk 395 METRICS (chunk 1) segment table (chunk 2) 4 rows: accounts, risk Stuck in onboarding 0.503 bar chart: risk by segment CALL LIST (chunk 3): accounts above the slider, riskiest first ACC-1847 Stuck in onboarding 0.99 MAP (chunk 4): every account on the two PCA axes 1 2 3 4
Fig. 3b.17 — The wireframe of dashboard.py with the numbers the page shows. Sidebar on the left, headline numbers on top, the segment table and chart in the middle, the call list below, a map at the bottom.
  1. Headline numbers (chunk 1). 4,400 paying accounts, an average churn risk of 8.1%, and 395 accounts above the 30% line. These are what Priya reads first.
  2. Segments (chunk 2). One row and one bar per segment. The bar for Stuck in onboarding, 0.503, towers over the others (0.037, 0.019, 0.005).
  3. The call list and its filter (chunk 3). The only interactive part: a sidebar slider (risk above 0.30) and a segment chooser. Move the slider to 0.50 and the list shrinks from 395 to 320 accounts.
  4. The map (chunk 4). The PCA picture of Fig. 3b.10, now filtered by the same sidebar.

How Streamlit works: rerun the whole script

Streamlit has one idea that explains everything. Every time a person clicks a widget, it runs your script again from the top, with the widget now returning its new value. There are no callbacks to wire and no HTML to write. You already know the cost: every interaction repeats all the work, so slow steps (reading a file, training a model) must be remembered with @st.cache_data.

That model makes Streamlit very quick to build with, and it is also why it stops fitting at some size. All viewers run Python on your server, state is awkward across pages, and fine control of layout and permissions is limited. The stack table below says when to move to a real front end, which is what Module 05b teaches.

The program below is built in four chunks. You do not need to know Streamlit yet; each chunk says what its new calls do, and its check line shows what the page contains. The chunks run in Streamlit's test harness here, because the page was also checked in a real browser.

Build it in chunks

We build dashboard.py in four chunks. Each runs as a page by itself (dashboard_chunk1.py to dashboard_chunk4.py in the code folder) and shows its own element. The code under each rung is only what that chunk adds; the checks below are printed by Streamlit's AppTest, a way to run a Streamlit page without a browser.

  1. Chunk 1 — load the scored table and show three headline numbers

    A dashboard starts as a script that prints a title and a few facts. Streamlit runs your file top to bottom and draws each st. call as a page element.

    Step-by-step: what chunk 1 does, in plain English
    1. st.set_page_config sets the browser tab title and uses the full page width. It must be the first Streamlit call.
    2. st.title writes the big heading.
    3. load() reads out/accounts_scored.csv, the file chunk 4 of the pipeline saved. @st.cache_data remembers the result, so the file is read once, not on every click.
    4. st.columns(3) makes three side-by-side slots, and .metric(label, value) draws a big number in each: accounts, average risk, and how many are above 30% risk.
    dashboard.py — chunk 1runs offline
    # ── chunk 1: load the scored accounts and show three headline numbers ──
    # pip install "streamlit>=1.40,<2" "pandas>=3,<4"      # run: streamlit run dashboard.py
    from pathlib import Path
    
    import pandas as pd
    import streamlit as st
    
    st.set_page_config(page_title="SaaSify customer segments", layout="wide")
    st.title("SaaSify: who are our customers, and who is about to leave?")
    
    
    @st.cache_data                                         # re-read the file only when it changes
    def load():
        return pd.read_csv(Path(__file__).parent / "out" / "accounts_scored.csv")
    
    
    df = load()
    a, b, c = st.columns(3)
    a.metric("Paying accounts", f"{len(df):,}")
    b.metric("Average churn risk", f"{df['ChurnRisk'].mean():.1%}")
    c.metric("Accounts above 30% risk", f"{(df['ChurnRisk'] > 0.30).sum():,}")

    @st.cache_data — keep a function's result between reruns. st.metric — a labelled big number.

    Run streamlit run dashboard_chunk1.py and open the address it prints. Below, the same page checked without a browser by python3 apptest_dashboard.py dashboard_chunk1.py, which uses Streamlit's AppTest.

    terminalactual output
    dashboard_chunk1.py exception: []
     metrics: [('Paying accounts', '4,400'), ('Average churn risk', '8.1%'), ('Accounts above 30% risk', '395')]
     subheaders: []
  2. Chunk 2 — one row per segment, as a table and a bar chart

    Priya's first question is about the segments, so the next element is the segment summary. It is the same group-by you wrote in pandas in Module 01c.

    Step-by-step: what chunk 2 does, in plain English
    1. df.groupby("SegmentName").agg(...) computes, for each segment, the number of accounts, the average churn risk and the average monthly charge.
    2. sort_values("avg_risk", ascending=False) puts the riskiest segment on top.
    3. st.subheader adds a heading. st.columns(2) splits the row in two.
    4. left.dataframe(...) draws a sortable table. right.bar_chart(...) draws the risk as bars.
    dashboard.py — chunk 2runs offline
    # ── chunk 2: one row per segment ──
    summary = (df.groupby("SegmentName")
                 .agg(accounts=("AccountID", "size"), avg_risk=("ChurnRisk", "mean"),
                      avg_monthly_charge=("MonthlyCharges", "mean"))
                 .sort_values("avg_risk", ascending=False))
    st.subheader("Segments")
    left, right = st.columns(2)
    left.dataframe(summary.round(3))
    right.bar_chart(summary["avg_risk"])

    Calling .dataframe and .bar_chart on a column object puts the element in that column.

    The table has four rows and the bar chart shows one tall bar: Stuck in onboarding at 0.503.

    terminalactual output
    dashboard_chunk2.py exception: []
     metrics: [('Paying accounts', '4,400'), ('Average churn risk', '8.1%'), ('Accounts above 30% risk', '395')]
     subheaders: ['Segments']
  3. Chunk 3 — the interactive filter and the call list

    This is the part a notebook cannot do for Priya: she moves a slider and the list changes. Every widget returns its current value, and Streamlit reruns the script when it changes.

    Step-by-step: what chunk 3 does, in plain English
    1. st.sidebar.multiselect puts a multi-choice box in the sidebar. Its value is the list of chosen segment names, all four by default.
    2. st.sidebar.slider returns a number between 0 and 1, starting at 0.30 and moving in steps of 0.05.
    3. df[...isin(chosen) & (df["ChurnRisk"] > threshold)] keeps accounts in a chosen segment and above the slider.
    4. The riskiest accounts come first. st.dataframe(...head(50)) shows the top 50 as the call list, and st.caption adds the monthly revenue in the list.
    dashboard.py — chunk 3runs offline
    # ── chunk 3: the interactive filter and the call list ──
    st.sidebar.header("Filter")
    chosen = st.sidebar.multiselect("Segments", sorted(df["SegmentName"].unique()),
                                    default=sorted(df["SegmentName"].unique()))
    threshold = st.sidebar.slider("Show accounts with risk above", 0.0, 1.0, 0.30, 0.05)
    
    view = df[df["SegmentName"].isin(chosen) & (df["ChurnRisk"] > threshold)]
    view = view.sort_values("ChurnRisk", ascending=False)
    st.subheader(f"Call list: {len(view):,} accounts")
    st.dataframe(view[["AccountID", "SegmentName", "ChurnRisk", "MonthlyCharges", "TenureMonths", "ContractType"]].head(50))
    st.caption(f"Monthly revenue at stake in this list: ${view['MonthlyCharges'].sum():,.0f}")

    Widgets return plain Python values. Move one and the script reruns from the top with the new value.

    With the slider at 0.50 the call list has 320 accounts. Restricting the segments to "Stuck in onboarding" gives 303 accounts with $23,134 of monthly revenue.

    terminalactual output
    dashboard_chunk3.py exception: []
     metrics: [('Paying accounts', '4,400'), ('Average churn risk', '8.1%'), ('Accounts above 30% risk', '395')]
     subheaders: ['Segments', 'Call list: 395 accounts']
     after slider 0.5: ['Call list: 320 accounts']
     after segment filter: ['Call list: 303 accounts'] Monthly revenue at stake in this list: $23,134
  4. Chunk 4 — a map of every account

    Fig. 3b.10 was a picture for the data team. The last element puts the same PCA map into the dashboard, and it respects the segment filter.

    Step-by-step: what chunk 4 does, in plain English
    1. Import PCA and StandardScaler from scikit-learn.
    2. Scale the six behaviour columns and reduce them to two PCA coordinates, as in pca_by_hand.py.
    3. Build a small table of PC1, PC2 and the segment name.
    4. st.scatter_chart(..., color="Segment") draws one coloured dot per account, filtered by the sidebar's chosen segments.
    dashboard.py — chunk 4runs offline
    # ── chunk 4: a map of all accounts (PCA squeezes 6 columns into 2) ──
    from sklearn.decomposition import PCA
    from sklearn.preprocessing import StandardScaler
    
    cols = ["TenureMonths", "MonthlyCharges", "SupportTickets", "LoginFrequency", "FeatureAdoption", "Seats"]
    xy = PCA(n_components=2).fit_transform(StandardScaler().fit_transform(df[cols]))
    mapdf = pd.DataFrame({"PC1": xy[:, 0], "PC2": xy[:, 1], "Segment": df["SegmentName"]})
    st.subheader("Map of every account")
    st.scatter_chart(mapdf[mapdf["Segment"].isin(chosen)], x="PC1", y="PC2", color="Segment")

    st.scatter_chart — a scatter plot with colours straight from a table column.

    Run the whole dashboard.py. The page shows three metrics, a table and bars, a call list with a slider, and a map of four coloured clouds.

    terminalactual output
    dashboard_chunk4.py exception: []
     metrics: [('Paying accounts', '4,400'), ('Average churn risk', '8.1%'), ('Accounts above 30% risk', '395')]
     subheaders: ['Segments', 'Call list: 395 accounts', 'Map of every account']
     after slider 0.5: ['Call list: 320 accounts']
     after segment filter: ['Call list: 303 accounts'] Monthly revenue at stake in this list: $23,134

The whole program

Chunk 1 is the imports, the page title, load() and the three metrics; chunk 2 is the summary block; chunk 3 is the sidebar filter and call list; chunk 4 is the PCA map. Run it with streamlit run dashboard.py after segment_and_track.py has produced out/accounts_scored.csv.

dashboard.pyruns offline
# ── chunk 1: load the scored accounts and show three headline numbers ──
# pip install "streamlit>=1.40,<2" "pandas>=3,<4"      # run: streamlit run dashboard.py
from pathlib import Path

import pandas as pd
import streamlit as st

st.set_page_config(page_title="SaaSify customer segments", layout="wide")
st.title("SaaSify: who are our customers, and who is about to leave?")


@st.cache_data                                         # re-read the file only when it changes
def load():
    return pd.read_csv(Path(__file__).parent / "out" / "accounts_scored.csv")


df = load()
a, b, c = st.columns(3)
a.metric("Paying accounts", f"{len(df):,}")
b.metric("Average churn risk", f"{df['ChurnRisk'].mean():.1%}")
c.metric("Accounts above 30% risk", f"{(df['ChurnRisk'] > 0.30).sum():,}")

# ── chunk 2: one row per segment ──
summary = (df.groupby("SegmentName")
             .agg(accounts=("AccountID", "size"), avg_risk=("ChurnRisk", "mean"),
                  avg_monthly_charge=("MonthlyCharges", "mean"))
             .sort_values("avg_risk", ascending=False))
st.subheader("Segments")
left, right = st.columns(2)
left.dataframe(summary.round(3))
right.bar_chart(summary["avg_risk"])

# ── chunk 3: the interactive filter and the call list ──
st.sidebar.header("Filter")
chosen = st.sidebar.multiselect("Segments", sorted(df["SegmentName"].unique()),
                                default=sorted(df["SegmentName"].unique()))
threshold = st.sidebar.slider("Show accounts with risk above", 0.0, 1.0, 0.30, 0.05)

view = df[df["SegmentName"].isin(chosen) & (df["ChurnRisk"] > threshold)]
view = view.sort_values("ChurnRisk", ascending=False)
st.subheader(f"Call list: {len(view):,} accounts")
st.dataframe(view[["AccountID", "SegmentName", "ChurnRisk", "MonthlyCharges", "TenureMonths", "ContractType"]].head(50))
st.caption(f"Monthly revenue at stake in this list: ${view['MonthlyCharges'].sum():,.0f}")

# ── chunk 4: a map of all accounts (PCA squeezes 6 columns into 2) ──
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

cols = ["TenureMonths", "MonthlyCharges", "SupportTickets", "LoginFrequency", "FeatureAdoption", "Seats"]
xy = PCA(n_components=2).fit_transform(StandardScaler().fit_transform(df[cols]))
mapdf = pd.DataFrame({"PC1": xy[:, 0], "PC2": xy[:, 1], "Segment": df["SegmentName"]})
st.subheader("Map of every account")
st.scatter_chart(mapdf[mapdf["Segment"].isin(chosen)], x="PC1", y="PC2", color="Segment")

Read the checks. Chunk 1 prints three metrics (4,400, 8.1%, 395), the same numbers as Fig. 3b.17, marker 1. Chunk 2 adds a Segments heading. In chunk 3 the harness moved the slider to 0.5 (320 accounts) and then selected only the stuck-in-onboarding segment (303 accounts, $23,134 of monthly revenue at stake): the filter works. Chunk 4 adds the map and leaves the previous elements unchanged.

The page was also run for real: streamlit run dashboard.py --server.headless true, opened in headless Chrome at 1300 pixels wide. It rendered the metrics, the segment table and bar chart, the filtered call list with the slider at 0.30, and the map; the first call-list row was ACC-1847, Stuck in onboarding, risk 0.99. The screenshot is not part of the course files.

Decision table: which dashboard tool
ToolChoose whenAvoid whenTypical cost
StreamlitAn internal data page, built by Python people, in a dayMany simultaneous users, per-user permissions, a polished product UIFree; hosting is one small server
GradioA demo of one model with inputs and outputsA multi-chart analytical pageFree
Dash (Plotly)Rich interactive charts and callbacks, a team that wants explicit controlYou want the fastest first versionFree; more code
PanelYou already live in the Jupyter and HoloViz worldYou need the biggest communityFree
React + FastAPIA customer-facing product, logins, scaleOne internal page for ten peopleWeeks of engineering

The stack, and why

The question that decides it: how many people will use this, how do they sign in, and can the data leave your network?

What this module uses, what else you could use, and when to switch (versions as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Clusteringscikit-learn 1.9.1 (KMeans, DBSCAN, HDBSCAN)the standalone hdbscan package, cuML (GPU)Already installed, one API for everything. Bad at: very large tables; all in memory on one CPU.Millions of rows (a few million and up) and a GPU is available: try cuML. The standalone hdbscan only for features sklearn's version lacks.
Dimensionality reductionPCA (scikit-learn)UMAP, t-SNEFast, deterministic, explains variance and loadings. Bad at: curved structure.You only want an exploratory picture of curved or very high-dimensional data, such as embeddings: UMAP. Never read distances off it.
Experiment trackingMLflow 3.17 with a SQLite backendWeights & Biases 0.31, Neptune, a plain CSVOpen source, runs offline, has the registry. Bad at: live charts and team sharing out of the box.Two or more people train and want hosted live charts, and data may leave your network: W&B. A single person with fewer than ~20 one-off runs: a CSV is fine.
Model registryMLflow registry (aliases)W&B Artifacts, SageMaker or Vertex registriesSame tool as tracking; the alias gives instant rollback.Your deployment already runs on one cloud with access rules and audit needs: use that cloud's registry.
Backend storeSQLite filePostgreSQL, MySQLNo server, one file, supports the registry. Bad at: concurrent writers.More than one person logs runs at the same time: PostgreSQL behind mlflow server.
DashboardStreamlit 1.66Gradio, Dash, Panel, React + FastAPI (Module 05b)A working page from a script in an hour. Bad at: many users, permissions, layout control.More than a few dozen simultaneous viewers, per-user access rules or a customer-facing product: React + FastAPI.

Start with the free, local tools: scikit-learn, MLflow on SQLite and Streamlit; move one layer at a time when a named condition above is true.

Quick reference: Streamlit

Rerun model
Every widget interaction re-runs the whole script top to bottom. Cache slow steps with @st.cache_data.
Widgets
st.sidebar.slider, multiselect: they return plain Python values.
Elements
st.metric, st.dataframe, st.bar_chart, st.scatter_chart draw numbers, tables and charts.
Run it
streamlit run dashboard.py. Add --server.headless true on a server with no browser.
Test it
streamlit.testing.v1.AppTest.from_file("dashboard.py").run() runs the page without a browser.
Outgrow it
When you need sign-in, per-user data or many concurrent viewers, build a front end over an API (Module 05b).

08 · Under the hoodThe Math, If You Want It

Where we are in the story: Priya has her segments and Dev has his runs. Marcus's analyst will ask where the numbers come from, and the answers are four short formulas. All of it is optional: nothing in the lab needs it.

Symbol cheat-sheet for this section
SymbolHow to say itWhat it means in plain words
xᵢ"x sub i"Account number i, as a list of its column values
μⱼ"mu sub j"The centre (average position) of group j
‖·‖²"norm squared"Squared straight-line length: add the squares of the gaps
Σ"sigma" (capital)Add up everything that follows, over the listed range
a, b"a" and "b"Average distance to own group; average distance to nearest other group
Σ (bold, in PCA)"covariance matrix"Table of how every pair of columns moves together
λ"lambda"How much spread one PCA axis carries (an eigenvalue)
v"v"The direction of an axis (an eigenvector)
h(x)"h of x"Number of random cuts needed to isolate account x
k-means: what it minimises, and why it must stop

The objective. k-means minimises the inertia J = Σᵢ ‖xᵢ − μc(i)‖², the sum over all accounts of the squared distance to the centre of the group c(i) that the account is in.

Symbol key: xᵢ (x sub i) is account i's row of numbers; μc(i) (mu sub c of i) is the centre of the group that account i belongs to; ‖·‖² (norm squared) is the squared straight-line distance; Σᵢ (sigma over i) adds over every account.

Why each move helps. The assign move gives each account to its nearest centre, which cannot make its distance larger.

The update move puts each centre at the mean of its group, and the mean is exactly the point that makes the sum of squared distances to a set of points smallest. So J never goes up. There are finitely many ways to group the accounts and J never repeats a grouping while it falls, so the loop must stop. It stops at a local minimum, which is why restarts matter (Fig. 3b.7). The by-hand check: J = 9.33 for the six accounts.

Silhouette: the formula for one account

The formula. s = (b − a) / max(a, b).

Symbol key: a is the average distance from the account to the other accounts of its own group; b is the average distance from the account to the accounts of the nearest other group; max(a, b) (the larger of a and b) scales the result into the range −1 to +1. For account A: a = 2.21, b = 10.68, s = 8.47 / 10.68 = 0.793.

When a is bigger than b the account is closer to another group, s is negative, and it is probably in the wrong one.

PCA: covariance, eigenvectors and the singular value decomposition

The recipe. Scale the data, build the covariance matrix Σ = XᵀX / (n − 1), and solve Σv = λv. The solutions v are the axes, and each λ is the variation along its axis. The share kept by axis j is λⱼ / Σₖ λₖ.

Symbol key: X (capital x) is the table of scaled data with n rows; Xᵀ (X transpose) is the table turned on its side; n is the number of accounts (4,400); Σ (bold sigma) is the 6 by 6 covariance matrix; v (an eigenvector) is a direction that Σ only stretches without turning; λ (lambda, an eigenvalue) is the stretch factor, equal to the variation along v; Σₖ (sigma over k) adds the six eigenvalues.

The same thing from the data. The singular value decomposition writes X = U S Vᵀ. The columns of V are the same axes v, and the variation is λⱼ = sⱼ² / (n − 1), where sⱼ (s sub j) is the j-th singular value. This is why pca_by_hand.py prints identical shares from the covariance route and the SVD route: 0.613 and 0.193. scikit-learn uses the SVD route because it is more accurate and never builds the covariance matrix.

DBSCAN, HDBSCAN and Isolation Forest: the definitions

DBSCAN. A point is a core point if at least min_samples points (itself included) lie within distance ε (epsilon, the radius eps) of it. Two core points within ε of each other are in the same group. A non-core point within ε of a core point joins that group as an edge. Anything else is noise.

HDBSCAN. It re-measures distance as the mutual reachability distance, which stretches distances in sparse areas, builds a tree of groups for every ε at once, and keeps the groups that persist longest as ε changes (subject to min_cluster_size). That is how it avoids picking one ε.

Isolation Forest score. s(x, n) = 2−E[h(x)] / c(n).

Symbol key: h(x) is how many random cuts it took one tree to isolate account x; E[h(x)] (the expected, i.e. average, value over all trees) is that count averaged; c(n) is the average cuts needed for a normal account in a sample of n, used to put the score on a common scale; 2 raised to a negative power turns a short path into a score near 1. A score near 1 means "isolated very quickly", about 0.5 means "ordinary". The planted bots scored 0.678.

There are no dumb questions

Can I use the clusters as features in the churn model?
Yes, and it is a common trick, but do it carefully. The segment is computed from the same columns the model already sees, so it usually adds little to a boosted-tree model, which can find those interactions itself. It helps most with a linear model, or when a segment brings in information from outside the training columns. If you use it, fit the clustering inside the cross-validation fold, or the segment will leak information about validation rows.
Why did the churn model score 0.942 here and about 0.92 in the sweep?
Different data and a different measure. The sweep uses Module 03's table (12,000 rows, independent columns) and a held-out validation slice. The segment pipeline uses SaaSify's 4,400 accounts, whose segments differ sharply in risk, and a 3-fold out-of-fold score. The two numbers are not comparable. This is why a tracked run records the data size and the seed beside the metric.
Is it cheating that our generator planted four types?
It is a teaching device, and the page says so. Real data has no TrueType column, so the checks you must rely on are the silhouette, stability under reruns and difference on an outside column such as churn. The hidden type lets us show how far the cheap checks can be trusted, which is the one thing real projects cannot do.
Should I put MLflow, W&B and Neptune in the same project?
No. Pick one per project; logging to two doubles the code and splits the history. Choose by who needs to see the runs and where the data may live.
Boardroom translation

For Marcus: in this table 372 accounts left, taking $29,642 of monthly revenue with them. A segmentation shows that 285 of those 372 (77%) and $21,601 of the $29,642 came from one segment, the 559 accounts stuck in onboarding, which is 13% of the customer base. A churn rate of 51% inside that group, against 0.6% for loyal veterans, turns "reduce churn" into "fix the first 30 days for one segment".

The ROI frame: if a fix cuts that segment's churn by one third, about 95 accounts and $7,200 of monthly revenue are kept, every month. The tracking and dashboard cost is a few days of engineering. The elevator version: "We found four customer types without labelling anyone, one of them loses half its members, and the CS team can see it, filter it, and call it from a page they open themselves."

09 · The labThe Segment Atlas

Where we are in the story: Priya has her dashboard and Dev has his runs. The next board meeting is in a quarter. They will ask the question every segmentation gets asked: "is this the best way to cut the customers, or just one way?" The lab answers it with data.

LAB 03b — The Segment Atlas: compare two clusterings, track both, ship the winner

Mission: extend segment_and_track.py to cluster SaaSify's accounts two ways (k-means and HDBSCAN), log both to MLflow, compare them with evidence, and ship the choice in the dashboard. You are given about 80%: the pipeline, the MLflow block and the dashboard. You write the comparison and the decision.

  • A second MLflow run named hdbscan-min100 logs min_cluster_size as a param, and the number of groups, the noise count and the silhouette (computed on non-noise points) as metrics.
  • A k-sweep for k = 2 to 8 logged as seven runs, found again with mlflow.search_runs and ranked by silhouette.
  • A stability check: re-run k-means with 5 different seeds and log the mean ARI between runs (it should be close to 1 with n_init=10).
  • A noise test: log the silhouette for random data with the same shape, and state in the README why your real silhouette is above it.
  • The dashboard gains a second filter (contract type) and shows the churn rate next to each segment name.
  • README documents: the metrics table, three failure modes you hit (for example unscaled spend, a different seed, an HDBSCAN noise share above 20%), and the fix for each.

Stretch goal: add Isolation Forest flags to the call list as a second column, and open MLflow's UI (mlflow ui) to compare the k-sweep runs side by side.

10 · Interview radarHow This Shows Up in Interviews

Interview radar

Interviewers use clustering and tracking questions to test judgement: whether you know a method's assumptions, can validate a result with no labels, and treat ML work as an engineering process. Job specs in the research files list "classical ML baselines" and MLOps tooling (MLflow plus Docker and one cloud covers most postings).

"How do you choose the number of clusters in k-means?"

The real test Do you know there is no single right answer, and that you validate with more than one signal?

Strong answer I plot inertia for a range of k and look for the elbow, then compute the silhouette score for the same range. On our customer table the elbow was at 4 and the silhouette peaked at 0.483 for k = 4. Both are advice, so I also check that the groups are stable across seeds and that the business can act on that many segments. If the silhouette is near 0.1, that is the noise level, and I do not trust any k.

Land it The metrics narrow the choice; the business use decides the k.

"What are the weaknesses of k-means, and what do you use instead?"

Strong answer Four weaknesses:

  • You must pick k up front.
  • It assumes round groups of similar size, so it cuts through crescents (ARI 0.25 on two moons).
  • It is sensitive to scale and to the starting centres, so I scale, and use n_init=10.
  • It puts every point in a group, so outliers drag centres.

For curved groups and noise I use HDBSCAN, which finds groups of different density and labels strays as noise.

Land it k-means for fast, round, similar-size groups; HDBSCAN when shapes, noise or density vary.

"Why do you scale features before clustering, and before PCA?"

Strong answer Both methods are built on distance or variance, so the column with the biggest numbers dominates. In our experiment lifetime spend had a spread of 1,949 against 10 for logins, and unscaled k-means agreed with the hidden types at 0.338 against 0.933 scaled. PCA on unscaled data would let the biggest-number column dominate its first axis. Scaling is one line inside a pipeline.

Land it Distance and variance methods vote by size, and scaling makes every column vote equally.

"You cannot reproduce the model from last month. What process would have prevented it?"

The real test Do you treat training as an engineering process with records, not a notebook?

Strong answer Experiment tracking. Each run logs its parameters, the data version or size and seed, its metrics and the model artifact. In MLflow that is a few lines per run, and the runs become a queryable table. We then register the chosen model with a version and an alias such as champion, so serving loads the alias and rollback is moving the alias back. I would also record the git commit as a tag and pin library versions.

Land it If it was not logged, it did not happen; log the settings in the same code that starts the run.

"MLflow or Weights & Biases, and why?" (vendor-agnostic judgment)

Strong answer It depends on three facts. Can the data and model metadata leave our network? Who needs to see runs? Do we need a registry on our own infrastructure? MLflow is open source and self-hosted, with a registry, so it suits a regulated company or a small team. W&B is hosted and stronger on live charts and collaboration, so it suits a research-heavy team that can use a cloud service. I would not use both on one project.

Land it Self-hosted control: MLflow. Hosted collaboration and charts: W&B. Decide by where the data may live.

"Design a customer-segmentation system that the support team can use weekly."

The real test A system-design answer that covers data, method, validation, tracking and delivery.

Strong answer A weekly job pulls account features from the warehouse and scales them. It fits k-means with several seeds, checks the silhouette, stability and noise baseline, names segments by rule and scores churn risk out of fold. Each run is logged in MLflow, with a registered pipeline. The scored table goes to a Streamlit page behind sign-in where support filters by segment and risk. Segments are re-fitted quarterly, and a drift alert fires if segment sizes move by more than a set amount.

Land it Pipeline, validation, tracking, delivery, refresh: five boxes, each with its own failure check.

"When would you not use clustering at all?"

Strong answer When I have the label I care about. If the question is "who will churn", a supervised classifier such as XGBoost answers it directly and can be graded; clustering cannot. I also avoid it when the groups are not stable or not actionable: a silhouette near 0.1 means the groups are borders drawn through one cloud, and a name on such a group misleads.

Land it Predict with labels, explore without them, and never name a group you cannot validate.

11 · RecapWhat You Can Do Now

  • You can explain when unsupervised learning is the right tool, and when a supervised model is.
  • You can write k-means from scratch in NumPy, trace it by hand on six points, and check it against scikit-learn.
  • You can choose k with the elbow and the silhouette, and say honestly what each cannot tell you.
  • You can spot and fix the three k-means failures: unscaled columns, non-round shapes, and unlucky starts.
  • You can use HDBSCAN for curved groups and noise, PCA to draw six columns in two, and Isolation Forest to find odd accounts.
  • You can turn numbered clusters into named segments and run the noise and stability checks that tell a real segmentation from a story.
  • You can log a sweep of runs in MLflow, find the best, register it with an alias, and say when to pick W&B instead.
  • You can ship results as a Streamlit dashboard with a working filter, and say when to move to a real front end.
🧠 Flex your memory

From this module: without looking, draw the three panels of Fig. 3b.3 for k = 2 on the six accounts: where do the centres start, where are they after one move, and what makes the loop stop? Then say in one sentence what the silhouette of 0.483 and the noise baseline of about 0.10 tell Priya.

From earlier modules: Module 02 scaled features so gradient descent would not zigzag; here scaling protected a distance sum. What is the common reason, and which of the two methods would have shown you the mistake in its own output? Then recall Module 03: why did we pick the winning sweep run by validation AUC and not test AUC?