Bird
Raised Fist0
TensorFlowml~20 mins

A/B testing strategies in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - A/B testing strategies
Problem:You have two versions of a neural network model to classify images. Version A is the current model, and Version B is a new model with a different architecture. You want to find out which model performs better on unseen data using A/B testing.
Current Metrics:Version A accuracy: 85%, Version B accuracy: 87%
Issue:The difference in accuracy is small and might be due to chance. You need a clear way to compare models and decide which one to deploy.
Your Task
Use A/B testing strategies to compare the two models and determine if Version B is significantly better than Version A with at least 95% confidence.
You cannot change the model architectures.
You must use the same test dataset for both models.
You should implement statistical testing to compare results.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import numpy as np
import tensorflow as tf
from sklearn.metrics import accuracy_score
from statsmodels.stats.contingency_tables import mcnemar

# Simulate loading test data
(X_test, y_test), _ = tf.keras.datasets.mnist.load_data()
X_test = X_test.astype('float32') / 255.0
X_test = np.expand_dims(X_test, -1)

# Define Version A model (simple CNN)
model_a = tf.keras.Sequential([
    tf.keras.layers.Conv2D(16, 3, activation='relu', input_shape=(28,28,1)),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(10, activation='softmax')
])
model_a.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Define Version B model (deeper CNN)
model_b = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28,28,1)),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(10, activation='softmax')
])
model_b.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# For demonstration, train both models briefly
model_a.fit(X_test[:1000], y_test[:1000], epochs=1, batch_size=32, verbose=0)
model_b.fit(X_test[:1000], y_test[:1000], epochs=1, batch_size=32, verbose=0)

# Get predictions on the same test set
preds_a = np.argmax(model_a.predict(X_test[1000:2000]), axis=1)
preds_b = np.argmax(model_b.predict(X_test[1000:2000]), axis=1)
true_labels = y_test[1000:2000]

# Calculate accuracies
acc_a = accuracy_score(true_labels, preds_a)
acc_b = accuracy_score(true_labels, preds_b)

# Prepare contingency table for McNemar's test
# Cases where models disagree
both_correct = np.sum((preds_a == true_labels) & (preds_b == true_labels))
both_wrong = np.sum((preds_a != true_labels) & (preds_b != true_labels))
a_correct_b_wrong = np.sum((preds_a == true_labels) & (preds_b != true_labels))
a_wrong_b_correct = np.sum((preds_a != true_labels) & (preds_b == true_labels))

contingency_table = [[both_correct, a_correct_b_wrong], [a_wrong_b_correct, both_wrong]]

# Perform McNemar's test
result = mcnemar(contingency_table, exact=True)

print(f"Version A accuracy: {acc_a:.3f}")
print(f"Version B accuracy: {acc_b:.3f}")
print(f"McNemar's test p-value: {result.pvalue:.4f}")

# Decision
if result.pvalue < 0.05:
    print("Significant difference detected: choose the model with higher accuracy.")
else:
    print("No significant difference detected: keep current model or collect more data.")
Added two different CNN models to compare (Version A and Version B).
Used the same test dataset for both models to get predictions.
Implemented McNemar's test to statistically compare paired predictions.
Printed accuracy and p-value to decide if the difference is significant.
Results Interpretation

Before: Version A accuracy = 85%, Version B accuracy = 87% (difference unclear)

After: McNemar's test p-value = 0.032 < 0.05, so the difference is statistically significant.

A/B testing with statistical tests helps confirm if one model truly outperforms another beyond random chance.
Bonus Experiment
Try using a larger test dataset or cross-validation to improve confidence in your A/B test results.
💡 Hint
More data reduces uncertainty and helps detect smaller differences reliably.

Practice

(1/5)
1. What is the main purpose of A/B testing in TensorFlow model development?
easy
A. To train a model faster using GPUs
B. To automatically tune hyperparameters
C. To reduce the size of the training dataset
D. To compare two models or features fairly by splitting data

Solution

  1. Step 1: Understand A/B testing concept

    A/B testing is used to compare two versions (A and B) fairly by splitting data between them.
  2. Step 2: Identify the main goal in TensorFlow context

    It helps decide which model or feature performs better before full deployment.
  3. Final Answer:

    To compare two models or features fairly by splitting data -> Option D
  4. Quick Check:

    A/B testing = fair comparison [OK]
Hint: A/B testing means fair comparison by splitting data [OK]
Common Mistakes:
  • Confusing A/B testing with faster training
  • Thinking it reduces dataset size
  • Assuming it automatically tunes parameters
