import tensorflow as tf
from tensorflow.keras import layers, models, regularizers
# Load dataset
mnist = tf.keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize data
X_train, X_test = X_train / 255.0, X_test / 255.0
# Flatten images
X_train = X_train.reshape(-1, 28*28)
X_test = X_test.reshape(-1, 28*28)
# Build model with L2 regularization and dropout
model = models.Sequential([
layers.Dense(128, activation='relu', kernel_regularizer=regularizers.l2(0.001), input_shape=(28*28,)),
layers.Dropout(0.3),
layers.Dense(64, activation='relu', kernel_regularizer=regularizers.l2(0.001)),
layers.Dropout(0.3),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train model
history = model.fit(X_train, y_train, epochs=20, batch_size=64, validation_split=0.2, verbose=0)
# Evaluate on test data
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
print(f'Test accuracy: {test_acc*100:.2f}%', f'Test loss: {test_loss:.4f}')