← Blog/KNN for Marketing: Recommend the Next Add-On, Step by Step
Machine LearningKNNPythonRecommendationsMarketing Analytics
Machine Learning · 25 min read

KNN for Marketing: Recommend the Next Add-On, Step by Step

A step-by-step KNN case for marketers: recommend each customer's next add-on from customers like them, in Python, with real code, data and charts.

· Martin Guzman

This is a business case for k-nearest neighbours (KNN): we use it to suggest the next add-on for every customer of a made-up software company, step by step in Python. Tuned with care, KNN puts the add-on a customer really uses among its three suggestions 85 percent of the time, against 44 percent for offering everyone the most popular add-on. Built the way most tutorials build it, with a handful of neighbours, it barely beats that popularity rule; step 8 shows a one-line fix.

KNN judges something by the known examples most like it. Here the "something" is a customer, the examples are other customers, and the question is which add-on they use that this customer does not. This guide focuses on the business problem and the build. For the math behind the model, how to choose its settings and how to judge it, read How KNN Works first or alongside.

Every number, table and chart below is real output from code you can download and run. The company and its data are invented, so nothing here belongs to a client.

The application: what to offer each customer next

Northpine Software, the made-up company used throughout this series, sells a business software subscription with 12 paid add-ons: connectors to a CRM, accounting or e-commerce system, payments, a help desk, team chat, single sign-on, an audit log, advanced reporting, API access, a data warehouse export and e-signature.

Northpine has 4,000 paying customers. On average each uses 2.61 add-ons, so almost every customer could use more. Account managers have a quarterly check-in with each customer, and lifecycle marketing sends one cross-sell email a month. Both have room for one or two suggestions. The question is the same for both teams: which add-on should we suggest to this customer?

What teams usually do

Without a model, teams use one of two rules:

  • Most popular first. Suggest the best-selling add-on the customer does not have yet. At Northpine that is CRM sync, used by 32.7 percent of customers.
  • Most popular in the segment. Suggest what sells best among customers in the same industry and on the same plan.

Both are reasonable. The first gives the same first suggestion, CRM sync, to every customer who does not have it yet: two in three customers. The second is better, but a segment is a blunt group: a software company that uses API access and warehouse export has more in common with a data-heavy manufacturer than with a software company that only uses e-signature.

What KNN changes

KNN looks at what each customer already uses, finds the customers whose usage looks most like theirs, and suggests what those customers use that this one does not. To check it honestly, we hide one add-on from every customer who uses two or more, and count how often each method suggests it among its first three. On the 1,711 test customers (step 12 shows the code):

How the suggestion is chosenHidden add-on in the first suggestionIn the first three
Most popular overall19.7%44.1%
Most popular in their industry and plan30.8%53.5%
Plain KNN, 10 nearest customers21.0%46.8%
Plain KNN, 480 nearest customers (its tuned k)55.9%85.2%
KNN, 160 nearest customers with something new (its tuned k)55.8%85.3%
Item-based KNN56.4%85.6%
Logistic regression, one model per add-on54.4%84.2%

Three results stand out. First, plain KNN, built the way most tutorials build it with a handful of neighbours, barely beats the most-popular rule: 46.8 percent against 44.1. Step 7 shows why: most of a customer's nearest neighbours use nothing it lacks, so they have nothing to suggest.

Second, plain KNN does catch up, but only with a very large neighbourhood. Its best k is 480 neighbours, out of 4,000 customers, and there it is level with a version that only lets customers with something new vote, 85.2 against 85.3 percent. That one-line fix, in step 8, gets close to its best with 20 to 40 neighbours, so the customers behind a suggestion stay few and genuinely similar, which is what makes them worth showing to an account manager.

Third, the fixed version, its close cousin item-based KNN ("customers who use this also use...") and a logistic regression all find the hidden add-on in the first three suggestions 84 to 86 percent of the time, against 44 percent for the most-popular rule. On this data, how the neighbours are chosen matters more than which method you pick.

What the teams receive

Each month, a table with one row per customer: the next add-on to suggest, and how many of the customer's lookalikes use it. For example, from the list built in step 13:

CustomerIndustryPlanUses todayNext best add-onLookalikes using it
NC-00321SoftwareGrowthteam chat, advanced reporting, e-signatureCRM sync152 of 160
NC-00187SoftwareGrowthsingle sign-on, advanced reporting, API accesswarehouse export149 of 160
NC-01494EducationGrowthsingle sign-on, warehouse exportAPI access146 of 160

And how each team uses it:

TeamDecisionWhat they do with the list
Account managementWhat to raise at the quarterly check-inLead with the top suggestion, and give the count behind it, "many companies set up like yours also use...", as the reason
Lifecycle marketingWhich cross-sell email each customer getsSend each customer the email for their top suggestion instead of one email to everyone
Product marketingWhich add-ons to bundle or promote togetherRead the item pairs in step 10: add-ons that go together make natural bundles
Customer successWhere adoption is laggingA customer far from every lookalike, or with a very confident suggestion they have not taken, is worth a call