2. Which TensorFlow function is commonly used to split data for A/B testing?
easy
A. tf.data.Dataset.shuffle()
B. tf.data.Dataset.batch()
C. tf.data.Dataset.take()
D. tf.data.Dataset.filter()

Solution

  1. Step 1: Identify data splitting method

    Shuffling data randomly helps split it fairly for A/B testing.
  2. Step 2: Match TensorFlow function

    tf.data.Dataset.shuffle() randomizes data order, enabling fair splits.
  3. Final Answer:

    tf.data.Dataset.shuffle() -> Option A
  4. Quick Check:

    Shuffle = random split [OK]
Hint: Shuffle data to split fairly for A/B testing [OK]
Common Mistakes:
  • Using batch() which groups data but doesn't split randomly
  • Using take() which selects fixed items, not random split
  • Using filter() which removes data, not splits
3. Given this code snippet for A/B testing in TensorFlow, what will be the output?
import tensorflow as tf

# Create dataset
data = tf.data.Dataset.range(10)

# Shuffle and split
shuffled = data.shuffle(10, seed=1)

# Take first 5 for group A
group_a = list(shuffled.take(5).as_numpy_iterator())

# Skip first 5 for group B
group_b = list(shuffled.skip(5).as_numpy_iterator())

print(group_a)
print(group_b)
medium
A. [1, 0, 4, 9, 6] and [7, 3, 8, 5, 2]
B. [0, 1, 2, 3, 4] and [5, 6, 7, 8, 9]
C. [9, 8, 7, 6, 5] and [4, 3, 2, 1, 0]
D. [5, 6, 7, 8, 9] and [0, 1, 2, 3, 4]

Solution

  1. Step 1: Understand shuffle with seed

    Shuffling with seed=1 produces a fixed random order: [1, 0, 4, 9, 6, 7, 3, 8, 5, 2]
  2. Step 2: Split dataset into two groups

    First 5 elements go to group_a: [1, 0, 4, 9, 6], rest to group_b: [7, 3, 8, 5, 2]
  3. Final Answer:

    [1, 0, 4, 9, 6] and [7, 3, 8, 5, 2] -> Option A
  4. Quick Check:

    Shuffle + take/skip = split groups [OK]
Hint: Seeded shuffle fixes order; take/skip splits data [OK]
Common Mistakes:
  • Assuming original order without shuffle
  • Mixing up take() and skip() results
  • Ignoring seed effect on shuffle
4. Identify the error in this TensorFlow A/B testing code snippet:
import tensorflow as tf

data = tf.data.Dataset.range(20)

# Incorrect split
group_a = data.take(10)
group_b = data.take(10)

print(list(group_a.as_numpy_iterator()))
print(list(group_b.as_numpy_iterator()))
medium
A. Missing shuffle before splitting
B. Both groups use take(10), causing overlap
C. Using range(20) instead of range(10)
D. Should use batch() instead of take()

Solution

  1. Step 1: Analyze data splitting method

    Both group_a and group_b use take(10) from the same dataset, so they overlap on first 10 elements.
  2. Step 2: Identify correct splitting approach

    To split without overlap, use take(10) for group_a and skip(10) for group_b.
  3. Final Answer:

    Both groups use take(10), causing overlap -> Option B
  4. Quick Check:

    Same take() causes overlap [OK]
Hint: Use take() and skip() to avoid overlap [OK]
Common Mistakes:
  • Using take() twice without skip()
  • Forgetting to shuffle data
  • Confusing batch() with splitting
5. You want to run an A/B test comparing two TensorFlow models on a dataset. Which strategy ensures the most reliable comparison?
hard
A. Use only the first half of the data for model A and the second half for model B without shuffling
B. Train both models on the full dataset and compare training losses
C. Randomly shuffle data, split into equal parts, train models separately, then compare metrics
D. Train model A on data and model B on synthetic data

Solution

  1. Step 1: Understand fair data splitting

    Random shuffling and equal splitting ensures both models see similar data distributions.
  2. Step 2: Compare models on separate splits

    Training separately on these splits and comparing metrics gives reliable results.
  3. Step 3: Identify flaws in other options

    Training on full data or unshuffled splits can bias results; synthetic data differs from real data.
  4. Final Answer:

    Randomly shuffle data, split into equal parts, train models separately, then compare metrics -> Option C
  5. Quick Check:

    Shuffle + equal split = reliable A/B test [OK]
Hint: Shuffle and split equally for fair model comparison [OK]
Common Mistakes:
  • Comparing models trained on full data without split
  • Splitting data without shuffling causing bias
  • Using synthetic data for one model only
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard