← Blog/KNN for Marketing: Matched Control Groups for an Event, Step by Step
Machine LearningKNNPythonIncrementalityMarketing Analytics
Machine Learning · 23 min read

KNN for Marketing: Matched Control Groups for an Event, Step by Step

Use k-nearest neighbours to build a matched control group and measure what a sales event really added, step by step in Python, with real code and charts.

· Martin Guzman

This is a business case for k-nearest neighbours (KNN): we use it to measure what a sales event actually added, by comparing each company that came with the companies that look most like it but did not. A naive comparison says the event lifted the rate of opening a sales opportunity by 18.0 percentage points. Bias-corrected matching, the estimate this case recommends, puts it at 5.3 points, with a 95 percent interval of +1.4 to +9.3. The main matched estimates run from 5.3 to 8.5.

KNN usually scores something new by the company it keeps. Here we use only its first half, finding the nearest neighbours, to build a fair comparison group. For the math behind the distances and the scaling, 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. Because the data is invented, we also know the right answer, which almost never happens with real data: the event adds 5 percentage points. That lets us check each method against the truth.

The application: did the roadshow work?

Northpine Software, the made-up company whose data we use throughout this series, ran a roadshow: a half-day event in several cities for business software buyers. Sales chose whom to invite. They did what any sales team would do, and invited the accounts that looked most promising in the CRM: bigger companies, accounts that had been on the website a lot, accounts that had looked at pricing, and accounts where someone already had a named contact.

Of 3,000 accounts in the territory, 553 came. Ninety days later, finance asks the question every event gets asked: was it worth it? Did the event create sales opportunities, or did sales just invite the accounts that were going to open one anyway?

What teams usually do

Without a method for this, teams report one of these:

  • Attendees against everyone else. 31.1 percent of attendees opened an opportunity within 90 days, against 13.1 percent of accounts that did not come. The event report says "+18 points".
  • Attendees against everyone else, within size bands. Split accounts into big and small, compare within each, and average. A step in the right direction, but it fixes one difference out of several.
  • Before and after. Compare the quarter with the event to the quarter before. This mixes the event with everything else that changed that quarter.

The first is the most common, and it has a basic flaw: the attendees were not a random group. Sales picked them because they looked likely to buy. Part of the 18 points is the event, and part is just who was invited.

What KNN changes

KNN finds, for each attendee, the non-attendees that looked most like it before the event, on every column sales could see: size, industry, website visits, pricing page views, downloads and whether there was a named contact. Those lookalikes become the comparison group. Step 10 shows a real one: an attendee, a software company of 90 people with six website visits and a named contact, is compared with five software companies of 64 to 99 people, with four to six visits and a named contact, that stayed home.

On the same 3,000 accounts (step 12 shows the code):

How the event is measuredEffect on opening an opportunityExtra opportunities credited to the event
Attendees against everyone else+18.0 points100
Within two size bands+16.2 points89
KNN matching, five matches per attendee+8.5 points47
KNN matching, bias-corrected+5.3 points29
The truth built into this invented data+5 points

The naive report credits the event with more than three times as many opportunities as it created. For a program that costs real money per city, that is the difference between "run it everywhere" and "run it where it pays".

What the teams receive

An event report with one number and its range, and the matched pairs behind it:

  • The effect: "+5.3 points, 95 percent interval +1.4 to +9.3", from bias-corrected matching (step 12). Plain matching with five matches per attendee says +8.5 (+4.6 to +12.4).
  • The balance table for the match you report: how close the comparison group is to the attendees, column by column, and where it still falls short (step 8).
  • The pairs file: each attendee and its five matched non-attendees, so anyone can open the CRM and check that the matches make sense.
TeamDecisionWhat they do with it
Field marketingRun the roadshow again, and whereCompare cost per extra opportunity with other programs, using the bias-corrected figure, not the naive one
Sales leadershipWho to invite next timeLook at which kinds of attendees gained most against their matches
FinanceEvent budgetUse the interval, not just the point estimate, when planning
Marketing operationsAudit the methodSpot-check matches in the pairs file

Other places the same idea works

Anywhere a program reached a hand-picked group and nobody kept a random holdout:

  • Customer success outreach. Accounts that got a check-in call against similar accounts that did not.
  • Loyalty or beta programs. Members against similar non-members, matched on behaviour before they joined.
  • Account-based campaigns. Target accounts against similar accounts left off the list.
  • Sales training. Reps who took a course against similar reps who did not, matched on territory and past results.