Other places the same idea works

The same "customers like you" logic sits under:

  • Next product to buy in retail and e-commerce, from basket or purchase history.
  • Content recommendations, such as which guide or webinar to send next, from what similar readers opened.
  • Feature adoption prompts inside a product, from which features similar accounts switched on.
  • Upsell targeting, by ranking customers by how many of their lookalikes already use an add-on.

KNN in one minute

To suggest an add-on, KNN describes every customer by the add-ons they use, measures how alike two customers are, takes the k most alike, and counts how many of them use each add-on this customer lacks. The add-on with the most votes is the suggestion. How KNN Works explains the general method with the math; this case changes two details. Similarity is measured by overlap rather than distance, because each column is just "uses it" or "does not". And the vote is over add-ons rather than over a yes-or-no outcome.

Try it on six real Northpine customers. Each has one add-on hidden, marked with a question mark. Start with "Nearest customers" and look at how many neighbour rows are faded: those neighbours use nothing this customer lacks, so they cannot vote for anything. Then switch to "Nearest with something new".

Pick a customer and watch its neighbours vote on the next add-on
Try it
Customer (one add-on hidden):
CRMAcctShopPayHelpChatSSOAuditRptsAPIDWHSignNC-00002?NC-03963 0.75NC-00174 0.67NC-01020 0.67NC-01415 0.67NC-02040 0.67NC-02205 0.67NC-02657 0.67NC-02986 0.67NC-03111 0.67NC-03715 0.67000000010votes
Hover or tap a column to read it.
10
Neighbours with something to offer
1 of 10
Top three recommendations
DWH · CRM · Sign
Warehouse export, CRM sync, E-signature
Hidden add-on: API access
missed
the customer uses itneighbour uses it, customer does notboth use itthe hidden add-on
NC-00002: Software, Growth plan, 2,706 employees. Faded rows are neighbours that use nothing NC-00002 lacks, so their vote adds nothing. The number after each neighbour is its similarity: shared add-ons divided by add-ons either one uses.
Six real test customers, each with one add-on hidden. Neighbours are their nearest customers among all 4,000, from the notebook appendix.

The data: Northpine's add-ons

This guide uses two tables. northpine_addons.csv has one row per customer and one column per add-on, with 1 if the customer uses it and 0 if not. northpine_customers.csv, shared with other guides in the series, adds what we know about each customer. We use three of its columns, plus the ID:

ColumnWhat it isRange
customer_idCustomer identifier, shared by both tablesNC-00001 to NC-04000
industryThe customer's sectorsix sectors
planSubscription planStarter, Growth or Enterprise
employeesCompany headcounta whole number
crm_sync … e_signatureUses that add-on (1) or not (0)12 columns

Here are the first five rows of the add-on table, with six of the 12 add-on columns left out to fit (step 1 prints them all):

customer_idcrm_syncaccounting_syncecommerce_connectorpaymentshelp_deskteam_chat
NC-00001100000
NC-00002000100
NC-00003100001
NC-00004010100
NC-00005000011
The data: who uses which add-on
Try it
CRM sync32.7%E-signature29.5%Advanced reporting27.2%Team chat26.7%Payments26.5%Accounting sync25.0%Help desk22.7%API access20.4%Warehouse export19.4%E-commerce connector11.7%Audit log11.3%Single sign-on8.0%
Hover or tap a bar to read it.
All 4,000 Northpine customers in northpine_addons.csv.

Three things to notice before writing any code.

Usage is sparse. Most customers use two or three add-ons out of 12. That is normal for add-ons, and it matters for KNN: two customers who each use two add-ons can only overlap on zero, one or two of them, so there are not many different levels of "alike".

We can only test on customers who use at least two add-ons. The test hides one add-on and checks whether the method suggests it, so the customer needs at least one more for the method to work from. The 81 customers with none and the 497 with one are still used as neighbours and still get suggestions; they just cannot be scored.

Popularity and similarity are computed after hiding. Step 4 hides one add-on per tested customer. From then on every count, the popularity of each add-on, the similarity between customers and every model, uses the table with those add-ons hidden, called H in the code, never the full table. Computing them from the full table would leak the hidden answers back into the suggestions and flatter every method.

Step by step in Python

The code uses pandas and NumPy, plus scikit-learn for one comparison in step 12, all free. Every block below is a cell in the downloadable notebook, and every output shown is what it printed.

Step 1: load the data

import numpy as np
import pandas as pd
pd.set_option("display.max_colwidth", None)
pd.set_option("display.width", 200)
 
