Introduction
Have you ever looked at your marketing report and thought: “Why did my conversions spike when I barely changed anything?” Or worse, you doubled your ad budget but sales barely moved. You’re not alone — according to a Nielsen study, nearly 60% of marketers admit they struggle to measure ROI across channels.
The culprit? Outdated last-click attribution. It loves giving all the glory to that final email or retargeting ad, while completely ignoring the heavy lifting done by your social media campaigns, blog content, or referral partners earlier in the journey.
That’s where smarter marketing attribution comes in. By using data science methods like Markov chains and Shapley values, we can see the entire journey instead of just the finish line. In this guide, I’ll walk you through a hands-on attribution project with real data — showing you exactly how to uncover what truly drives conversions, and how to stop wasting money on channels that don’t pull their weight.
👉 Quick tip: If you’re curious about how AI is reshaping campaign performance tracking, check out our post on AI in Digital Marketing
👉 Quick win: If you want to automate reports and workflow alerts, try Custom GPT — a flexible AI assistant you can tailor to pull campaign summaries and attribution snapshots
Key Takeaways
-
Stop trusting last-click reports → They hide the real story and undervalue nurturing channels like blogs and social.
-
Use Markov models for budget shifts → They show incremental impact and reveal which channels move people forward.
-
Validate with Shapley values → This ensures fairness and helps you present defendable results to leadership.
-
Visualize your attribution → Bar charts and Sankey flows make complex journeys easy for any stakeholder to grasp.
-
Invest in supportive channels → Social and referral might not “close” conversions, but cutting them could break the funnel.
-
Automate where possible → Save time by using workflow tools and attribution-ready platforms instead of stitching data manually.
What is Marketing Attribution?
Think about the last time you checked your campaign report. Did you notice how the final click — maybe an email or a direct visit — seemed to take all the credit for the sale? Feels unfair, right? The truth is, that customer probably saw your social ad, read a blog, maybe even clicked a referral link long before they ever opened that email.
That’s exactly why marketing attribution matters. It’s simply figuring out which touchpoints in the customer journey actually influenced the final decision.
Think about it: one day they notice your ad, a week later they stumble on your blog, and only after a few reminders do they finally click “buy.” Each step mattered.
The catch? A lot of teams still stick with first-touch or last-touch because it’s the default setting in tools like Google Analytics — quick to grab, even if it’s not the full picture.
But easy doesn’t mean accurate. In today’s world of multi-touch attribution, buyers rarely convert after a single click. They zigzag across platforms, compare options, and interact with your brand multiple times before saying yes.
👉 If you’d like to see how data science is reshaping AI in digital marketing, you can read our post on From Insights to Impact: How Data Science Will Revolutionize AI in Digital Marketing
💡 If you don’t want to spend hours stitching data from different platforms, tools like HubSpot Marketing Hub or SEMrush Traffic Analytics can save you a ton of time.
They pull all your touchpoints into one place so you can actually see what’s working without living in spreadsheets.
Dataset & Preparation
Before we dive into the models, let’s talk about the data. For this project, I used the Kaggle Multi-Touch Attribution dataset — 10,000 rows of marketing journeys across six different channels. If you don’t want to start from scratch, you can grab this dataset (or pull your own from Google Analytics / CRM).
📌 Code Snippet 1: Dataset Cleaning & Anonymization
import pandas as pd
import uuid
# Load data
df = pd.read_csv("multi_touch_attribution_data.csv")
# Step 1: Anonymize User IDs
user_map = {u: uuid.uuid4().hex[:8] for u in df["User ID"].unique()}
df["User_ID_Anon"] = df["User ID"].map(user_map)
# Step 2: Normalize Conversion
df["Conversion_Flag"] = df["Conversion"].map({"Yes": 1, "No": 0})
# Step 3: Format Timestamp & Add Step Order
df["Timestamp"] = pd.to_datetime(df["Timestamp"])
df = df.sort_values(["User_ID_Anon", "Timestamp"])
df["Step_Order"] = df.groupby("User_ID_Anon").cumcount() + 1
# Step 4: (Optional) Generalize Campaigns
df["Campaign_Anon"] = df["Campaign"].replace("", "Generic").fillna("Generic")
# Select safe columns for blog
df_safe = df[["User_ID_Anon", "Timestamp", "Step_Order", "Channel", "Campaign_Anon", "Conversion_Flag"]]
# Save anonymized version
df_safe.to_csv("anonymized_attribution.csv", index=False)
print("✅ Anonymized dataset saved as anonymized_attribution.csv")
Here’s a simplified look at the dataset after cleaning and anonymizing it:
| User ID | Step Order | Channel | Campaign | Conversion |
|---|---|---|---|---|
| 001 | 1 | Search Ads | Winter Sale | 0 |
| 001 | 2 | Blog | Blog Article CTA | 0 |
| 001 | 3 | Retargeting Offer | 1 | |
| 002 | 1 | Social Media | Brand Awareness | 0 |
| 002 | 2 | Referral | Partner Website | 1 |
✅ After prep, each user journey is clean, ordered, and anonymized — safe to use and perfect for testing attribution models.
👉 Related read: A/B Testing with Data Science: Optimizing Your Marketing Campaigns
Rule-Based Attribution Models
Before we get into the advanced stuff, let’s start with the basics. Most marketers begin with rule-based attribution because it’s quick and easy to set up. The three most common are:
First-Touch Attribution → 100% credit goes to the first channel that brought the user in.
Last-Touch Attribution → 100% credit goes to the final channel before conversion.
Linear Attribution → Credit is divided equally across all touchpoints in the journey.
📌 Code Snippet 2: Rule-Based Attribution Models (First, Last, Linear)
# Build user journeys
journeys = (
df_safe.sort_values(["User_ID_Anon", "Step_Order"])
.groupby("User_ID_Anon")
.agg({"Channel": list, "Conversion_Flag": "max"})
.reset_index()
)
converted_journeys = journeys[journeys["Conversion_Flag"] == 1]["Channel"]
# First-touch attribution
def first_touch(paths):
credits = {}
for p in paths:
credits[p[0]] = credits.get(p[0], 0) + 1
return credits
# Last-touch attribution
def last_touch(paths):
credits = {}
for p in paths:
credits[p[-1]] = credits.get(p[-1], 0) + 1
return credits
# Linear attribution
def linear(paths):
credits = {}
for p in paths:
share = 1 / len(p)
for ch in p:
credits[ch] = credits.get(ch, 0) + share
return credits
# Calculate
ft = first_touch(converted_journeys)
lt = last_touch(converted_journeys)
lin = linear(converted_journeys)
print("📌 First Touch Attribution:", ft)
print("📌 Last Touch Attribution:", lt)
print("📌 Linear Attribution:", lin)
📌 Code Snippet 3: Visualizing Rule-Based Attribution Results
import matplotlib.pyplot as plt
import numpy as np
# Create DataFrame for visualization
attrib_df = pd.DataFrame({
"Channel": list(set(ft.keys()) | set(lt.keys()) | set(lin.keys())),
"First Touch": [ft.get(ch, 0) for ch in set(ft.keys()) | set(lt.keys()) | set(lin.keys())],
"Last Touch": [lt.get(ch, 0) for ch in set(ft.keys()) | set(lt.keys()) | set(lin.keys())],
"Linear": [lin.get(ch, 0) for ch in set(ft.keys()) | set(lt.keys()) | set(lin.keys())],
})
attrib_df.set_index("Channel").plot(kind="bar", figsize=(10,6))
plt.ylabel("Conversions credited")
plt.title("Rule-Based Attribution Comparison")
plt.xticks(rotation=45, ha="right")
plt.show()
Rule-Based Attribution Comparison
Here’s a sample comparison of how these models can give very different answers using the same set of journeys:
| Channel | First-Touch % | Last-Touch % | Linear % |
|---|---|---|---|
| Search Ads | 45% | 20% | 30% |
| 10% | 40% | 25% | |
| Social Media | 25% | 15% | 20% |
| Referral | 15% | 20% | 20% |
| Display Ads | 5% | 5% | 5% |
👉 Notice how Search Ads dominates in first-touch (because it grabs attention early), while Email shines in last-touch (since it often closes). Linear tries to spread the credit, but in reality, it still doesn’t reflect true influence.
💡 Pro tip: If you’re only using rule-based models today, you’re likely overvaluing the channels that appear first or last. Advanced models (like Markov or Shapley) fix this problem by looking at the whole journey.
📌 If you want an easier way to test different attribution models without coding, check out HubSpot Attribution Reporting. It lets you run these comparisons in minutes.
Markov Chain Attribution
Here’s where things start to get interesting. Instead of just guessing which channel matters most, a Markov chain model actually looks at how people move through their journey.
Think of it this way: every channel is a stop on a map. Some people go from Social → Blog → Email → Conversion, while others might jump from Search → Display → Referral → Conversion. A Markov model helps us understand the probabilities of moving from one stop to the next.
The most powerful part? The removal effect. This tells us what happens to the overall conversion rate if we remove a channel completely. If conversions drop heavily when we remove “Email,” that means Email was pulling a lot of weight in the journey.
Pro tip: if you need to pipe events from multiple sources into a single data store for Markov modeling, N8n io is a lightweight automation tool you can self-host or run in the cloud:
📌 Code Snippet 4: Markov Chain Attribution
# Cell 6 -- Markov Chain Attribution
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
# Use journeys built earlier
paths = journeys["Channel"].tolist()
conv_flags = journeys["Conversion_Flag"].tolist()
# Step 1: Build transition counts
trans_counts = defaultdict(lambda: defaultdict(int))
start_counts = defaultdict(int)
for path, conv in zip(paths, conv_flags):
if not path: continue
start_counts[path[0]] += 1
trans_counts["start"][path[0]] += 1
for a,b in zip(path, path[1:]):
trans_counts[a][b] += 1
last = path[-1]
trans_counts[last]["conversion" if conv==1 else "null"] += 1
# Step 2: Build Q and R matrices
channels = sorted({c for p in paths for c in p})
absorbing = ["conversion","null"]
state_idx = {s:i for i,s in enumerate(channels)}
abs_idx = {a:i for i,a in enumerate(absorbing)}
k = len(channels)
Q = np.zeros((k,k))
R = np.zeros((k,len(absorbing)))
for s in channels:
i = state_idx[s]
total_out = sum(trans_counts[s].values())
if total_out == 0:
R[i, abs_idx["null"]] = 1.0
continue
for t,cnt in trans_counts[s].items():
if t in state_idx:
Q[i, state_idx[t]] = cnt/total_out
elif t in abs_idx:
R[i, abs_idx[t]] = cnt/total_out
else:
R[i, abs_idx["null"]] += cnt/total_out
# Step 3: Base conversion probability
total_starts = sum(start_counts.values())
pi = np.array([start_counts.get(s,0)/total_starts for s in channels]) if total_starts>0 else np.ones(k)/k
pi = pi/pi.sum()
I = np.eye(k)
N = np.linalg.pinv(I - Q) # fundamental matrix
B = N.dot(R)
conv_from_state = B[:, abs_idx["conversion"]]
base_conv_prob = float(np.dot(pi, conv_from_state))
print("Base conversion probability:", round(base_conv_prob,6))
# Step 4: Removal effect
removal_effects = {}
for i,ch in enumerate(channels):
mask = [j for j in range(k) if j != i]
if not mask:
removal_effects[ch] = 0.0
continue
Qp = Q[np.ix_(mask,mask)]
Rp = R[np.ix_(mask, list(range(R.shape[1])))]
pip = pi[mask]
pip = pip/pip.sum() if pip.sum()>0 else np.ones(len(mask))/len(mask)
Np = np.linalg.pinv(np.eye(len(mask)) - Qp)
Bp = Np.dot(Rp)
conv_without = float(np.dot(pip, Bp[:, abs_idx["conversion"]]))
removal_effects[ch] = base_conv_prob - conv_without
# Step 5: Normalize to percentages
total_re = sum(removal_effects.values())
markov_pct = {ch: (v/total_re)*100 if total_re>0 else 0.0 for ch,v in removal_effects.items()}
markov_df = pd.DataFrame(sorted(markov_pct.items(), key=lambda x: x[1], reverse=True),
columns=["channel","markov_pct"])
# Save to CSV
markov_df.to_csv("/content/markov_attribution_comparison.csv", index=False)
print("✅ Saved to /content/markov_attribution_comparison.csv")
display(markov_df)
# Step 6: Plot and save bar chart
plt.figure(figsize=(10,6))
plt.bar(markov_df["channel"], markov_df["markov_pct"], color="tab:blue")
plt.ylabel("Attribution Share (%)")
plt.title("Markov Attribution Results (Removal Effect)")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
out_png = "/content/markov_attribution.png"
plt.savefig(out_png, dpi=150, bbox_inches="tight")
plt.show()
print("✅ Saved bar chart to:", out_png)
Markov Attribution Results
Here’s a simplified version of the results from our project:
| Channel | Removal Effect (Drop in Conversion %) | Markov Attribution Share |
|---|---|---|
| Search Ads | -22% | 23% |
| -20% | 21% | |
| Social Media | -18% | 19% |
| Referral | -15% | 16% |
| Display Ads | -10% | 11% |
| Direct | -9% | 10% |
👉 What this shows: Search Ads and Email are still strong closers, but now you can clearly see that Social Media and Referral are critical mid-funnel players. Without them, many journeys wouldn’t even reach the point where Email can convert.
💡 Pro tip: This is where multi-touch attribution shines. It reveals that channels you thought were “assist players” might actually be MVPs in your funnel.
📌 Want to test Markov models without coding? Tools like Funnel.io or Dreamdata.io comes with advanced attribution baked in.
Shapley Value Attribution
Now, let’s talk about fairness. If Markov is about probabilities and removal effects, Shapley values (borrowed from game theory) are about giving each channel the credit it deserves based on its contribution across all possible combinations.
Think of it like this: if a group of players wins a game, Shapley figures out how much each player really added, even if they weren’t the one scoring the final goal. In marketing, this means every channel gets recognized — whether it’s the blog that warmed the lead, the ad that grabbed attention, or the email that closed the sale.
📌 Code Snippet 5: Shapley Attribution
# Cell 7 -- Shapley-value attribution (compute, compare, plot)
import time
import random
import itertools
import math
from functools import lru_cache
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Safety checks: ensure required objects exist
try:
journeys # from Cell 4
trans_counts # from Cell 6 markov build
start_counts
except NameError as e:
raise RuntimeError("Run previous cells (up through Markov) before running Shapley. Missing: " + str(e))
# Build channel list (same order used earlier)
all_channels = sorted({c for p in journeys["Channel"] for c in p})
n_channels = len(all_channels)
print("Channels (n={}): {}".format(n_channels, all_channels))
# Helper: conversion probability if only channels in S are available (Markov-style)
def conv_prob_for_channels(S):
S = list(S)
if len(S) == 0:
return 0.0
absorbing = ["conversion", "null"]
state_idx_local = {s:i for i,s in enumerate(S)}
abs_idx_local = {a:i for i,a in enumerate(absorbing)}
k_local = len(S)
Q_local = np.zeros((k_local,k_local), dtype=float)
R_local = np.zeros((k_local, len(absorbing)), dtype=float)
for s in S:
i = state_idx_local[s]
total_out = sum(trans_counts[s].values())
if total_out == 0:
R_local[i, abs_idx_local["null"]] = 1.0
continue
for t, cnt in trans_counts[s].items():
if t in state_idx_local:
Q_local[i, state_idx_local[t]] = cnt / total_out
elif t in abs_idx_local:
R_local[i, abs_idx_local[t]] = cnt / total_out
else:
R_local[i, abs_idx_local["null"]] += cnt / total_out
# start distribution for S
total_starts_global = sum(start_counts.values())
if total_starts_global == 0:
pi_local = np.ones(k_local) / k_local
else:
pi_local = np.array([start_counts.get(s,0)/total_starts_global for s in S], dtype=float)
if pi_local.sum() == 0:
pi_local = np.ones(k_local) / k_local
else:
pi_local = pi_local / pi_local.sum()
# fundamental matrix & conversion prob
try:
N_local = np.linalg.pinv(np.eye(k_local) - Q_local)
B_local = N_local.dot(R_local)
conv_prob = float(np.dot(pi_local, B_local[:, abs_idx_local["conversion"]]))
return conv_prob
except Exception:
return 0.0
# Cache wrapper
@lru_cache(maxsize=None)
def conv_prob_cache(tup):
return conv_prob_for_channels(list(tup))
# Decide exact vs Monte-Carlo
shapley = {ch: 0.0 for ch in all_channels}
start_time = time.time()
if n_channels <= 8:
print("Computing exact Shapley over all permutations (n! permutations)...")
perms = list(itertools.permutations(all_channels))
fact = math.factorial(n_channels)
for perm in perms:
prev = []
v_prev = conv_prob_cache(tuple(prev))
for ch in perm:
prev_with = tuple(prev + [ch])
v_with = conv_prob_cache(prev_with)
marginal = v_with - v_prev
shapley[ch] += marginal
prev = list(prev_with)
v_prev = v_with
for ch in shapley:
shapley[ch] /= fact
else:
n_samples = 3000 # adjust for speed/accuracy
print(f"n={n_channels} > 8 -- using Monte-Carlo Shapley with {n_samples} samples.")
for s in range(n_samples):
perm = random.sample(all_channels, k=n_channels)
prev = []
v_prev = conv_prob_cache(tuple(prev))
for ch in perm:
prev_with = tuple(prev + [ch])
v_with = conv_prob_cache(prev_with)
marginal = v_with - v_prev
shapley[ch] += marginal
prev = list(prev_with)
v_prev = v_with
for ch in shapley:
shapley[ch] /= float(n_samples)
elapsed = time.time() - start_time
print("Shapley computation finished in {:.1f}s".format(elapsed))
# Normalize Shapley to percentages
total_sh = sum(shapley.values())
shapley_pct = {ch: (v/total_sh)*100 if total_sh>0 else 0.0 for ch,v in shapley.items()}
# Create DataFrame for comparison with rule_df & markov_df
shap_df = pd.DataFrame(sorted(shapley_pct.items(), key=lambda x: x[1], reverse=True),
columns=["channel","shapley_pct"])
# Merge with existing rule_df and markov_df if present
# rule_df from Cell 5, markov_df from Cell 6
try:
merged = rule_df.merge(markov_df, left_on="channel", right_on="channel", how="outer").fillna(0)
merged = merged.merge(shap_df, left_on="channel", right_on="channel", how="outer").fillna(0)
merged = merged[["channel","first_touch_pct","last_touch_pct","linear_pct","markov_pct","shapley_pct"]]
except Exception:
# if merges fail, just create minimal comp
merged = pd.DataFrame({
"channel": shap_df["channel"],
"shapley_pct": shap_df["shapley_pct"]
})
# Save CSV
merged.to_csv("/content/shapley_attribution_comparison.csv", index=False)
print("✅ Saved Shapley comparison to /content/shapley_attribution_comparison.csv")
display(merged)
# Plot Markov vs Shapley (if both exist)
if "markov_pct" in merged.columns and "shapley_pct" in merged.columns:
labels = merged["channel"].tolist()
x = np.arange(len(labels))
width = 0.35
plt.figure(figsize=(10,6))
plt.bar(x - width/2, merged["markov_pct"], width, label="Markov")
plt.bar(x + width/2, merged["shapley_pct"], width, label="Shapley")
plt.xticks(x, labels, rotation=45, ha="right")
plt.ylabel("Attribution (%)")
plt.title("Shapley vs Markov Attribution Comparison")
plt.legend()
plt.tight_layout()
out_png = "/content/shapley_vs_markov_comparison.png"
plt.savefig(out_png, dpi=150, bbox_inches="tight")
plt.show()
print("✅ Saved chart to:", out_png)
else:
print("Markov or Shapley columns not present for plotting (merged columns: {})".format(list(merged.columns)))
Shapley vs Markov Attribution Comparison
Here’s a simplified example of Shapley vs Markov from our project:
| Channel | Shapley Attribution % | Markov Attribution % |
|---|---|---|
| Search Ads | 22% | 23% |
| 20% | 21% | |
| Social Media | 18% | 19% |
| Referral | 17% | 16% |
| Display Ads | 12% | 11% |
| Direct | 11% | 10% |
👉 What’s interesting: Shapley spreads credit slightly more evenly. It doesn’t let “big closers” like Email hog all the credit, and it lifts the importance of supportive channels like Referral and Social Media.
💡 Pro tip: If you ever have to present attribution results to a cross-functional team (like sales or finance), Shapley is your best friend. It’s hard to argue against fairness.
📌 Tools like Dreamdata and Windsor.ai actually have Shapley attribution models built in — a great shortcut if you don’t want to crunch it yourself.
Visual Insights: Making Attribution Click
Numbers are useful, but visuals tell the story in a way everyone can understand. Here’s how we broke down the results:
Bar Chart: Rule-Based vs Markov
We started by plotting First-Touch, Last-Touch, Linear, and Markov side by side. The chart instantly showed the bias in rule-based models — with Email and Search Ads swinging wildly between first vs last touch — while Markov provided a balanced, data-driven view.
👉 Takeaway: If you’re still reporting attribution without visuals, you’re missing the chance to spot (and explain) these biases quickly.
Sankey Diagram: User Journey Flows
Next, we visualized the top 12 customer journeys with a Sankey diagram. It was eye-opening: you could literally see how users bounced from Social → Blog → Email → Conversion, or Search → Referral → Conversion.
👉 Takeaway: This makes it crystal clear for teams outside marketing (like sales or finance) to grasp the real journey without digging into raw data.
📌 Code Snippet 6: Sankey Attribution
# Cell 8 -- Sankey-like flow visualization (matplotlib)
from collections import Counter, defaultdict
import matplotlib.pyplot as plt
import numpy as np
# Use journeys DataFrame created earlier
paths_str = journeys["Channel"].apply(lambda x: " > ".join(x))
path_counts = paths_str.value_counts().reset_index()
path_counts.columns = ["path_str","count"]
K = 12 # top K paths to highlight; reduce if plots look crowded
top_paths = path_counts.head(K)
# Count edges for top paths (highlight) and all edges (background)
edge_counts = Counter()
for p,cnt in zip(top_paths["path_str"], top_paths["count"]):
chs = p.split(" > ")
for a,b in zip(chs, chs[1:]):
edge_counts[(a,b)] += cnt
all_edges = Counter()
for p in journeys["Channel"]:
for a,b in zip(p, p[1:]):
all_edges[(a,b)] += 1
# Build nodes and approximate x positions by average step index
nodes = sorted({n for e in set(list(edge_counts.keys()) + list(all_edges.keys())) for n in e})
channel_positions = defaultdict(list)
for p in journeys["Channel"]:
for idx,ch in enumerate(p):
channel_positions[ch].append(idx)
avg_pos = {ch: np.mean(idxs) for ch,idxs in channel_positions.items()}
minp, maxp = min(avg_pos.values()), max(avg_pos.values())
norm_pos = {ch:(avg_pos[ch]-minp)/(maxp-minp) if maxp>minp else 0.5 for ch in avg_pos}
# Group by x and assign y positions per group
groups = defaultdict(list)
for ch, x in norm_pos.items():
groups[round(x,2)].append(ch)
node_coords = {}
for x_group, chs in groups.items():
x = float(x_group)
n = len(chs)
for i,ch in enumerate(sorted(chs)):
y = 1.0 - (i+1)/(n+1)
node_coords[ch] = (x, y)
# fallback positions
for ch in nodes:
if ch not in node_coords:
node_coords[ch] = (0.5, 0.5)
# Draw plot
plt.figure(figsize=(12,6))
ax = plt.gca(); ax.axis('off')
max_count = max(all_edges.values()) if all_edges else 1
def draw_edge(a,b,count,alpha=0.3,z=1,linewidth_scale=6):
(x1,y1) = node_coords[a]; (x2,y2) = node_coords[b]
xm = (x1+x2)/2; ctrl_y = max(y1,y2) + 0.15
xs = [x1, xm, x2]; ys = [y1, ctrl_y, y2]
lw = max(0.5, (count/max_count)*linewidth_scale)
ax.plot(xs, ys, linewidth=lw, alpha=alpha, zorder=z, solid_capstyle='round')
# Draw background edges faintly
for (a,b), cnt in all_edges.items():
draw_edge(a,b,cnt,alpha=0.12,z=1,linewidth_scale=4)
# Highlight top-path edges
for (a,b), cnt in edge_counts.items():
draw_edge(a,b,cnt,alpha=0.9,z=3,linewidth_scale=10)
# Draw nodes and labels
for ch,(x,y) in node_coords.items():
ax.scatter([x],[y], s=200, zorder=4)
ax.text(x+0.01, y, ch, va='center', fontsize=10)
plt.title(f"Sankey-like flow: Top {K} paths highlighted")
plt.tight_layout()
out_png = "/content/sankey_flows.png"
plt.savefig(out_png, dpi=150, bbox_inches="tight")
plt.show()
print("✅ Saved Sankey image to:", out_png)
Sankey-style diagram
Top User Paths (Sankey-style Summary)
| Top user path | Count | Share |
|---|---|---|
| Social → Blog → Email → Conversion | 420 | 21.0% |
| Search → Referral → Conversion | 310 | 15.5% |
| Display → Search → Email → Conversion | 210 | 10.5% |
| Social → Referral → Conversion | 180 | 9.0% |
| Search → Blog → Email → Conversion | 160 | 8.0% |
| Direct → Search → Conversion | 120 | 6.0% |
Shapley vs Markov: Grouped Comparison
Finally, we put Shapley and Markov results side by side in a grouped bar chart. Both models largely agreed, but you could see Shapley gently lifting the “supporting actors” (Referral, Social) while Markov stuck closer to hard probabilities.
👉 Takeaway: Presenting both models side by side builds confidence. It shows your results aren’t biased toward one method, and stakeholders can trust the insights.
💡 Pro tip: Tools like Tableau and Zoho Analytics can help you create these charts without writing code, especially if you want stakeholder-ready dashboards.
Conclusion: From Guesswork to Confidence
Attribution isn’t about giving the loudest channel all the credit — it’s about understanding the entire journey. By using Markov chains and Shapley values, you go from guesswork to clarity. You see which channels spark awareness, which nurture trust, and which push conversions across the line.
Marketers who embrace this level of attribution stop wasting budget and start scaling smart. The best part? You don’t have to build it all yourself — platforms like HubSpot Marketing Hub, SEMrush Traffic Analytics, and Dreamdata already have attribution features baked in.
Recommended tools (affiliate):
- Custom GPT — Automate reporting, summaries, campaign alerts
- SEOWriting AI — Fast SEO-optimized content & meta generation
- AIWriter — Rapid copy generation and testing:
- N8n io — Integrate events and stitch data pipelines for attribution
📥 Next Step: Download our anonymized dataset + Jupyter Notebook, replicate the models, and apply them to your own campaigns. Once you do, you’ll never look at last-click reports the same way again.
FAQ
What is marketing attribution in simple words?
It’s the process of figuring out which marketing channels deserve credit for a conversion.
Why is last-click attribution misleading?
Because it ignores all the earlier touchpoints that influenced the customer.
What is multi-touch attribution?
A method that distributes credit across multiple interactions in the customer journey.
How does first-touch attribution work?
It gives 100% credit to the first channel that introduced the user to your brand.
What is linear attribution?
It spreads credit equally across all touchpoints in a journey.
What is Markov chain attribution?
It uses probabilities to see how removing a channel changes overall conversion rates.
What are Shapley values in marketing attribution?
A game-theory method that fairly distributes credit based on each channel’s contribution.
Which attribution model is most accurate?
Data-driven models like Markov and Shapley give a more realistic picture than rule-based ones.
Can small businesses use marketing attribution?
Yes, even simple tools like HubSpot or Google Analytics offer attribution reports.
How do I choose the right attribution model?
Start with rule-based for speed, then move to Markov or Shapley for deeper insights.
What tools are best for marketing attribution?
HubSpot, SEMrush, Dreamdata, and Windsor.ai are popular choices.
Can attribution improve ROI?
Yes, by showing which channels truly work, you can invest smarter and cut waste.
Can attribution improve ROI?
Yes, by showing which channels truly work, you can invest smarter and cut waste.
Is marketing attribution only for paid ads?
No, it covers all channels — paid, organic, social, referral, email, even offline.
How do you prepare data for attribution?
Clean user journeys, anonymize IDs, and order steps with timestamps.
Where can I find a dataset for practice?
Kaggle’s Multi-Touch Attribution dataset is a good starting point.
Do I need coding to run attribution models?
Not always. Tools have built-in models, but Python/R let you customize.
What’s the difference between Markov and Shapley models?
Markov shows incremental impact via removal effect, Shapley ensures fair credit distribution.
Can attribution work with offline channels?
Yes, if you can track interactions (like phone calls or store visits) and include them in journeys.
How do I visualize attribution results?
Use bar charts for model comparison and Sankey diagrams for user flows.
What mistakes do marketers make with attribution?
Relying only on last-click, ignoring supporting channels, and not validating with multiple models.
How do I explain attribution to non-technical stakeholders?
Use visuals (charts, Sankeys) and simple analogies like “team sports.”
Can AI improve attribution?
Yes, AI can analyze massive datasets faster and uncover hidden patterns.
How often should I review attribution?
Monthly is a good starting point, but review more often if you run frequent campaigns.
Does attribution replace analytics?
No, it complements analytics by showing not just what happened, but why.
What’s the future of marketing attribution?
It’s moving toward AI-powered, real-time models that integrate across all platforms.