KNN in one minute

To score something, KNN finds the known examples nearest to it on every column at once, after putting the columns on the same scale. Matching uses exactly that search, and stops there: instead of letting the neighbours vote, it uses them as the comparison group. Each attendee gets the non-attendees nearest to it, and the event's effect is the average difference in outcomes between attendees and their matches.

Two things carry over from How KNN Works: columns must be scaled, or "nearest" just means "similar headcount", and every column you add counts in the distance. One thing is new: we can check whether the matching worked, by measuring how similar the two groups ended up.

Press play below. Each indigo attendee gets joined to its five nearest non-attendees, and the comparison group in the bars changes from "everyone who did not come" to "the matched controls". The matches are found on all eleven columns but drawn on two, so some lines look longer than they are.

Find each attendee its lookalikes, then compare
Try it
101001,0000510152025employees (log scale)engagement before the event
came to the eventmatched non-attendee
other non-attendees (sample)
0 of 40 sampled attendees matched. Hover or tap a dot to read it.
Attendees31.1% opened an opportunity
Everyone who did not come13.1% opened an opportunity
Naive gap+18.0 points
Attendees were bigger and keener before the event, so part of this gap would have happened anyway.
A sample of 40 of the 553 attendees. Matches are found on all eleven columns and drawn on two; the bars use all attendees.

The data: Northpine's roadshow

This case uses one table, northpine_event.csv: the 3,000 accounts in the roadshow's territory, what the CRM showed about each one before the event, whether it came, and whether it opened an opportunity in the 90 days after. The first five rows:

account_idindustryemployeesweb visitspricing page visitsdownloadsnamed contactattendedopportunity
NE-00001Professional services50600100
NE-00002Professional services30100000
NE-00003Retail33610101
NE-00004Professional services47000000
NE-00005Education342501000
ColumnWhat it is
industryThe company's sector, one of six
employeesCompany headcount
web_visits_beforeWebsite visits in the 90 days before the event
pricing_page_visits_beforePricing page visits in the same period
content_downloads_beforeGuides and reports downloaded in the same period
has_named_contactSales had a named contact at the account (1) or not (0)
attended_eventThe account came to the roadshow (1) or not (0)
opportunity_90dSales opened an opportunity within 90 days after the event (1) or not (0)

Two rules matter more than anything else in this case.

Match only on what was known before the event. Every column we match on describes the account before anyone was invited. If you matched on something the event could change, such as website visits in the month after it, you would be matching away part of the effect you are trying to measure.

Matching can only fix what is in the table. Sales invited accounts based on what they could see in the CRM, and every one of those columns is here. If they had also invited accounts because a rep "had a good feeling", and that feeling predicted buying, no amount of matching on these columns would remove it. This assumption cannot be tested from the data. It has to be argued from how the invitations were really made, which is why the first question to ask is always "how did people end up at the event?"

Because the data is invented, we know the rule that generated it, from the dataset script in the site's repository: the event raises each account's chance of opening an opportunity by exactly 5 percentage points. Real data never tells you this; here it lets us grade each method.

Step by step in Python

The code uses pandas and scikit-learn, both 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
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
 
events = pd.read_csv("northpine_event.csv")
print(events.shape)
events.head()
(3000, 9)

Three thousand accounts, nine columns.

Step 2: the naive comparison

rates = events.groupby("attended_event")["opportunity_90d"].agg(accounts="count", rate="mean")
naive_gap = rates.loc[1, "rate"] - rates.loc[0, "rate"]
print(rates.round(3))
print(f"naive gap: {naive_gap * 100:+.1f} percentage points")
                accounts   rate
attended_event
0                   2447  0.131
1                    553  0.311
naive gap: +18.0 percentage points

This is the number in most event reports. Keep it in mind as the figure every later step should be compared with.

Step 3: how attendees differed before the event

before = ["employees", "web_visits_before", "pricing_page_visits_before",
          "content_downloads_before", "has_named_contact"]
events.groupby("attended_event")[before].median().T
attended_event                  0      1
employees                   118.0  271.0
web_visits_before             3.0    5.0
pricing_page_visits_before    0.0    1.0
content_downloads_before      0.0    1.0
has_named_contact             0.0    1.0

The typical attendee had more than twice the headcount of the typical non-attendee, more website visits, had looked at pricing, and had a named contact. Every one of those things makes an account more likely to open an opportunity, event or no event. That is the problem in one table: the two groups were different before anyone got on a plane.

Switch between the columns below. Against everyone who did not come, the attendees' shapes sit to the right. Switch the comparison to the matched controls, the five matches per attendee used from step 8 on, and the shapes move much closer. They do not line up at the top end: the largest and most engaged attendees have few lookalikes among the accounts that stayed home, so their matches are smaller and less engaged. Steps 7 and 8 measure that gap.

Attendees were different before the event
Try it
0%5%10%15%51332791995001,2563,155employees (log bins, lower edge)
attendeeseveryone who did not come
Hover or tap a pair of bars. Switch the comparison group to see how much closer the shapes get.
All 3,000 accounts. Matched controls are each attendee’s five nearest non-attendees, counted once per match.

Step 4: put the columns on one scale

X = events[before].copy()
X["employees"] = np.log10(X["employees"])
X = X.join(pd.get_dummies(events["industry"], prefix="ind", dtype=float))
Z = pd.DataFrame(StandardScaler().fit_transform(X), columns=X.columns, index=X.index)
 
treated = events["attended_event"] == 1
y = events["opportunity_90d"]
print(f"{treated.sum()} attendees, {(~treated).sum():,} possible controls, {X.shape[1]} columns")
553 attendees, 2,447 possible controls, 11 columns

The same preparation as any KNN model:

  • Headcount goes in as its logarithm, because the gap between 50 and 150 employees matters more than the gap between 4,000 and 4,100.
  • Industry becomes six yes-or-no columns, one per sector, because distance needs numbers.
  • StandardScaler puts every column in standard deviations, so a difference of one standard deviation counts the same on every column. Without it, headcount would decide every match.

X keeps the columns in their natural units for the balance checks; Z is the scaled version used to measure distance. In this case it is fine to scale on all accounts at once: we are not predicting anything for new accounts, so there is nothing to leak.

Step 5: measure the imbalance

sd = np.sqrt((X[treated].var() + X[~treated].var()) / 2)
 
def smd(controls):
    """Gap between attendees and a control group, in standard deviations."""
    return (X[treated].mean() - controls.mean()) / sd
 
balance = pd.DataFrame({"before": smd(X[~treated])})
balance.round(2)
                            before
employees                     0.75
web_visits_before             0.55
pricing_page_visits_before    0.47
content_downloads_before      0.42
has_named_contact             0.65
ind_Education                -0.12
ind_Healthcare               -0.00
ind_Manufacturing             0.07
ind_Professional services    -0.02
ind_Retail                   -0.01
ind_Software                  0.06

The standardized mean difference is the gap in averages between two groups, divided by the column's standard deviation, so every column is on the same footing. A common rule of thumb is that below 0.1 the groups are balanced on that column. Before matching, attendees sit 0.75 standard deviations above non-attendees on headcount (in logs) and 0.65 on having a named contact. Industry differs a little: Education accounts were invited less.

Step 6: match each attendee to its nearest non-attendee

nn = NearestNeighbors(n_neighbors=1).fit(Z[~treated])
distance, index = nn.kneighbors(Z[treated])
 
control_ids = Z[~treated].index[index[:, 0]]
matched_gap = y[treated].mean() - y[control_ids].mean()
print(f"distinct controls used: {len(set(control_ids))} for {treated.sum()} attendees")
print(f"matched gap: {matched_gap * 100:+.1f} percentage points")
distinct controls used: 426 for 553 attendees
matched gap: +8.1 percentage points

NearestNeighbors is the search half of KNN without the vote. We fit it on the non-attendees only, then ask, for each attendee, which non-attendee is closest. The matched gap is the attendees' opportunity rate minus their matches' rate.

Two details:

  • Matching is with replacement. 553 attendees used 426 distinct controls, so some non-attendees are the best match for more than one attendee. That keeps each match as close as possible. Without replacement, the last attendees to be matched would get whoever was left.
  • The gap more than halved, from +18.0 to +8.1 points. More than half of what the naive report credited to the event was really the difference in who was invited.

