Below is an example Python script that uses TensorFlow to load the MNIST dataset, performs an 80/20 random train/test split, and then builds and trains two models:
- Softmax Regression: Implemented as a one-layer neural network (i.e. a Dense layer with softmax activation).
- Multilayer Perceptron (MLP): Implemented as a neural network with one hidden layer.
You can run the code as-is if you have TensorFlow installed.
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
# For reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Download the MNIST dataset
# MNIST images are 28x28 pixels (grayscale) and labels are integers in [0, 9].
# The dataset returned by tf.keras.datasets.mnist.load_data() comes split into a training set and test set.
# Here, we will combine them and make our own 80/20 split.
(mnist_x_train, mnist_y_train), (mnist_x_test, mnist_y_test) = tf.keras.datasets.mnist.load_data()
all_images = np.concatenate([mnist_x_train, mnist_x_test], axis=0)
all_labels = np.concatenate([mnist_y_train, mnist_y_test], axis=0)
# Preprocess the data:
# 1. Normalize the images to the [0, 1] range.
# 2. Flatten the 28x28 images into 784-dimensional vectors.
all_images = all_images.astype("float32") / 255.0
num_samples = all_images.shape[0]
all_images = all_images.reshape(num_samples, -1) # reshape to (num_samples, 784)
# Split the data into an 80% training set and 20% test set.
X_train, X_test, y_train, y_test = train_test_split(all_images, all_labels, test_size=0.2, random_state=42, shuffle=True)
print(f"Training samples: {X_train.shape[0]}, Test samples: {X_test.shape[0]}")
# --------------------------
# Model 1: Softmax Regression
# --------------------------
# This model is implemented as a sequential model with a single Dense layer with softmax activation.
softmax_model = tf.keras.models.Sequential([
# Dense layer with 10 units (one for each digit 0-9) and softmax activation.
tf.keras.layers.Dense(10, activation="softmax", input_shape=(784,))
])
softmax_model.compile(optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"])
print("\nTraining Softmax Regression Model...")
softmax_history = softmax_model.fit(X_train, y_train, epochs=10, batch_size=128, validation_split=0.1, verbose=2)
# Evaluate the softmax regression model on the test set.
softmax_test_loss, softmax_test_acc = softmax_model.evaluate(X_test, y_test, verbose=2)
print(f"Softmax Regression Model Test Accuracy: {softmax_test_acc:.4f}")
# ----------------------------------------------------
# Model 2: Multilayer Perceptron (MLP) with 1 hidden layer
# ----------------------------------------------------
# This model consists of one hidden Dense layer (e.g., 128 units, ReLU activation)
# followed by the output layer with softmax activation.
mlp_model = tf.keras.models.Sequential([
# Hidden layer with 128 units and ReLU activation.
tf.keras.layers.Dense(128, activation="relu", input_shape=(784,)),
# Output layer with 10 units (for the 10 classes) and softmax activation.
tf.keras.layers.Dense(10, activation="softmax")
])
mlp_model.compile(optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"])
print("\nTraining Multilayer Perceptron Model...")
mlp_history = mlp_model.fit(X_train, y_train, epochs=10, batch_size=128, validation_split=0.1, verbose=2)
# Evaluate the MLP model on the test set.
mlp_test_loss, mlp_test_acc = mlp_model.evaluate(X_test, y_test, verbose=2)
print(f"Multilayer Perceptron Model Test Accuracy: {mlp_test_acc:.4f}")
Explanation
-
Data Preparation:
- We load the MNIST dataset and combine the provided training and test sets.
- The images are normalized by dividing by 255.0 and then reshaped from 28×28 to a 784-length vector.
- We then use
sklearn.model_selection.train_test_split to create our custom 80/20 training/test split.
-
Softmax Regression Model:
- A single Dense layer with 10 units (one per digit) and a softmax activation is used.
- The model is compiled with the Adam optimizer and the
sparse_categorical_crossentropy loss since our labels are integer coded.
- The model is trained for 10 epochs and then evaluated on the test set.
-
Multilayer Perceptron Model:
- The MLP includes one hidden Dense layer with 128 neurons and the ReLU activation.
- The output layer is again Dense with 10 neurons and softmax activation.
- The model is compiled, trained, and evaluated in a similar manner.
You can modify epochs, batch size, and other parameters as needed. Enjoy exploring and experimenting with these models!