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.")