Step 7: check the balance after matching

balance["after"] = smd(X.loc[control_ids])
balance.round(2)
                            before  after
employees                     0.75   0.17
web_visits_before             0.55   0.15
pricing_page_visits_before    0.47   0.09
content_downloads_before      0.42   0.06
has_named_contact             0.65   0.03
ind_Education                -0.12   0.00
ind_Healthcare               -0.00   0.00
ind_Manufacturing             0.07   0.00
ind_Professional services    -0.02   0.00
ind_Retail                   -0.01  -0.00
ind_Software                  0.06   0.00

This step is what makes matching more trustworthy than most alternatives: you can see whether it worked. Industry and named contact are now matched almost exactly. Pricing views and downloads are under 0.1.

Headcount, at 0.17, and web visits, at 0.15, are not. Where attendees are most unlike the accounts that stayed home, even the nearest non-attendee is some distance away, and on average the matches are still a little smaller and less engaged. Both of those make an account less likely to open an opportunity, so the leftover gap pushes the estimate up. Steps 8 and 12 deal with it.

Step 8: choose the matching settings

Two settings matter: k, how many matches each attendee gets, and the caliper, a maximum distance beyond which a match does not count.

y_controls = y[~treated].to_numpy()
X_controls = X[~treated].to_numpy()
 
def match(k, caliper=np.inf):
    dist, idx = NearestNeighbors(n_neighbors=k).fit(Z[~treated]).kneighbors(Z[treated])
    close = dist <= caliper                       # matches near enough to count
    kept = close.any(axis=1)                      # attendees with at least one
    w = close[kept] / close[kept].sum(axis=1, keepdims=True)
    control_rate = (y_controls[idx[kept]] * w).sum(axis=1)
    diffs = y[treated].to_numpy()[kept] - control_rate
    control_means = (X_controls[idx[kept]] * w[:, :, None]).sum(axis=1).mean(axis=0)
    worst = np.abs((X[treated][kept].mean() - control_means) / sd).max()
    return {"k": k, "caliper": caliper, "attendees_kept": int(kept.sum()),
            "gap": diffs.mean(), "worst_smd": worst, "diffs": diffs}
 
settings = [match(k) for k in [1, 3, 5, 10, 20, 50]] + [match(5, c) for c in [1.0, 0.5]]
pd.DataFrame(settings).drop(columns="diffs").round(3)
    k  caliper  attendees_kept    gap  worst_smd
0   1      inf             553  0.081      0.170
1   3      inf             553  0.072      0.228
2   5      inf             553  0.085      0.251
3  10      inf             553  0.083      0.278
4  20      inf             553  0.095      0.319
5  50      inf             553  0.111      0.393
6   5      1.0             391  0.044      0.156
7   5      0.5             278  0.008      0.036

For each attendee, match takes its k nearest non-attendees, drops any farther than the caliper, and averages the rest. worst_smd is the largest remaining imbalance across the eleven columns. Reading the table:

  • More matches, worse balance. With 50 matches per attendee, the comparison group drifts back towards "everyone else": the worst imbalance reaches 0.39 and the gap climbs to +11.1 points. It is the same trade-off as choosing k in any KNN model. A few matches are close but noisy; many matches are steady but less alike.
  • k = 1 to 10 agree. Between +7.2 and +8.5 points. Five matches is a common choice: each attendee is compared with an average, not a single account, so the estimate is steadier.
  • A caliper improves balance but changes the question. With a caliper of 0.5 standard deviations, the worst imbalance falls to 0.04, but only 278 of the 553 attendees have a match that close. The ones dropped are the attendees least like anyone who stayed home. The +0.8 points that remains describes the half of the attendees that have close lookalikes, not the event as a whole, and its interval is wide.
How the matching settings change the answer
Try it
−5.0+0.0+5.0+10.0+15.0+20.0true +5naivek = 1k = 3k = 5k = 10k = 20k = 50k = 5, caliper 1.0k = 5, caliper 0.5estimated effect on opening an opportunity, percentage points
Hover or tap a row to see how many attendees it keeps and how well it balances them.
Matched gap with a 95% bootstrap interval for each setting in step 8. The caliper is a distance in standard deviations.

There is no setting that is simply right. Hover each row above: the trade is always between how alike the groups are and how many attendees the answer still covers. Report the setting you chose and show that the main conclusion does not hinge on it.

