Lab 12: Group Summit Gear's Customers

ACCTG 6155, Fall 2026, Week 12. Due Sunday, November 22, 11:59 PM MT. One notebook, one upload. Plan on about 2.5 hours.
The AI tutor on this page knows which exercise you are reading. Paste what you have into the box at the bottom, then ask. Show it your attempt first.

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.

Open Lab 12 in Colab

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

The data

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_value

Scaled to z-scores before k-means.

In the deck, left out here

credit_limitavg_balance

Exercise 2 asks what leaving them out changes.

Set aside until the check

defaulteddays_to_pay

defaulted comes back after the clusters are built.

Which columns k-means sees. The deck clustered eight behavior columns. The lab clusters six of them. The two outcome columns stay out of every fit.

The three steps

  1. 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
  2. 2Choose k and read the clusters

    Argue for k from the elbow and silhouette table, name the four clusters, then bring defaulted back as a check.

    k from 2 to 8, graded at 4
  3. 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 deck clustered a different set of columns, so your clusters will differ from the slides'. That is expected, and Exercise 2 asks you to explain it.

The three exercises

Exercise 1: Distance and scaling 30 points

Step 1a: the raw distance

Notebook cell: TODO (Exercise 1a). It replaces the lines that set pair_raw and spend_share to None.

Ask an AI
pair is a pandas DataFrame with two rows, one per account, and six columns. Compute the Euclidean distance between the two rows as pair_raw. Then compute spend_share: the squared difference in annual_spend divided by the sum of the six squared differences. Print a table with each column's difference, squared difference and share of the total.

Read the code before you run it. It must set pair_raw and spend_share.

Type it yourself
# 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.

Ask an AI
Set X_raw = df[LAB_COLUMNS]. Scale it with sklearn's StandardScaler and keep the result as a DataFrame named X_scaled, with columns=LAB_COLUMNS and index=df.index. Then compute pair_scaled, the Euclidean distance between the rows of X_scaled for the two customer_ids in PAIR, and print each column's share of the squared scaled distance.

Read the code before you run it. X_scaled must be a DataFrame with the column names, not a bare array.

Type it yourself
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.

Ask an AI
Fit sklearn KMeans(n_clusters=K, n_init=N_INIT, random_state=SEED) on X_raw and name it km_unscaled. Fit the same settings on X_scaled and name it km_scaled.

Read the code before you run it. Both fits must use K, N_INIT and SEED.

Type it yourself
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

Step 2a: the elbow and silhouette table

Notebook cell: TODO (Exercise 2a). It replaces the line that sets elbow to None.

Ask an AI
For k from 2 to 8, fit KMeans(n_clusters=k, n_init=N_INIT, random_state=SEED) on X_scaled. Record k, the fit's inertia_, and silhouette_score(X_scaled, labels). Put the results in a DataFrame named elbow with columns k, inertia and silhouette, one row per k, and print it.

Read the code before you run it. Every fit must be on X_scaled, with N_INIT and SEED.

Type it yourself
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.

Ask an AI
Group df by the cluster column and take the median of each column in LAB_COLUMNS. Name the result profile, with one row per cluster (the index is the cluster number) and one column per lab column. Add a column n with the number of accounts in each cluster, and print profile rounded to 2 places.

Read the code before you run it. It must group by the cluster column the notebook made, not refit k-means.

Type it yourself
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.

Ask an AI
Group df by cluster and take the mean of defaulted, as a Series named default_by_cluster indexed by cluster number. Print it as percentages.

Read the code before you run it. The result must be a Series indexed by cluster number.

Type it yourself
# 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

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.

Ask an AI
km_scaled.transform(X_scaled) gives each account's distance to every cluster center. For each account, take the distance to the center of its own cluster (km_scaled.labels_) and keep the result as a numpy array named dist_to_center, one value per row of df.

Read the code before you run it. It must keep one distance per account, to that account's own center.

Type it yourself
# 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.

Ask an AI
Make a DataFrame named flags with the 22 accounts that have the largest dist_to_center (1% of the rows of df), sorted from the largest distance down. Columns: customer_id, segment, cluster, distance (the dist_to_center value), extreme_col (the column of X_scaled with the largest absolute value in that account's row), extreme_z (that z-score, with its sign), extreme_value (that column's raw value in df), and defaulted. Print it.

Read the code before you run it. The column names must match the prompt, because the Final check reads them.

Type it yourself
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

  1. Runtime > Restart session and run all. Every cell shows its output, and the Final check reads your latest work.
  2. The Final check prints RESULTS with no null in it, and every row is green.
  3. 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 1done
✓pair_raw, spend_share and pair_scaled: the two accountsdone
✓km_unscaled and km_scaled: k = 4, n_init = 10, random_state = 12done
✓elbow: k from 2 to 8, inertia and silhouettedone
✓profile: four clusters, a median for each lab columndone
✓default_by_cluster: a default rate for each clusterdone
✓dist_to_center: one distance per accountdone
✓flags: the top 1%, with the most extreme column of eachdone
✗flag_default_rate: the flagged accounts' default ratenot 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)
A sample Final check with one piece left. Your numbers replace the x's. Here 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.

ExerciseNumbers in RESULTSYour writingTotal
1. Distance and scalingthe pair's raw distance and spend share 6, the scaled distance and the scaled check 4, both fits and their sizes 6: 16why unscaled is a sort by spend 1430
2. Choose k and read the clustersthe elbow table 4, the profile (sizes and medians) 4, the default rate by cluster 4: 12your argument for k 8, the cluster names 8, the check after the fact 1240
3. Accounts that fit nowherethe 22 flagged accounts 6, their most extreme columns 3, the flagged default rate 3: 12three accounts to review 1830
Total4060100

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.