A/B Test Analysis

A/B Test Analysis

Teaches an AI agent to design and analyse A/B tests in Python, covering sample size, significance testing, effect size and interpreting results.

Skill files3 files

scripts/

templates/

SKILL.md279 lines
1
---
2
name: A/B Test Analysis
3
description: Design and analyze A/B tests, calculate statistical significance, and determine sample sizes for conversion optimization and experiment validation
4
---
5
6
# A/B Test Analysis
7
8
## Overview
9
10
A/B testing is a statistical method to compare two variants and determine which performs better, enabling data-driven optimization decisions.
11
12
## When to Use
13
14
- Comparing two versions of a product feature, webpage, or marketing campaign
15
- Optimizing conversion rates, click-through rates, or user engagement metrics
16
- Making data-driven decisions with statistical confidence about changes
17
- Determining sample size requirements for experiment validity
18
- Analyzing treatment effects and measuring lift from interventions
19
- Evaluating whether observed differences are statistically significant
20
21
## Core Components
22
23
- **Control Group**: Original version (A)
24
- **Treatment Group**: New variant (B)
25
- **Metric**: Outcome being measured
26
- **Sample Size**: Observations needed for power
27
- **Significance Level**: Type I error threshold (α = 0.05)
28
- **Power**: 1 - Type II error (typically 0.80)
29
30
## Analysis Steps
31
32
1. Define success metric
33
2. Calculate sample size
34
3. Run experiment
35
4. Check assumptions
36
5. Perform statistical test
37
6. Calculate effect size
38
7. Interpret results
39
40
## Implementation with Python
41
42
```python
43
import pandas as pd
44
import numpy as np
45
import matplotlib.pyplot as plt
46
from scipy import stats
47
from scipy.stats import binom_test, ttest_ind, chi2_contingency
48
import seaborn as sns
49
50
# Sample A/B test data
51
np.random.seed(42)
52
53
# Scenario: Testing new checkout flow
54
control_conversions = np.random.binomial(1, 0.10, 10000)
55
treatment_conversions = np.random.binomial(1, 0.12, 10000)
56
57
control_revenue = np.random.exponential(50, 10000)
58
treatment_revenue = np.random.exponential(55, 10000)
59
60
# Create dataframes
61
df_control = pd.DataFrame({
62
'group': 'Control',
63
'converted': control_conversions,
64
'revenue': control_revenue,
65
})
66
67
df_treatment = pd.DataFrame({
68
'group': 'Treatment',
69
'converted': treatment_conversions,
70
'revenue': treatment_revenue,
71
})
72
73
df = pd.concat([df_control, df_treatment], ignore_index=True)
74
75
print("A/B Test Data Summary:")
76
print(df.groupby('group')[['converted', 'revenue']].agg({
77
'converted': ['sum', 'count', 'mean'],
78
'revenue': ['sum', 'mean', 'std'],
79
}))
80
81
# 1. Conversion Rate Test (Chi-square)
82
contingency_table = pd.crosstab(df['group'], df['converted'])
83
print("\nContingency Table:")
84
print(contingency_table)
85
86
chi2, p_value, dof, expected = chi2_contingency(contingency_table)
87
print(f"\nChi-square Test:")
88
print(f"Chi2 statistic: {chi2:.4f}")
89
print(f"P-value: {p_value:.4f}")
90
print(f"Significant: {'Yes' if p_value < 0.05 else 'No'}")
91
92
# 2. Conversion Rate Calculation
93
control_cr = df[df['group'] == 'Control']['converted'].mean()
94
treatment_cr = df[df['group'] == 'Treatment']['converted'].mean()
95
lift = (treatment_cr - control_cr) / control_cr * 100
96
97
print(f"\nConversion Rates:")
98
print(f"Control: {control_cr:.4f} ({control_cr*100:.2f}%)")
99
print(f"Treatment: {treatment_cr:.4f} ({treatment_cr*100:.2f}%)")
100
print(f"Lift: {lift:.2f}%")
101
102
# 3. Revenue Per User Test (T-test)
103
control_revenue = df[df['group'] == 'Control']['revenue']
104
treatment_revenue = df[df['group'] == 'Treatment']['revenue']
105
106
t_stat, p_value_revenue = ttest_ind(control_revenue, treatment_revenue)
107
print(f"\nRevenue Per User T-test:")
108
print(f"Control Mean: ${control_revenue.mean():.2f}")
109
print(f"Treatment Mean: ${treatment_revenue.mean():.2f}")
110
print(f"T-statistic: {t_stat:.4f}")
111
print(f"P-value: {p_value_revenue:.4f}")
112
print(f"Significant: {'Yes' if p_value_revenue < 0.05 else 'No'}")
113
114
# 4. Effect Size (Cohen's d)
115
def cohens_d(group1, group2):
116
n1, n2 = len(group1), len(group2)
117
var1, var2 = np.var(group1, ddof=1), np.var(group2, ddof=1)
118
pooled_std = np.sqrt(((n1-1)*var1 + (n2-1)*var2) / (n1+n2-2))
119
return (np.mean(group1) - np.mean(group2)) / pooled_std
120
121
effect_size = cohens_d(control_revenue, treatment_revenue)
122
print(f"\nEffect Size (Cohen's d): {effect_size:.4f}")
123
print("Interpretation: " + {
124
True: "Small effect (|d| < 0.2)",
125
False: {
126
True: "Medium effect (0.2 <= |d| < 0.8)",
127
False: "Large effect (|d| >= 0.8)"
128
}[abs(effect_size) < 0.8]
129
}[abs(effect_size) < 0.2])
130
131
# 5. Confidence Intervals
132
def confidence_interval(data, confidence=0.95):
133
n = len(data)
134
mean = np.mean(data)
135
se = stats.sem(data)
136
margin = se * stats.t.ppf((1 + confidence) / 2, n - 1)
137
return mean - margin, mean + margin
138
139
ci_control = confidence_interval(control_revenue)
140
ci_treatment = confidence_interval(treatment_revenue)
141
142
print(f"\n95% Confidence Intervals:")
143
print(f"Control: (${ci_control[0]:.2f}, ${ci_control[1]:.2f})")
144
print(f"Treatment: (${ci_treatment[0]:.2f}, ${ci_treatment[1]:.2f})")
145
146
# 6. Sample Size Calculation
147
def calculate_sample_size(baseline_cr, target_cr, significance=0.05, power=0.80):
148
from scipy.stats import norm
149
effect_size = 2 * (np.arcsin(np.sqrt(target_cr)) - np.arcsin(np.sqrt(baseline_cr)))
150
z_alpha = norm.ppf(1 - significance/2)
151
z_beta = norm.ppf(power)
152
n = ((z_alpha + z_beta) / effect_size) ** 2
153
return int(np.ceil(n))
154
155
sample_size_needed = calculate_sample_size(control_cr, treatment_cr)
156
print(f"\nSample Size Analysis:")
157
print(f"Baseline CR: {control_cr:.4f}")
158
print(f"Target CR: {treatment_cr:.4f}")
159
print(f"Required per group: {sample_size_needed:,}")
160
print(f"Actual per group: {len(df[df['group'] == 'Control']):,}")
161
162
# 7. Sequential Testing / Running Analysis
163
fig, axes = plt.subplots(2, 2, figsize=(14, 8))
164
165
# Cumulative conversion rates
166
control_cumsum = df[df['group'] == 'Control']['converted'].cumsum()
167
treatment_cumsum = df[df['group'] == 'Treatment']['converted'].cumsum()
168
control_n = np.arange(1, len(control_cumsum) + 1)
169
treatment_n = np.arange(1, len(treatment_cumsum) + 1)
170
171
axes[0, 0].plot(control_n, control_cumsum / control_n, label='Control', alpha=0.7)
172
axes[0, 0].plot(treatment_n, treatment_cumsum / treatment_n, label='Treatment', alpha=0.7)
173
axes[0, 0].set_xlabel('Sample Size')
174
axes[0, 0].set_ylabel('Conversion Rate')
175
axes[0, 0].set_title('Conversion Rate Over Time')
176
axes[0, 0].legend()
177
axes[0, 0].grid(True, alpha=0.3)
178
179
# Distribution comparison
180
axes[0, 1].hist(control_revenue, bins=50, alpha=0.5, label='Control', density=True)
181
axes[0, 1].hist(treatment_revenue, bins=50, alpha=0.5, label='Treatment', density=True)
182
axes[0, 1].set_xlabel('Revenue')
183
axes[0, 1].set_ylabel('Density')
184
axes[0, 1].set_title('Revenue Distribution')
185
axes[0, 1].legend()
186
187
# Box plot comparison
188
data_box = [control_revenue, treatment_revenue]
189
axes[1, 0].boxplot(data_box, labels=['Control', 'Treatment'])
190
axes[1, 0].set_ylabel('Revenue')
191
axes[1, 0].set_title('Revenue Distribution (Box Plot)')
192
axes[1, 0].grid(True, alpha=0.3, axis='y')
193
194
# Conversion comparison
195
conversion_data = pd.DataFrame({
196
'Group': ['Control', 'Treatment'],
197
'Converted': [control_conversions.sum(), treatment_conversions.sum()],
198
'Not Converted': [len(control_conversions) - control_conversions.sum(),
199
len(treatment_conversions) - treatment_conversions.sum()],
200
})
201
conversion_data.set_index('Group')[['Converted', 'Not Converted']].plot(
202
kind='bar', ax=axes[1, 1], color=['green', 'red'], edgecolor='black'
203
)
204
axes[1, 1].set_title('Conversion Comparison')
205
axes[1, 1].set_ylabel('Count')
206
axes[1, 1].legend(title='Status')
207
208
plt.tight_layout()
209
plt.show()
210
211
# 8. Bayesian Perspective
212
print("\n8. Bayesian Analysis (informative):")
213
from scipy.stats import beta
214
215
# Assume prior Beta(1, 1) - uninformative
216
control_successes = control_conversions.sum()
217
control_failures = len(control_conversions) - control_successes
218
treatment_successes = treatment_conversions.sum()
219
treatment_failures = len(treatment_conversions) - treatment_successes
220
221
# Posterior distributions
222
posterior_control = beta(1 + control_successes, 1 + control_failures)
223
posterior_treatment = beta(1 + treatment_successes, 1 + treatment_failures)
224
225
samples_control = posterior_control.rvs(10000)
226
samples_treatment = posterior_treatment.rvs(10000)
227
228
prob_treatment_better = (samples_treatment > samples_control).mean()
229
print(f"Probability Treatment > Control: {prob_treatment_better:.4f}")
230
231
# Visualization
232
fig, ax = plt.subplots(figsize=(10, 5))
233
ax.hist(samples_control, bins=50, alpha=0.5, label='Control', density=True)
234
ax.hist(samples_treatment, bins=50, alpha=0.5, label='Treatment', density=True)
235
ax.set_xlabel('Conversion Rate')
236
ax.set_ylabel('Density')
237
ax.set_title('Bayesian Posterior Distributions')
238
ax.legend()
239
ax.grid(True, alpha=0.3)
240
plt.show()
241
242
# 9. Summary Report
243
print("\n" + "="*50)
244
print("A/B TEST SUMMARY REPORT")
245
print("="*50)
246
print(f"Metric: Conversion Rate")
247
print(f"Control CR: {control_cr*100:.2f}%")
248
print(f"Treatment CR: {treatment_cr*100:.2f}%")
249
print(f"Lift: {lift:.2f}%")
250
print(f"P-value: {p_value:.4f}")
251
print(f"Result: {'REJECT H0 - Significant Difference' if p_value < 0.05 else 'FAIL TO REJECT H0 - No Significant Difference'}")
252
print(f"Winner: {f'Treatment (+{lift:.2f}%)' if p_value < 0.05 and lift > 0 else 'Control (No clear winner)'}")
253
print("="*50)
254
```
255
256
## Sample Size Determination
257
258
- **Baseline conversion rate**: Current performance
259
- **Target effect size**: Minimum detectable difference
260
- **Significance level (α)**: Usually 0.05
261
- **Power (1-β)**: Usually 0.80 or 0.90
262
263
## Key Metrics
264
265
- **Conversion Rate**: Proportion of successes
266
- **Revenue Per User**: Average transaction value
267
- **Click-through Rate**: Ad performance
268
- **Engagement**: Feature adoption
269
270
## Deliverables
271
272
- Test design document
273
- Sample size calculations
274
- Statistical test results
275
- Effect size measurements
276
- Confidence intervals
277
- Visualization of results
278
- Executive summary with recommendation
279

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,331 prompts

More by @OpenSourceBuffGuy

See all
Lab teacher silences class as infected close in prompt image

Lab teacher silences class as infected close in

Generates a short realistic horror clip in a Japanese school science lab where a teacher and students hide silently from infected figures closing in, with sound-driven beats.

video-prompt, horror, cinematic, photorealistic, handheld, timed-beats, camera-movement, negative-prompt, guardrails, moody, short-film, seedance, for-filmmakers, for-content-creators, storytelling, thriller, dramatic-lighting, muted-colors, japan

Valentine's newspaper editorial portrait from your photo prompt image

Valentine's newspaper editorial portrait from your photo

Turns an uploaded face photo into a top-down Valentine's fashion editorial: red blazer, roses, heart balloons and a newspaper headline.

image-prompt, nano-banana, reference-image, face-reference, photo-editing, portrait, woman, fashion-shoot, editorial, valentines-day, photorealistic, studio-lighting, close-up, high-angle, film-grain, vibrant-colors, flowers, text-rendering, placeholders, fashion, holiday, soft-lighting, bokeh, vertical-format

Woman leaps into leaf pile revealing pool prompt image

Woman leaps into leaf pile revealing pool

Generates a one-shot autumn gag where someone announces the first day of fall and leaps into a leaf pile that hides a tiny blue kiddie pool.

video-prompt, comedy, autumn, single-take, wide-shot, golden-hour, vibrant-colors, humorous, timed-beats, lip-sync, natural-light, short-form-video, quick, cinematic, action, transformation

Reviews

Loading reviews…

Discussion

Loading comments…