The rest of this case uses five matches per attendee, without a caliper, so every attendee counts. That is the match we report, so its balance table is the one to check:

dist5, idx5 = NearestNeighbors(n_neighbors=5).fit(Z[~treated]).kneighbors(Z[treated])
balance["after_k5"] = smd(X[~treated].iloc[idx5.ravel()])
balance.round(2)
                            before  after  after_k5
employees                     0.75   0.17      0.25
web_visits_before             0.55   0.15      0.19
pricing_page_visits_before    0.47   0.09      0.18
content_downloads_before      0.42   0.06      0.15
has_named_contact             0.65   0.03      0.03
ind_Education                -0.12   0.00      0.00
ind_Healthcare               -0.00   0.00     -0.00
ind_Manufacturing             0.07   0.00      0.00
ind_Professional services    -0.02   0.00      0.00
ind_Retail                   -0.01  -0.00     -0.01
ind_Software                  0.06   0.00      0.00

Five matches balance worse than one. Industry and named contact are still matched, but four columns are now above the 0.1 bar: headcount at 0.25, web visits at 0.19, pricing views at 0.18 and downloads at 0.15. The second to fifth matches are farther away than the first, and for the biggest, most engaged attendees they are smaller and less engaged accounts. So the plain k = 5 estimate in step 9 still carries part of the selection, and leans high. That is why step 12 adds a bias correction, and why the corrected figure is the one to report.

Switch the chart below between the three views. "After, k = 5" is the match the rest of this case uses.

Balance check: how far apart are the groups on each column?
Try it
-0.20.00.20.40.60.8Employees (log)Web visitsPricing page visitsContent downloadsNamed contactIndustry: EducationIndustry: HealthcareIndustry: ManufacturingIndustry: Prof. servicesIndustry: RetailIndustry: Softwareattendees minus comparison group, in standard deviations
Largest gap after matching, k = 5: 0.25 SD. The green band is within 0.1 SD, the usual bar for "balanced". Hollow dots are before matching.
Standardized mean differences, using the standard deviation before matching. Real output from steps 5, 7 and 8; the guide reports the k = 5 match.

Step 9: how sure can we be?

best = match(5)
rng = np.random.default_rng(42)
n = len(best["diffs"])
boot = np.array([best["diffs"][rng.integers(0, n, n)].mean() for _ in range(2000)])
low, high = np.percentile(boot, [2.5, 97.5])
print(f"matched gap (k=5): {best['gap'] * 100:+.1f} points, "
      f"95% interval {low * 100:+.1f} to {high * 100:+.1f}")
matched gap (k=5): +8.5 points, 95% interval +4.6 to +12.4

The bootstrap, which re-runs the estimate on random resamples of the attendees, shows how much the answer could move by chance. We resample the 553 attendee-against-matches differences 2,000 times and keep the middle 95 percent. The interval runs from +4.6 to +12.4 points. It excludes zero, so the event did something. It also excludes the naive +18.0: even the top of the range falls well short of it, so not all of the naive gap was the event. And because this match is still unbalanced on four columns (step 8), this estimate leans high; step 12 corrects it.

How much the estimate could move by chance
Try it
050100150200+0.0+5.0+10.0+15.0+20.0true +5estimate +8.5matched gap in each re-estimate, percentage pointsre-estimates
Green bars hold the middle 95%: +4.6 to +12.4 points. Hover a bar.
2,000 bootstrap re-estimates of the k = 5 matched gap, resampling attendees. Real output from step 9.

The true effect of 5 points sits just inside the interval: 88 of the 2,000 re-estimates are at or below it. This simple bootstrap treats each attendee's comparison as independent, which is not quite true when controls are reused, so the real uncertainty is a little wider than shown.

Step 10: look at one match

one = 0                                            # the first attendee in the file
pair = pd.concat([events[treated].iloc[[one]],
                  events[~treated].iloc[idx5[one]]])
show = ["account_id", "industry", "employees", "web_visits_before",
        "pricing_page_visits_before", "has_named_contact", "attended_event", "opportunity_90d"]
pair[show].assign(distance=np.r_[0, dist5[one]].round(2))
account_idindustryemployeesweb visitspricing page visitsnamed contactattendedopportunitydistance
NE-00006Software90601100.00
NE-01014Software71601000.21
NE-01593Software64601000.31
NE-00235Software92501010.34
NE-01655Software82401000.68
NE-00770Software99401000.68

