Below is the Python code using TensorFlow to implement softmax regression and a multilayer perceptron (MLP) with one hidden layer on the MNIST dataset, with an 80/20 train/test split. The code includes a basic visualization of some MNIST elements and uses SGD as the optimizer.
import tensorflow as tf
from tensorflow.keras import layers, models
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
# Load MNIST dataset
(x, y), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Basic visualization of some MNIST elements
def visualize_mnist(x_data, y_data, num_samples=5):
plt.figure(figsize=(10, 2))
for i in range(num_samples):
plt.subplot(1, num_samples, i + 1)
plt.imshow(x_data[i], cmap='gray')
plt.title(f"Label: {y_data[i]}")
plt.axis('off')
plt.show()
# Visualize some training samples
visualize_mnist(x, y)
# 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 using SGD
softmax_model = build_softmax_regression_model()
softmax_model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),
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 using SGD
mlp_model = build_mlp_model()
mlp_model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),
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:
-
Visualization:
- The
visualize_mnist function displays the first 5 images from the training set along with their corresponding labels using matplotlib.
- This provides a basic visual understanding of the MNIST dataset.
-
Softmax Regression:
- A single dense layer with 10 neurons (one for each digit class) and a softmax activation function is used.
- The model is compiled with the SGD optimizer (learning rate = 0.01) 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).
- The model is compiled with the SGD optimizer (learning rate = 0.01) and categorical cross-entropy loss.
-
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.
Notes:
- Using SGD instead of Adam may result in slower convergence and potentially lower accuracy, but it is implemented as requested.
- You can adjust the learning rate (
learning_rate) or the number of epochs to improve performance if needed.
Let me know if you need further clarification or modifications!