addons = pd.read_csv("northpine_addons.csv")
customers = pd.read_csv("northpine_customers.csv")[["customer_id", "industry", "plan", "employees"]]
data = customers.merge(addons, on="customer_id")
 
ADDONS = list(addons.columns[1:])
print(data.shape)
print(ADDONS)
print(addons.head().to_string(index=False))
(4000, 16)
['crm_sync', 'accounting_sync', 'ecommerce_connector', 'payments', 'help_desk', 'team_chat', 'single_sign_on', 'audit_log', 'advanced_reporting', 'api_access', 'warehouse_export', 'e_signature']
customer_id  crm_sync  accounting_sync  ecommerce_connector  payments  help_desk  team_chat  single_sign_on  audit_log  advanced_reporting  api_access  warehouse_export  e_signature
   NC-00001         1                0                    0         0          0          0               0          0                   1           0                 0            1
   NC-00002         0                0                    0         1          0          0               1          0                   1           1                 0            0
   NC-00003         1                0                    0         0          0          1               1          0                   0           0                 0            1
   NC-00004         0                1                    0         1          0          0               0          0                   0           0                 0            0
   NC-00005         0                0                    0         0          1          1               0          0                   0           0                 0            0

Four thousand customers. The 16 columns are the four customer columns plus the 12 add-ons. The last lines are the first five rows of the add-on table.

Step 2: look at the add-ons

owned = data[ADDONS].sum(axis=1)
print(f"add-ons per customer: mean {owned.mean():.2f}")
print(owned.value_counts().sort_index().to_string())
print()
print(data[ADDONS].mean().sort_values(ascending=False, kind="stable").round(3).to_string())
add-ons per customer: mean 2.61
0      81
1     497
2    1312
3    1354
4     554
5     177
6      24
7       1
 
crm_sync               0.327
e_signature            0.295
advanced_reporting     0.272
team_chat              0.267
payments               0.265
accounting_sync        0.250
help_desk              0.226
api_access             0.204
warehouse_export       0.194
ecommerce_connector    0.117
audit_log              0.112
single_sign_on         0.080

CRM sync is the most used add-on, at 32.7 percent of customers. Single sign-on is the least used, at 8.0 percent. Remember the top of this list: the most-popular rule will suggest CRM sync first to every customer who does not have it, about two in three customers (step 13 counts them).

Step 3: turn usage into similarity

M = data[ADDONS].to_numpy()          # one row per customer, one column per add-on, 1 = uses it
 
def jaccard(A):
    """Similarity of every row with every other row: shared add-ons / add-ons either one uses."""
    A = A.astype(float)
    shared = A @ A.T
    size = A.sum(axis=1)
    either = size[:, None] + size[None, :] - shared
    return np.divide(shared, either, out=np.zeros_like(shared), where=either > 0)
 
S_full = jaccard(M)
print(f"{S_full.shape[0]:,} x {S_full.shape[1]:,} similarities")
print(data.loc[[0, 1], ["customer_id"] + ADDONS].to_string(index=False))
print(f"similarity of these two: {S_full[0, 1]:.3f}")
4,000 x 4,000 similarities
customer_id  crm_sync  accounting_sync  ecommerce_connector  payments  help_desk  team_chat  single_sign_on  audit_log  advanced_reporting  api_access  warehouse_export  e_signature
   NC-00001         1                0                    0         0          0          0               0          0                   1           0                 0            1
   NC-00002         0                0                    0         1          0          0               1          0                   1           1                 0            0
similarity of these two: 0.167

M is the usage table as a grid of zeros and ones, one row per customer. The similarity is the Jaccard index: the number of add-ons two customers share, divided by the number that either of them uses. It runs from 0, nothing in common, to 1, exactly the same add-ons.

The first two customers share one add-on, advanced reporting, out of six that either uses, so their similarity is 1 ÷ 6 = 0.167. Why not the usual distance from How KNN Works? With yes-or-no columns, distance counts shared zeros as agreement. Two customers who both lack ten add-ons would look alike for what they do not use, which says little about what they want. Jaccard ignores shared zeros.

Step 4: hide one add-on per customer

To judge a recommender, you need to know the right answer. We create one: hide one add-on from every customer who uses at least two, and see whether each method suggests it.

rng = np.random.default_rng(42)
eligible = np.where(M.sum(axis=1) >= 2)[0]
 
H = M.copy()                 # what the model is allowed to see
hidden = {}                  # customer row -> the add-on we hid
for u in eligible:
    j = rng.choice(np.where(M[u] == 1)[0])
    H[u, j] = 0
    hidden[u] = j
 