The first row is the attendee: a software company of 90 people with six website visits and a named contact. Its five matches are software companies of 64 to 99 people, with four to six visits and a named contact, that did not come. One of the five opened an opportunity, a rate of 20 percent; the attendee did not, so its own difference is −20 points. One attendee proves nothing. The average over 553 of them is the estimate.

This table is what makes the method easy to defend. Anyone in sales can look at it and agree that these are fair comparisons, which is not true of "everyone who did not come".

Step 11: save the matched pairs

pairs = pd.DataFrame({
    "attendee": np.repeat(events.loc[treated, "account_id"].to_numpy(), 5),
    "control": events.loc[~treated, "account_id"].to_numpy()[idx5.ravel()],
    "distance": dist5.ravel().round(3),
})
pairs.to_csv("event_matched_controls.csv", index=False)
print(pairs.shape)
pairs.head(6)
(2765, 3)
 
   attendee   control  distance
0  NE-00006  NE-01014     0.213
1  NE-00006  NE-01593     0.306
2  NE-00006  NE-00235     0.339
3  NE-00006  NE-01655     0.681
4  NE-00006  NE-00770     0.682
5  NE-00011  NE-02455     0.011

One row per attendee and match: 553 attendees with five matches each, 2,765 rows. This is the audit trail. Sort it by distance, descending, to find the attendees with the weakest matches; those are the accounts where the comparison is least reliable.

Step 12: compare with other methods

design = X.assign(attended=treated.astype(float))
adjusted = LinearRegression().fit(design, y).coef_[-1]
 
def strata_gap():
    big = events["employees"] >= 250
    gaps = [y[treated & g].mean() - y[~treated & g].mean() for g in (big, ~big)]
    weights = [(treated & big).sum(), (treated & ~big).sum()]
    return np.average(gaps, weights=weights)
 
# bias-corrected matching: subtract what a regression on the controls
# expects for each account, so small leftover differences in the matches cancel
mu0 = LinearRegression().fit(X[~treated], y[~treated])
resid_controls = y_controls - mu0.predict(X[~treated])
corrected = (y[treated] - mu0.predict(X[treated])).to_numpy() - resid_controls[idx5].mean(axis=1)
 
estimates = pd.Series({
    "Naive: attendees vs everyone else": naive_gap,
    "Rule: compare within size bands": strata_gap(),
    "Regression adjustment": adjusted,
    "KNN matching, k=1": matched_gap,
    "KNN matching, k=5": best["gap"],
    "KNN matching, k=5, bias-corrected": corrected.mean(),
})
pd.DataFrame({"gap_in_points": (estimates * 100).round(1),
              "extra_opportunities": (estimates * treated.sum()).round(0).astype(int)})
                                   gap_in_points  extra_opportunities
Naive: attendees vs everyone else           18.0                  100
Rule: compare within size bands             16.2                   89
Regression adjustment                        3.8                   21
KNN matching, k=1                            8.1                   45
KNN matching, k=5                            8.5                   47
KNN matching, k=5, bias-corrected            5.3                   29

Each method answers the same question on the same 3,000 accounts. extra_opportunities multiplies the gap by the 553 attendees, the number of opportunities each method credits to the event.

  • Regression adjustment fits one linear model of the outcome on all eleven columns plus attendance, and reads off the attendance coefficient. It says +3.8 points. It relies on that straight-line model being right, everywhere, including for the large accounts where there are few non-attendees to learn from.
  • Bias-corrected matching combines the two. It matches first, then uses a regression fitted on the non-attendees to remove what is left of the size and engagement gap in the k = 5 balance table from step 8. It says +5.3 points. This combination is a common recommendation, because each part covers the other's weakness: matching makes the groups alike, and the regression only has to tidy up small differences.
  • The size-band rule barely helps, at +16.2, because size is only one of the reasons accounts were invited.

With the intervals from the notebook's appendix:

Six ways to measure the same event
Try it
−5.0+0.0+5.0+10.0+15.0+20.0true +5naiveNaive comparisonWithin size bandsRegression adjustmentKNN matching, k=1KNN matching, k=5KNN matching, bias-correctedestimated effect on opening an opportunity, percentage points
Hover or tap a row. Lines are 95% bootstrap intervals; the dotted white line is the true effect built into the data.
All 3,000 accounts. Intervals are 95% bootstrap intervals, built two ways: the naive and regression intervals resample all accounts, while the matching intervals resample attendees with their matches held fixed, which ignores reused controls and makes them narrower than they should be. The true effect is known only because the data is invented.

The truth in this invented data is +5 points. Bias-corrected matching lands closest, at +5.3, with an interval of +1.4 to +9.3. Plain matching, at +8.5, overstates it by about 3.5 points because of the leftover imbalance, and regression adjustment comes in a little low, with an interval that reaches just below zero. Every adjusted method is far closer than the naive report's +18.0. With real data you would not know the truth. You would report the bias-corrected estimate with its interval, and show that plain matching and regression tell a similar story.

The intervals are not all built the same way. The naive and regression intervals resample all 3,000 accounts. The matching intervals resample the attendees with their matches held fixed, which ignores that some controls are reused, so they are narrower than they should be.

Using the result

What Northpine does with the answer:

  • Report the bias-corrected figure. The roadshow created about 29 extra opportunities by the bias-corrected estimate (95 percent interval 8 to 51), not the 100 the naive report claimed. Divide the event's cost by the extra opportunities, not by all the attendees' opportunities, and compare that with what other programs cost per extra opportunity.
  • Show the balance table with it, for the match you report. A number without the balance check is just another claim. With it, anyone can see how close the comparison was on every column sales used to invite, and where the correction had work to do.
  • Look at who gained. With the pairs file, compare attendees and their matches within groups, for example by industry or size, to see where the event added most. Treat those splits with care: each group has fewer attendees, so the intervals widen quickly.
  • Plan a holdout next time. Matching is the best you can do after the fact. Before the next roadshow, take the list sales wants to invite, randomly hold back one in five, and invite the rest. Comparing the invited with the held-back accounts measures the effect without any of the assumptions above. Incrementality Meaning, With a Marketing Example explains how.

Mistakes to avoid

  • Matching on what happened after the event. Website visits or meetings in the weeks after the roadshow are partly caused by it. Matching on them erases part of the effect. Use only what was known before anyone was invited.
  • Skipping the balance check. Matching always produces a number. Only the balance table tells you whether the groups are comparable. If the worst column is still well above 0.1, the estimate still carries part of the selection.
  • Forgetting to scale. Without StandardScaler, headcount dominates every distance and the matches ignore engagement and contacts, which are exactly the things sales used to choose.
  • Believing matching removes all bias. It only balances the columns you have. If invitations depended on something not in the CRM, such as a rep's private judgement, the estimate is still biased, and the data cannot tell you by how much.
  • Using too many matches. With 50 matches per attendee, the comparison group drifts back towards "everyone else" and the estimate drifts towards the naive answer. Check how the answer moves as k grows.
  • Applying a tight caliper without saying so. Dropping attendees without close matches improves balance, but the answer then describes only the attendees that remain. Report how many were kept and who they are.
  • Treating the interval as exact. The simple bootstrap here ignores the reuse of controls. Read the interval as a guide to the uncertainty, not a guarantee.

KNN matching and the other options

MethodWhat it gives youStrengthWatch out for
Randomized holdoutThe effect, with no assumptions about who was chosenThe gold standardHas to be planned before the event
KNN matching (this case)A comparison group that looks like the attendeesEasy to check and explain, one pair at a timeOnly balances measured columns; leftover gaps in sparse regions
Regression adjustmentThe effect, holding the other columns fixedUses all the dataDepends on the model's shape being right
Matching plus regressionMatching, with leftover gaps correctedUsually the most reliable after the factOne more step to explain
Before and afterA change over timeSimpleMixes the event with everything else that changed

For how KNN works in general, including scaling and choosing k, see How KNN Works. For the wider picture of measuring what marketing caused, see Causal Inference for Marketing Analysts.

Download the data and the notebook

Both files are free to use. The notebook runs every step of this case in order and already contains the outputs shown above.

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

Want this on your own data?

If you have an event, a campaign or a program that reached a hand-picked group and you want to know what it really added, get in touch. We can look at your CRM data together and see whether a matched comparison, or a holdout for next time, is the better route.