Below is the Python code using TensorFlow to implement both softmax regression and a multilayer perceptron (MLP) with one hidden layer on the MNIST dataset. The dataset is split into 80/20 for training and testing.
import tensorflow as tf
from tensorflow.keras import layers, models
from sklearn.model_selection import train_test_split
import numpy as np
# Load MNIST dataset
(x, y), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalize the data to the range [0, 1]
x = x.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# Flatten the images (28x28 -> 784)
x = x.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)
# Perform an 80/20 train/test split
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=42)
# Convert labels to one-hot encoding
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_val = tf.keras.utils.to_categorical(y_val, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 1. Softmax Regression (implemented as a neural network using models.Sequential)
def build_softmax_regression_model():
model = models.Sequential([
layers.Input(shape=(784,)), # Input layer
layers.Dense(10, activation='softmax') # Output layer with softmax activation
])
return model
# Compile and train the softmax regression model
softmax_model = build_softmax_regression_model()
softmax_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
softmax_model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=10, batch_size=32)
# Evaluate the softmax regression model
softmax_test_loss, softmax_test_acc = softmax_model.evaluate(x_test, y_test)
print(f"Softmax Regression Test Accuracy: {softmax_test_acc:.4f}")
# 2. Multilayer Perceptron (MLP) with one hidden layer
def build_mlp_model():
model = models.Sequential([
layers.Input(shape=(784,)), # Input layer
layers.Dense(128, activation='relu'), # Hidden layer with 128 neurons and ReLU activation
layers.Dense(10, activation='softmax') # Output layer with softmax activation
])
return model
# Compile and train the MLP model
mlp_model = build_mlp_model()
mlp_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
mlp_model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=10, batch_size=32)
# Evaluate the MLP model
mlp_test_loss, mlp_test_acc = mlp_model.evaluate(x_test, y_test)
print(f"MLP Test Accuracy: {mlp_test_acc:.4f}")
Explanation:
-
Softmax Regression:
- A single dense layer with 10 neurons (one for each digit class) and a softmax activation function is used.
- The model is trained using the Adam optimizer and categorical cross-entropy loss.
-
Multilayer Perceptron (MLP):
- A dense hidden layer with 128 neurons and ReLU activation is added before the output layer.
- The output layer is the same as in softmax regression (10 neurons with softmax activation).
-
Data Preprocessing:
- The MNIST images are normalized to the range [0, 1].
- The images are flattened from 28x28 to 784-dimensional vectors.
- Labels are one-hot encoded for categorical cross-entropy loss.
-
Training and Evaluation:
- Both models are trained for 10 epochs with a batch size of 32.
- Validation accuracy is monitored during training.
- The test accuracy is printed after evaluation on the test set.
Let me know if you need further clarification!