order = rng.permutation(eligible)
tune, test = np.sort(order[: len(order) // 2]), np.sort(order[len(order) // 2:])
print(f"customers with 2+ add-ons: {len(eligible):,}")
print(f"tuning: {len(tune):,}   test: {len(test):,}")
customers with 2+ add-ons: 3,422
tuning: 1,711   test: 1,711

H is what every method is allowed to see. The 3,422 testable customers are split in half: we choose settings on the tuning half and report results on the test half, which plays the role of held-out data. default_rng(42) makes the hidden add-ons and the split repeatable, so your numbers will match these.

This test has a limit worth naming now. A hit means the method found an add-on the customer chose on their own. It does not prove that suggesting it would have made them buy it. "Using the recommendations" below covers how to measure that.

Step 5: the baseline to beat

def hit_rate(recommend, rows, n=3):
    """Share of customers whose hidden add-on is among the n recommendations."""
    return np.mean([hidden[u] in recommend(u)[:n] for u in rows])
 
popularity = H.mean(axis=0)
 
def rank(score):
    """Add-ons from highest score to lowest. Ties go to the more popular add-on."""
    return np.lexsort((-popularity, -score))
 
def most_popular(u):
    score = popularity.copy()
    score[H[u] == 1] = -1                      # never recommend what they already use
    return rank(score)
 
print(f"most popular, top 3: {hit_rate(most_popular, test):.3f}")
most popular, top 3: 0.441

hit_rate asks each method for its suggestions, keeps the first three, and counts how often the hidden add-on is among them. Recommending the three most popular add-ons the customer does not have finds the hidden one 44.1 percent of the time. With only 12 add-ons, three guesses already cover a quarter of the catalogue, so this baseline is not easy to beat.

rank puts add-ons in order from highest score to lowest. When two add-ons have the same score, it puts the more popular one first. That detail matters more than it looks: in step 7, ties decide many of plain KNN's suggestions.

Step 6: plain KNN

S = jaccard(H)
np.fill_diagonal(S, -1)                        # a customer is not its own neighbour
 
def knn_naive(u, k):
    neighbours = np.argsort(-S[u], kind="stable")[:k]
    score = H[neighbours].mean(axis=0)         # share of neighbours using each add-on
    score[H[u] == 1] = -1
    return rank(score)
 
print(f"tuning half, most popular:      {hit_rate(most_popular, tune):.3f}")
for k in [5, 10, 20]:
    print(f"tuning half, plain KNN, k = {k:>2}: {hit_rate(lambda u: knn_naive(u, k), tune):.3f}")
tuning half, most popular:      0.440
tuning half, plain KNN, k =  5: 0.453
tuning half, plain KNN, k = 10: 0.466
tuning half, plain KNN, k = 20: 0.491

This is user-based KNN as most tutorials write it: take the k most similar customers, score each add-on by the share of them who use it, and suggest the highest scores. We try it on the tuning half; the test half stays untouched until step 9. It barely beats the most-popular rule: 45.3 percent with 5 neighbours and 49.1 percent with 20, against 44.0 percent for popularity on the same customers.

Step 7: why plain KNN struggles here

def nothing_new(u, k):
    """Share of the k nearest customers who use nothing that customer u lacks."""
    neighbours = np.argsort(-S[u], kind="stable")[:k]
    new = H[neighbours][:, H[u] == 0].sum(axis=1)
    return np.mean(new == 0)
 
for k in [5, 10, 20]:
    print(f"k = {k:>2}: {np.mean([nothing_new(u, k) for u in tune]):.1%} of neighbours have nothing to recommend")
k =  5: 95.3% of neighbours have nothing to recommend
k = 10: 94.6% of neighbours have nothing to recommend
k = 20: 93.6% of neighbours have nothing to recommend

With 10 neighbours, 94.6 percent of the "most similar" customers use nothing that this customer lacks. They cannot vote for anything.

The reason is how Jaccard rewards overlap. Take a customer with three add-ons. Another customer who uses two of those three, and nothing else, shares 2 of the 3 add-ons either uses: 2 ÷ 3 = 0.667, very similar and no help at all. A customer who uses all three plus one more shares 3 of 4, which is 0.75, but there are few of those. So the nearest neighbours are mostly customers behind this one, using a subset of the same add-ons. When nearly every vote is zero, most add-ons tie, and the tie rule picks the suggestion. Our rank sends ties to the more popular add-on, so plain KNN with few neighbours ends up close to the most-popular rule, a little ahead of it. Leave ties in column order, as a plain np.argsort does, and it falls below popularity: 42.6 percent at k = 10 on the tuning half, against 46.6 percent with ties broken by popularity and 44.0 for the most-popular rule (the notebook appendix has the code).

You can see this in the playground above: with "Nearest customers" selected, most neighbour rows are faded.

Step 8: the fix, and choosing k

The fix is one line: before choosing neighbours, drop the customers who use nothing this customer lacks.

def knn(u, k):
    lacks = H[u] == 0
    has_something_new = H[:, lacks].sum(axis=1) > 0
    sim = np.where(has_something_new, S[u], -1)   # only neighbours with something to offer
    neighbours = np.argsort(-sim, kind="stable")[:k]
    score = H[neighbours].mean(axis=0)
    score[H[u] == 1] = -1
    return rank(score)
 
results = []
for k in [5, 10, 20, 40, 80, 160, 240, 320, 480, 640]:
    results.append((k, round(hit_rate(lambda u: knn_naive(u, k), tune), 3),
                       round(hit_rate(lambda u: knn(u, k), tune), 3)))
pd.DataFrame(results, columns=["k", "plain", "fixed"])
     k  plain  fixed
0    5  0.453  0.755
1   10  0.466  0.784
2   20  0.491  0.821
3   40  0.520  0.839
4   80  0.600  0.841
5  160  0.728  0.846
6  240  0.830  0.846
7  320  0.839  0.842
8  480  0.850  0.846
9  640  0.840  0.808

With the fix, five neighbours already find the hidden add-on 75.5 percent of the time on the tuning customers, against 45.3 percent without it. With 20 neighbours the fixed rule reaches 82.1 percent, and with 40, 83.9. From 40 to 480 every k scores between 0.839 and 0.846; only at 640 does it drop, to 0.808.

The plain rule climbs much more slowly. It needs 240 neighbours to pass 80 percent, and peaks at 480 with 0.850, slightly above the fixed rule's best of 0.846.

Choosing k, and why the plain rule fails
Try it
0%25%50%75%100%510204080160240320480640k, neighbours that vote (log scale)hidden add-on in top 3most popular 44.0%
nearest with something newnearest customersmost popular add-on
Hover or tap the chart to read each k.
The 1,711 tuning customers, one add-on hidden each. Hit rates from step 8, the most-popular line from step 6, and the share of neighbours with nothing new from step 7 and the notebook appendix.

What the chart says:

  • Only the fixed rule is far above the popularity line at small k. At k = 20 the fixed rule scores 82.1 percent, the plain rule 49.1 and the most-popular rule 44.0.
  • The plain rule needs a very large neighbourhood. Its best k is 480, out of 4,000 customers. Switch to "Neighbours with nothing new": even at k = 480, 58.9 percent of the plain rule's neighbours have nothing to offer. The rule works at that size only because those neighbours vote for nothing, so the rest decide the suggestion.
  • A fairly large k suits both rules. Each customer uses only two or three add-ons, so one neighbour says little about what this customer lacks. A vote among many neighbours gives a steadier score.

Step 9: test once

best_k_naive = max(results, key=lambda r: r[1])[0]
best_k = max(results, key=lambda r: r[2])[0]
print(f"plain KNN, k = {best_k_naive}: test hit rate, top 3: {hit_rate(lambda u: knn_naive(u, best_k_naive), test):.3f}")
print(f"fixed KNN, k = {best_k}: test hit rate, top 3: {hit_rate(lambda u: knn(u, best_k), test):.3f}")
plain KNN, k = 480: test hit rate, top 3: 0.852
fixed KNN, k = 160: test hit rate, top 3: 0.853

Each rule goes to the test half at its own best k: 480 for the plain rule, 160 for the fixed one. For the fixed rule, three values of k tie at 0.846 after rounding, and max keeps the first, 160. On the 1,711 test customers, which played no part in choosing k, the two rules are level: the hidden add-on is among the first three suggestions 85.2 and 85.3 percent of the time. The fixed rule's 85.3 is close to the 84.6 percent the tuning customers gave at the same k, so the choice of k did not just fit the tuning half.

So the fix does not make KNN more accurate at its best. What it changes is how many neighbours a good suggestion needs. On the tuning half, the fixed rule is within a few points of its best with 20 or 40 neighbours, while the plain rule needs several hundred. A short list of customers who really are alike is easier to show to a person as the reason for a suggestion, which step 11 does.

Step 10: item-based KNN

There is a second way to use neighbours. Instead of finding similar customers, find similar add-ons: two add-ons are alike when the same customers use them. Then suggest the add-ons most alike to the ones a customer already uses. This is the "customers who use X also use Y" you see on shopping sites. The name comes from recommender jargon, where products are "items" and customers are "users": item-based KNN finds neighbours among the add-ons, while user-based KNN, the kind in steps 6 to 9, finds them among the customers.

I = jaccard(H.T)                    # add-on x add-on: how often two add-ons go together
np.fill_diagonal(I, 0)
 
def knn_items(u):
    score = I[:, H[u] == 1].sum(axis=1)       # how close each add-on is to the ones they use
    score[H[u] == 1] = -1
    return rank(score)
 
print(f"item-based KNN, top 3: {hit_rate(knn_items, test):.3f}")
pairs = pd.DataFrame(I, index=ADDONS, columns=ADDONS)
pairs["payments"].sort_values(ascending=False, kind="stable").head(4).round(3)
item-based KNN, top 3: 0.856
 
accounting_sync        0.178
ecommerce_connector    0.125
audit_log              0.123
e_signature            0.092
Name: payments, dtype: float64

jaccard(H.T) uses the same similarity on the transposed table, so the rows are add-ons instead of customers. The result is a 12 × 12 table. Item-based KNN finds the hidden add-on 85.6 percent of the time, level with the customer-based version.

The last lines read the table for one add-on. Customers who use payments are most often also using accounting sync, with a similarity of 0.178. That pairing is exactly what a product marketer can act on.

Customers who use one add-on also use…
Try it
CRMAcctShopPayHelpChatSSOAuditRptsAPIDWHSignCRMAcctShopPayHelpChatSSOAuditRptsAPIDWHSign
Hover or tap a square: brighter means the two add-ons are more often used by the same customers.
Similarity = customers using both ÷ customers using either. Strongest pairs: API access + Warehouse export (0.223), CRM sync + Team chat (0.190), Accounting sync + Payments (0.178).
Jaccard similarity between every pair of add-ons, from the usage the model could see (one add-on hidden per tested customer). Real output from step 10.

The strongest pairs in the whole table, from the notebook appendix, are API access with warehouse export (0.223), CRM sync with team chat (0.190) and accounting sync with payments (0.178). They describe three kinds of customer without anyone having labelled them: data teams, sales-led teams and finance teams.

Item-based KNN has practical advantages. The add-on table is small, 12 × 12, so it is cheap to store and to recompute, and its reasons are easy to say out loud. Customer-based KNN can do one thing it cannot: point to the actual customers behind a suggestion, which is what the next step does.

Step 11: explain a suggestion

u = test[0]
row = data.iloc[u]
print(row.customer_id, "|", row.industry, "|", row.plan, "|", row.employees, "employees")
print("uses:  ", [a for a, v in zip(ADDONS, H[u]) if v])
print("hidden:", ADDONS[hidden[u]])
 
lacks = H[u] == 0
sim = np.where(H[:, lacks].sum(axis=1) > 0, S[u], -1)
neighbours = np.argsort(-sim, kind="stable")[:best_k]
votes = pd.Series(H[neighbours].sum(axis=0), index=ADDONS)[lacks]
print(f"\nof its {best_k} nearest customers, how many use each add-on it lacks:")
print(votes.sort_values(ascending=False, kind="stable").head(5).to_string())
NC-00002 | Software | Growth | 2706 employees
uses:   ['payments', 'single_sign_on', 'advanced_reporting']
hidden: api_access
 
of its 160 nearest customers, how many use each add-on it lacks:
api_access          48
warehouse_export    39
accounting_sync     23
e_signature         23
crm_sync            22

The first test customer, NC-00002, is a Growth-plan software company that uses payments, single sign-on and advanced reporting. We hid API access. Of its 160 nearest customers among those that use something it lacks, 48 use API access and 39 use warehouse export, so the method's first suggestion is the add-on we hid.

This is the sentence an account manager can use: "Of the 160 companies most like yours that use an add-on you don't, 48 use API access, more than use any other add-on you lack." It is honest about the filter and does not claim that most of them use it. The neighbour list is also how you catch a bad model early. If the suggestion and its neighbours make no business sense, check the data before trusting the list.

Step 12: compare every method

A fair guide should tell you how the method does against the alternatives: the simple rules a team would use without any model, and another method from this series.

That other method is logistic regression, which predicts a yes-or-no outcome as a probability. Here it becomes 12 small models, one per add-on, each predicting whether a customer uses that add-on from the other 11. A customer's suggestions are the add-ons it lacks, in order of predicted probability. It learns from the same table H as KNN and is scored on the same test customers.

from sklearn.linear_model import LogisticRegression
 
P = np.zeros(H.shape)            # P[u, j]: the chance customer u uses add-on j, given the others it uses
for j in range(len(ADDONS)):
    others = np.delete(H, j, axis=1)
    P[:, j] = LogisticRegression(max_iter=1000).fit(others, H[:, j]).predict_proba(others)[:, 1]
 
def logistic(u):
    score = P[u].copy()
    score[H[u] == 1] = -1
    return rank(score)
 
print(f"logistic regression, top 3: {hit_rate(logistic, test):.3f}")
logistic regression, top 3: 0.842

Logistic regression finds the hidden add-on in the first three 84.2 percent of the time, close to KNN. It is the subject of part 3 of this series. Now every method side by side:

segment = data["industry"] + " / " + data["plan"]
 
def segment_popular(u):
    peers = segment.to_numpy() == segment[u]
    peers[u] = False
    score = H[peers].mean(axis=0)
    score[H[u] == 1] = -1
    return rank(score)
 
methods = {
    "Most popular overall": most_popular,
    "Most popular in their industry and plan": segment_popular,
    "Plain KNN (k = 10)": lambda u: knn_naive(u, 10),
    f"Plain KNN, tuned (k = {best_k_naive})": lambda u: knn_naive(u, best_k_naive),
    f"KNN, neighbours with something new (k = {best_k})": lambda u: knn(u, best_k),
    "Item-based KNN": knn_items,
    "Logistic regression, one per add-on": logistic,
}
pd.DataFrame({f"top_{n}": {name: round(hit_rate(f, test, n), 3) for name, f in methods.items()}
              for n in [1, 3]})
                                              top_1  top_3
Most popular overall                          0.197  0.441
Most popular in their industry and plan       0.308  0.535
Plain KNN (k = 10)                            0.210  0.468
Plain KNN, tuned (k = 480)                    0.559  0.852
KNN, neighbours with something new (k = 160)  0.558  0.853
Item-based KNN                                0.564  0.856
Logistic regression, one per add-on           0.544  0.842

Every method is judged on the same 1,711 test customers, with the same hidden add-ons. Slide the number of suggestions to see how the gap changes:

Seven ways to pick the next add-on, on the same test customers
Try it
3
Most popular overall44.1%Most popular in their industry and plan53.5%Plain KNN (k = 10)46.8%Plain KNN, tuned (k = 480)85.2%KNN, neighbours with something new (k = 160)85.3%Item-based KNN85.6%Logistic regression, one per add-on84.2%
With 3 suggestions, the best method is Item-based KNN at 85.6%. Hover a bar to read it.
Amber: simple rules. Grey: plain KNN, without the fix. Green: KNN with the fix. Indigo: item-based KNN. Blue: logistic regression.
The 1,711 test customers, one add-on hidden each. Real output from step 12.

Reading it as a marketer:

  • The segment rule is a real improvement on plain popularity, 53.5 percent against 44.1 in the first three. If you have no time for a model, use it.
  • The same plain KNN scores 46.8 or 85.2 percent, depending on whether it uses 10 neighbours or 480. A method's name is no guarantee; how its neighbours are chosen decides whether it works.
  • Every tuned method lands between 84.2 and 85.6 percent. With a single suggestion, they get it right 54.4 to 56.4 percent of the time, against 19.7 percent for the most popular add-on. The gaps between them are small, so treat these methods as level.
  • Choose on practical grounds. Item-based KNN is the lightest to run. Logistic regression gives each add-on a probability but no customers to point to. Customer-based KNN with the fix can name the customers behind each suggestion, and needs far fewer of them than the plain version.

Step 13: build the next-best add-on list

Now use everything we know, with nothing hidden, and pick the top suggestion for every customer:

S_all = jaccard(M)               # now use everything we know, nothing hidden
np.fill_diagonal(S_all, -1)
 
rows = []
for u in range(len(data)):
    if M[u].sum() == len(ADDONS):
        continue
    lacks = M[u] == 0
    sim = np.where(M[:, lacks].sum(axis=1) > 0, S_all[u], -1)
    neighbours = np.argsort(-sim, kind="stable")[:best_k]
    using = M[neighbours].sum(axis=0)
    using[~lacks] = -1
    top = rank(using)[0]
    rows.append((data.customer_id[u], data.industry[u], data.plan[u],
                 ", ".join(a for a, v in zip(ADDONS, M[u]) if v) or "none",
                 ADDONS[top], using[top], round(using[top] / best_k, 3)))
 
next_best = pd.DataFrame(rows, columns=["customer_id", "industry", "plan", "uses", "next_best",
                                        "lookalikes_using", "share_of_lookalikes"])
next_best = next_best.sort_values("share_of_lookalikes", ascending=False, kind="stable")
next_best.to_csv("next_best_addon.csv", index=False)
print(next_best["next_best"].value_counts().to_string())
print(f"most-popular rule: crm_sync first for {(M[:, ADDONS.index('crm_sync')] == 0).sum():,} customers")
next_best.drop_duplicates("uses").head(8)
next_best
e_signature            743
crm_sync               598
advanced_reporting     574
team_chat              374
help_desk              360
payments               322
single_sign_on         255
accounting_sync        238
audit_log              174
warehouse_export       152
api_access             129
ecommerce_connector     81
most-popular rule: crm_sync first for 2,693 customers
 
     customer_id               industry        plan                                                             uses         next_best  lookalikes_using  share_of_lookalikes
320     NC-00321               Software      Growth                       team_chat, advanced_reporting, e_signature          crm_sync               152                0.950
3031    NC-03032  Professional services      Growth  ecommerce_connector, team_chat, advanced_reporting, e_signature          crm_sync               152                0.950
2265    NC-02266               Software      Growth            help_desk, team_chat, advanced_reporting, e_signature          crm_sync               151                0.944
186     NC-00187               Software      Growth                   single_sign_on, advanced_reporting, api_access  warehouse_export               149                0.931
520     NC-00521               Software  Enterprise             single_sign_on, advanced_reporting, warehouse_export        api_access               149                0.931
862     NC-00863               Software      Growth            team_chat, audit_log, advanced_reporting, e_signature          crm_sync               148                0.925
1493    NC-01494              Education      Growth                                 single_sign_on, warehouse_export        api_access               146                0.912
3376    NC-03377               Software      Growth        help_desk, single_sign_on, advanced_reporting, api_access  warehouse_export               145                0.906

S_all is the similarity on the full table. For each customer, the code keeps the 160 nearest customers with something new to offer, counts how many of them use each add-on the customer lacks, and keeps the add-on with the most votes. lookalikes_using is that count, and share_of_lookalikes is the same as a share. The print after the counts shows, for comparison, how many customers the most-popular rule would send CRM sync first. The last line shows the most confident suggestion for each different combination of add-ons.

Two things to read in the output. First, the suggestions are spread across all 12 add-ons, from e-signature for 743 customers to the e-commerce connector for 81. The most-popular rule would have sent CRM sync first to every customer without it: 2,693 of the 4,000, about two in three. Second, the most confident rows come close to certainty: 152 of NC-00321's 160 lookalikes use CRM sync, and it does not.

The file next_best_addon.csv is what goes to the account managers and to the email tool.

Using the recommendations

A list only matters if someone acts on it. Ways Northpine could use this one:

  • Account check-ins. Give each account manager their customers' top suggestion with the count behind it. "Many companies set up like yours use X", backed by that count, is a better opener than a product pitch.
  • Cross-sell emails. Replace the single monthly cross-sell email with one email per add-on, each sent only to the customers for whom it is the top suggestion.
  • Bundles. The strongest item pairs, such as API access with warehouse export, are candidates for a bundle or a joint trial.
  • Refresh monthly. Every new add-on a customer turns on changes their neighbours. Recompute the list each month.

Then measure it properly. The hit rate in this guide shows that KNN predicts what customers adopt. It does not show that suggesting it causes extra sales: many of those customers would have found the add-on on their own. To measure what the suggestions add, hold back a random share of customers, send the suggestions to the rest, and compare add-on purchases between the two groups over the next quarter. That is an incrementality test, explained in Incrementality Meaning, With a Marketing Example.

Mistakes to avoid

  • Taking the nearest neighbours at face value. With sparse usage, the most similar customers often use a subset of what this customer uses and have nothing to suggest. With 10 neighbours, plain KNN barely beat the popularity rule for exactly this reason, and it needed 480 to catch up. Keep only neighbours that can suggest something, and decide how ties are broken: with sparse votes, the tie rule quietly picks many suggestions.
  • Counting shared absences as similarity. Ordinary distance treats "neither uses it" as agreement. With 12 add-ons and two or three in use, that drowns the signal. Use Jaccard or cosine similarity for yes-or-no usage.
  • Testing on customers you cannot test. A customer with one add-on has nothing left once you hide it. Count them separately and say how many there are, as step 4 does.
  • Tuning and reporting on the same customers. Choose k on one half and report on the other, or the score you show flatters the model.
  • Skipping the simple baselines. Without the popularity and segment rules in the comparison, the 46.8 percent of plain KNN with 10 neighbours might have looked like a working model.
  • Confusing prediction with persuasion. A high hit rate means the model knows what customers like this tend to use. Only a holdout test shows whether suggesting it changes anything.
  • Suggesting what the customer cannot buy. If an add-on needs a higher plan or a system the customer does not have, filter it out before the list goes to a person.

KNN and the rest of the series

For when KNN is the right choice and when it is not, see How KNN Works. Recommendations are one of the jobs it does best: there is no outcome column to model, the logic is easy to explain, and new usage changes the suggestions at once without retraining.

MethodWhat it gives youStrengthWatch out for
KNN (this case)Suggestions from similar customersExplains itself with real customersChoosing neighbours with care, slow at large scale
Linear regressionHow much one number moves anotherSimple, readable effectsMistaking correlation for cause
Logistic regressionA probability for a yes or no outcomeAccurate, clear weights per columnStraight-line assumptions
Decision treeRules that split customers into groupsRules anyone can readUnstable, overfits if allowed
XGBoostStrong predictions from many treesUsually the most accurateNeeds extra tools to explain

Download the data and the notebook

All three files are free to use. The notebook runs every step of this guide in order and already contains the outputs shown above, so you can compare your results line by line.

To run it: install Python, then run pip install pandas numpy scikit-learn jupyter, put the files in one folder, and open the notebook with Jupyter. Step 13 writes your own next_best_addon.csv.

Want this on your own data?

If you would like next-best-product suggestions built from your own customer and usage data, or want to know whether your data is ready for it, get in touch and we can talk it through on a short call.