You are the analyst at Summit Gear Co. For two weeks you predicted something about these 2,200 accounts: how long each takes to pay, then which ones default. This week there is no target. The controller asks two questions. Which accounts look alike? And which fit no group at all? Groups help the credit and sales teams set terms and plan reviews. An account that fits nowhere is worth a look before anyone signs off on the receivables. An AI tool can write the clustering code, or you can type it from this page. Either way, you check that each fit used the columns, scaling and settings you asked for, say what the clusters mean, and decide which unusual accounts deserve a question.
Then choose File > Save a copy in Drive and work in your copy. The copy that opens from the link does not save your work. If your U of U Google account cannot open Colab, a personal Google account can.
Before you start
- Time. Plan on about 2.5 hours: about 40 minutes for Exercise 1, about an hour for Exercise 2, and about 45 minutes for Exercise 3. The fits take seconds. Most of the time goes to reading the output and the five written cells.
- Practice first, if you like. The customer clusters trainer puts the Summit Gear accounts on two columns and lets you step k-means, switch scaling on and off, and ring the accounts farthest from their centers. It is not graded.
- Two ways to write the code. Each step that needs code shows two options side by side. Ask an AI gives a prompt for Gemini in Colab or any AI tool. Type it yourself gives the code to type or paste, with a line on what it prints. Pick either one, step by step. Both should give the same results, and neither earns more points. Whichever you use, put the code in the cell the step names, in place of the lines that set its names to
None. - The settings are fixed. Everyone clusters the same six columns, scaled, with k = 4,
n_init=10andrandom_state=12, so your clusters can be checked against a key. You still argue for your own k in Exercise 2. - Two helpers are provided.
cluster_numbers()numbers the clusters 1 to 4 by median annual spend, so your numbers line up with the key.check_fit()prints a fit's settings and sizes against the X you pass it, and warns if the model was not fit on that X. Nothing in this lab is a hand-written helper. - In Canvas, Lab 12 is a short quiz with one file upload and four short closing questions, which are not graded.
The data
- summit_gear_customers.csv: the same 2,200 accounts as Weeks 10 and 11, one row each. The notebook reads it from this link for you.
- The data dictionary: every column, its unit and its timing. It was written for Week 11. This week no column is a target, and
defaultedcomes back only for the check after the fact.
This week there is no target. The notebook sets defaulted and days_to_pay aside right after it loads the table, so k-means never sees them. defaulted comes back once, after the clusters are built, as a check on what they found. About 20% of the accounts defaulted, the base rate (19.9%).
Clustered: the six lab columns
annual_spendprior_late_countdays_since_last_orderorders_per_yeardiscount_rateavg_order_valueScaled to z-scores before k-means.
In the deck, left out here
credit_limitavg_balanceExercise 2 asks what leaving them out changes.
Set aside until the check
defaulteddays_to_paydefaulted comes back after the clusters are built.
The three steps
- 1Distance and scaling
Measure how far apart two accounts are, raw and scaled, and fit k-means at k = 4 both ways.
One pair, then all 2,200 - 2Choose k and read the clusters
Argue for k from the elbow and silhouette table, name the four clusters, then bring
k from 2 to 8, graded at 4defaultedback as a check. - 3Accounts that fit nowhere
Rank every account by its distance to its own cluster's center, flag the top 1%, and decide which to ask about.
The farthest 1%
The three exercises
Exercise 1: Distance and scaling 30 points
- Compute the Euclidean distance between accounts C-01417 and C-02031 on the six raw columns, and the share of the squared distance that comes from
annual_spend. Distance: take the difference in each column, square it, add the squares, and take the square root. - Scale the six columns with
StandardScaler, keep the result as a DataFrame with the column names, and compute the same pair's distance in scaled units. A z-score is (value minus mean) divided by sd, so a step of 1 means the same thing in every column. - Fit k-means at k = 4 on the raw columns and on the scaled ones, same settings. Run
check_fit()on both and compare each line with what you asked for.
Step 1a: the raw distance
Notebook cell: TODO (Exercise 1a). It replaces the lines that set pair_raw and spend_share to None.
Read the code before you run it. It must set pair_raw and spend_share.
# Each column's difference, then squared
diff = pair.iloc[0] - pair.iloc[1]
sq = diff ** 2
# Add the squares and take the square root
pair_raw = float(np.sqrt(sq.sum()))
# annual_spend's squared difference over the total
spend_share = float(sq["annual_spend"] / sq.sum())
print(pd.DataFrame({"difference": diff.round(2),
"squared": sq.round(2),
"share": (sq / sq.sum()).round(4)}))
pair has one row per account, so the first line gives one difference per column. It prints a table with six rows, one per lab column: the difference, the squared difference, and that column's share. The shares add up to 1. The cell below prints pair_raw and the share from annual_spend.
Step 1b: scale, then the scaled distance
Notebook cell: TODO (Exercise 1b). It replaces the lines that set X_raw, X_scaled and pair_scaled to None.
Read the code before you run it. X_scaled must be a DataFrame with the column names, not a bare array.
X_raw = df[LAB_COLUMNS]
# z-scores: (value minus mean) / sd, column by column
scaler = StandardScaler()
X_scaled = pd.DataFrame(scaler.fit_transform(X_raw),
columns=LAB_COLUMNS, index=df.index)
# The two accounts' rows of z-scores
za = X_scaled[df["customer_id"] == PAIR[0]].iloc[0]
zb = X_scaled[df["customer_id"] == PAIR[1]].iloc[0]
zsq = (za - zb) ** 2
pair_scaled = float(np.sqrt(zsq.sum()))
print((zsq / zsq.sum()).round(4)
.rename("share of scaled distance").to_string())
fit_transform returns a plain array, so pd.DataFrame puts the column names and row index back. check_fit reads the names. It prints six shares, one per column, that add up to 1. The check cell below shows mean 0 and sd 1 for every column, then the scaled distance.
Step 1c: fit k-means twice
Notebook cell: TODO (Exercise 1c). It replaces the lines that set km_unscaled and km_scaled to None.
Read the code before you run it. Both fits must use K, N_INIT and SEED.
km_unscaled = KMeans(n_clusters=K, n_init=N_INIT,
random_state=SEED).fit(X_raw)
km_scaled = KMeans(n_clusters=K, n_init=N_INIT,
random_state=SEED).fit(X_scaled)
K, N_INIT and SEED are set near the top of the notebook. The two fits differ only in the X. This cell prints nothing. The check cell below runs check_fit() on each fit, and the cell after it prints the median of each column by cluster, one table per fit.
Written: Why unscaled is a sort by spend. Three to five sentences.
- Give the share of the pair's squared raw distance that comes from
annual_spend, and say why one column can carry that much. - Say what changed when you scaled: the scaled distance, and which columns now carry most of it.
- Compare the unscaled and scaled cluster sizes, and say what separates the unscaled clusters.
Graded on (14 points): The spend share and the scaled distance from your output. A reason tied to the columns' units. The columns that carry the scaled distance. The unscaled sizes, and what the unscaled clusters have in common.
Exercise 2: Choose k and read the clusters 40 points
- Fit k-means on the scaled columns for every k from 2 to 8 and record the inertia and the silhouette of each, in a table named
elbow. The notebook draws both charts. - Inertia is the sum of each account's squared distance to its own center. It keeps falling as k rises, because each extra center can only shorten distances. The silhouette compares each account's average distance to the rest of its own cluster with its average distance to the next nearest cluster. It runs from -1 to 1, and values near 0 mean the clusters overlap. Neither is a rule. Each is evidence.
- The graded fit stays at k = 4, so everyone's clusters compare. Build
profile, the median of each lab column by cluster, and read it. - Then the notebook brings
defaultedback. Compute the default rate by cluster, asdefault_by_cluster.
Step 2a: the elbow and silhouette table
Notebook cell: TODO (Exercise 2a). It replaces the line that sets elbow to None.
Read the code before you run it. Every fit must be on X_scaled, with N_INIT and SEED.
rows = []
for k in range(2, 9): # k = 2 through 8
m = KMeans(n_clusters=k, n_init=N_INIT,
random_state=SEED).fit(X_scaled)
sil = silhouette_score(X_scaled, m.labels_)
rows.append({"k": k, "inertia": m.inertia_,
"silhouette": sil})
elbow = pd.DataFrame(rows)
range(2, 9) stops before 9, so the loop fits seven models. Each pass records the fit's inertia and its silhouette on the same scaled data. This cell prints nothing and may take a few seconds. The cell below prints elbow, seven rows with k, inertia and silhouette, and draws the two charts.
Step 2b: the profile of each cluster
Notebook cell: TODO (Exercise 2b), after the cell that adds df["cluster"]. It replaces the line that sets profile to None.
Read the code before you run it. It must group by the cluster column the notebook made, not refit k-means.
profile = df.groupby("cluster")[LAB_COLUMNS].median()
# Put the count of accounts first, as column n
counts = df["cluster"].value_counts().sort_index()
profile.insert(0, "n", counts)
print(profile.round(2).to_string())
The cluster column comes from the cell above, which numbered the clusters with cluster_numbers(). It prints four rows, clusters 1 to 4, each with n and a median for every lab column.
Step 2c: the default rate by cluster
Notebook cell: TODO (Exercise 2c), after the cell that brings defaulted back. It replaces the line that sets default_by_cluster to None.
Read the code before you run it. The result must be a Series indexed by cluster number.
# defaulted is 1 or 0, so its mean is the share
by_cluster = df.groupby("cluster")["defaulted"]
default_by_cluster = by_cluster.mean()
print(default_by_cluster.map("{:.1%}".format))
It prints one line per cluster, clusters 1 to 4, each a percentage. The cell below lines each rate up against the base rate.
Written: Your argument for k. Three or four sentences.
- What inertia does as k rises, and why the lowest inertia cannot choose k.
- Which k has the highest silhouette, and how strong that is on a scale from -1 to 1, where values near 0 mean the clusters overlap.
- The k you would pick for the credit team, and why. The graded fit stays at k = 4 either way.
Graded on (8 points): Why falling inertia cannot pick k by its lowest value. The silhouette read from your table, with the highest k and a fair word on its strength. A k with a reason, which may be a business reason. Any k earns full credit if the argument uses the table.
Written: Name your four clusters. One line per cluster, then one sentence.
- Clusters 1 to 4: the size, the medians that set the cluster apart from the other three, and a business name a credit manager would recognize
- The numbers: one sentence on what the cluster numbers do and do not tell you
Graded on (8 points): Four lines, each with the size and the medians that set the cluster apart, from your profile table. Business names that match those medians. A correct sentence on what the numbering means.
Written: The check after the fact. Four to six sentences.
- The default rate by cluster against the 19.9% base rate, with the numbers. Which cluster stands out, and which of its medians might explain it.
- The deck's eight-column clusters ran from 17.8% to 22.9%. Yours differ. Which two columns did this lab drop, and why does dropping them change what k-means finds?
- Why this is a check on the clusters and not a default model.
Graded on (12 points): Default rates by cluster from your output, compared with 19.9%. The cluster that stands out, tied to its medians. The two dropped columns named, with a reason tied to what they measure and how k-means weighs every column it is given. Why rates on clusters built without defaulted are a check, not a prediction.
Exercise 3: Accounts that fit nowhere 30 points
- Week 6 flagged values far from one column's middle. Now do it across all six columns at once. Compute each account's distance to its own cluster's center, in scaled units, as
dist_to_center. - List the top 1% by that distance (22 of 2,200 accounts) as
flags, with each account's most extreme column: the lab column where the account's z-score is largest in absolute value. That is the account's most unusual column overall. It is not always the column that puts the account far from its own center. - After the flag list, write one line yourself in the cell marked
TODO (Exercise 3c):flag_default_rate, the share of the flagged accounts that defaulted. - A flagged account is worth a look. It is not wrong because it is far from its center. Some accounts are unusual for ordinary business reasons, and every review costs someone's time.
Step 3a: each account's distance to its own center
Notebook cell: TODO (Exercise 3a). It replaces the line that sets dist_to_center to None.
Read the code before you run it. It must keep one distance per account, to that account's own center.
# One row per account, one distance per cluster center
all_d = km_scaled.transform(X_scaled)
# Keep the distance to each account's own center
own = km_scaled.labels_
dist_to_center = all_d[np.arange(len(df)), own]
km_scaled.labels_ holds each account's own cluster in the model's numbering, 0 to 3, so the last line picks one distance from each row. This cell prints nothing. The cell below prints a summary of the 2,200 distances and draws a histogram with a dashed line where the top 1% start.
Step 3b: the flag list
Notebook cell: TODO (Exercise 3b). It replaces the line that sets flags to None.
Read the code before you run it. The column names must match the prompt, because the Final check reads them.
n_flag = round(0.01 * len(df))
# Rows from the farthest down; keep the top 1%
top = np.argsort(-dist_to_center, kind="stable")[:n_flag]
Z = X_scaled.to_numpy()
rows = []
for i in top:
# The column with the largest absolute z-score
j = int(np.argmax(np.abs(Z[i])))
col = LAB_COLUMNS[j]
rows.append({
"customer_id": df["customer_id"].iloc[i],
"segment": df["segment"].iloc[i],
"cluster": int(df["cluster"].iloc[i]),
"distance": round(float(dist_to_center[i]), 3),
"extreme_col": col,
"extreme_z": round(float(Z[i, j]), 2),
"extreme_value": float(df[col].iloc[i]),
"defaulted": int(df["defaulted"].iloc[i]),
})
flags = pd.DataFrame(rows)
Sorting the negative distances puts the largest first. In the loop, np.abs drops the sign to find the most extreme column, and extreme_z keeps the sign, so you can tell high from low. extreme_value is that column's raw value from df, in its own units. This cell prints nothing. The cell below prints the flagged accounts, one row each, farthest first, then how often each column is the most extreme.
Written: Three accounts to review. About 150 to 250 words, as a short list or a paragraph.
- Three accounts from your flag list, each by
customer_id, with its most extreme column and what that value is. - For each, what you would ask and of whom, and why that person or record can answer it.
- One flagged account that is probably unusual for a harmless reason, and why.
- The flagged accounts' default rate against the 19.9% base rate, and what it says about unusual and risky.
Graded on (18 points): Three flagged accounts by id, each with its most extreme column and value from your output. A specific question for each, put to a person or record that can confirm the answer on its own. One harmless explanation that fits the numbers. The flagged default rate from your output against 19.9%, read with care.
Ask the tutor
The tutor reads this box and the exercise. It can explain a distance, a z-score, an elbow chart or an error. It will not write your written answers for you.
What the tutor sees, and a prompt to copy into another AI tool
The preview shows the full prompt, including earlier turns of the conversation. Nothing on this page submits to Canvas.
What to submit
In Canvas, Lab 12 is a short quiz with one file upload and four short closing questions. The file is your notebook, run top to bottom. In Colab choose File > Download > Download .ipynb, rename it <uID>_lab_12.ipynb with your uID in place of <uID>, upload it to Lab 12, answer the closing questions, and submit the quiz.
Three checks before you submit
- Runtime > Restart session and run all. Every cell shows its output, and the Final check reads your latest work.
- The Final check prints
RESULTSwith nonullin it, and every row is green. - Your five written cells have your words in them, not the placeholder line.
Lab 12 check: 8 of 9 done
| ✓ | X_scaled: 2,200 rows, the six lab columns, mean 0 and sd 1 | done |
| ✓ | pair_raw, spend_share and pair_scaled: the two accounts | done |
| ✓ | km_unscaled and km_scaled: k = 4, n_init = 10, random_state = 12 | done |
| ✓ | elbow: k from 2 to 8, inertia and silhouette | done |
| ✓ | profile: four clusters, a median for each lab column | done |
| ✓ | default_by_cluster: a default rate for each cluster | done |
| ✓ | dist_to_center: one distance per account | done |
| ✓ | flags: the top 1%, with the most extreme column of each | done |
| ✗ | flag_default_rate: the flagged accounts' default rate | not yet, see Exercise 3 |
RESULTS = {"columns": [the six lab columns], "pair_raw": xxxxx.x, "pair_spend_share": 0.xxxx, "pair_scaled": x.xxx, "sizes_unscaled": [n, n, n, n], "sizes": [n, n, n, n], "inertia_k4": xxxx.x, "elbow": [[2, xxxxx.x, 0.xxx], ...], "medians": {...}, "base_rate": 0.1991, "default_rate": {"1": 0.xxxx, ...}, "n_flagged": 22, "flagged_ids": [...], "drivers": {...}, "flag_default_rate": null}
Still to do: flag_default_rate: the flagged accounts' default rate (Exercise 3)
flag_default_rate is still null and one row is red, so this notebook is not ready to submit. A red row names the exercise to go back to.How it is graded
Lab 12 is worth 100 points, all of them for the notebook. The four closing questions are not graded.
| Exercise | Numbers in RESULTS | Your writing | Total |
|---|---|---|---|
| 1. Distance and scaling | the pair's raw distance and spend share 6, the scaled distance and the scaled check 4, both fits and their sizes 6: 16 | why unscaled is a sort by spend 14 | 30 |
| 2. Choose k and read the clusters | the elbow table 4, the profile (sizes and medians) 4, the default rate by cluster 4: 12 | your argument for k 8, the cluster names 8, the check after the fact 12 | 40 |
| 3. Accounts that fit nowhere | the 22 flagged accounts 6, their most extreme columns 3, the flagged default rate 3: 12 | three accounts to review 18 | 30 |
| Total | 40 | 60 | 100 |
A script reads the RESULTS your Final check prints and reruns the same columns, scaling, k and seed from the data. Because the settings are fixed, your numbers should match the rerun. Small differences from rounding, or from scaling with the sample standard deviation instead of StandardScaler's, are accepted.
The five written cells are 60 of the 100 points. Each is read against the line under "Graded on" in its exercise above, and any number you quote is checked against your own output. An AI tool may write the clustering code, or you may type it from this page. Either way, the points go to the checks you ran, what you read in the output, and the five written cells.
You may resubmit. Each new attempt starts empty, so upload the notebook again and answer the closing questions again. The latest attempt is kept, so a resubmission after the deadline replaces your on-time attempt and is marked late.