Okay, here's the Python code using TensorFlow and Keras (its high-level API) to implement both Softmax Regression and a Multilayer Perceptron (MLP) on the MNIST dataset.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
print("TensorFlow version:", tf.__version__)
# --- 1. Load and Preprocess MNIST Data ---
print("\nLoading and preprocessing MNIST data...")
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Normalize pixel values to be between 0 and 1
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# Reshape labels (not strictly needed for SparseCategoricalCrossentropy,
# but good practice to know if using CategoricalCrossentropy)
# y_train = keras.utils.to_categorical(y_train, 10)
# y_test = keras.utils.to_categorical(y_test, 10)
print(f"x_train shape: {x_train.shape}") # (60000, 28, 28)
print(f"y_train shape: {y_train.shape}") # (60000,) - integer labels
print(f"x_test shape: {x_test.shape}") # (10000, 28, 28)
print(f"y_test shape: {y_test.shape}") # (10000,) - integer labels
# --- Hyperparameters ---
BATCH_SIZE = 128
EPOCHS = 10
LEARNING_RATE = 0.01 # Can be adjusted
HIDDEN_UNITS = 128 # For the MLP
# --- 2. Softmax Regression (as a Simple Neural Network) ---
print("\n--- Building Softmax Regression Model ---")
model_softmax = keras.Sequential(
[
keras.Input(shape=(28, 28)), # Input shape for MNIST images
layers.Flatten(), # Flattens the 28x28 image to a 784 vector
layers.Dense(10, activation="softmax") # Output layer with 10 units (0-9 digits)
# Softmax activation for probabilities
],
name="softmax_regression",
)
model_softmax.summary()
print("\n--- Compiling Softmax Regression Model ---")
model_softmax.compile(
loss="sparse_categorical_crossentropy", # Use sparse version for integer labels
optimizer=keras.optimizers.Adam(learning_rate=LEARNING_RATE),
metrics=["accuracy"],
)
print("\n--- Training Softmax Regression Model ---")
history_softmax = model_softmax.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_split=0.1, # Use 10% of training data for validation
verbose=1, # Show progress bar
)
print("\n--- Evaluating Softmax Regression Model ---")
score_softmax = model_softmax.evaluate(x_test, y_test, verbose=0)
print(f"Softmax Regression Test loss: {score_softmax[0]:.4f}")
print(f"Softmax Regression Test accuracy: {score_softmax[1]:.4f}")
# --- 3. Multilayer Perceptron (MLP) with One Hidden Layer ---
print("\n\n--- Building MLP Model ---")
model_mlp = keras.Sequential(
[
keras.Input(shape=(28, 28)), # Input shape
layers.Flatten(), # Flatten the image
layers.Dense(HIDDEN_UNITS, activation="relu"), # Hidden layer with ReLU activation
layers.Dense(10, activation="softmax") # Output layer (same as softmax regression)
],
name="mlp_one_hidden_layer",
)
model_mlp.summary()
print("\n--- Compiling MLP Model ---")
model_mlp.compile(
loss="sparse_categorical_crossentropy",
optimizer=keras.optimizers.Adam(learning_rate=LEARNING_RATE), # Can try different optimizers/LR
metrics=["accuracy"],
)
print("\n--- Training MLP Model ---")
history_mlp = model_mlp.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_split=0.1,
verbose=1,
)
print("\n--- Evaluating MLP Model ---")
score_mlp = model_mlp.evaluate(x_test, y_test, verbose=0)
print(f"MLP Test loss: {score_mlp[0]:.4f}")
print(f"MLP Test accuracy: {score_mlp[1]:.4f}")
# --- 4. (Optional) Visualize Training History ---
def plot_history(histories, names, key='accuracy'):
plt.figure(figsize=(10,6))
for history, name in zip(histories, names):
val = plt.plot(history.epoch, history.history['val_'+key],
'--', label=name.title()+' Val')
plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
label=name.title()+' Train')
plt.xlabel('Epochs')
plt.ylabel(key.replace('_',' ').title())
plt.legend()
plt.grid(True)
plt.show()
print("\nPlotting training histories...")
plot_history([history_softmax, history_mlp], ['Softmax', 'MLP'], key='accuracy')
plot_history([history_softmax, history_mlp], ['Softmax', 'MLP'], key='loss')
print("\nScript finished.")
Explanation:
- Imports: Import necessary libraries:
tensorflow, keras, layers, numpy, and matplotlib.
- Load Data:
keras.datasets.mnist.load_data() downloads and loads the MNIST dataset into training and testing sets (x_train, y_train, x_test, y_test).
- Preprocess Data:
- Normalization: Pixel values (0-255) are scaled to the range [0, 1] by dividing by 255.0. This helps the models train more effectively. We ensure the type is float first.
- Labels: The labels (
y_train, y_test) are already integers from 0 to 9. We use "sparse_categorical_crossentropy" as the loss function, which is designed to work directly with integer labels, so we don't need to one-hot encode them with keras.utils.to_categorical. (If you were using "categorical_crossentropy", you would need to uncomment the to_categorical lines).
- Hyperparameters: Define key training parameters like batch size, epochs, and learning rate.
- Softmax Regression Model:
- A
keras.Sequential model is created.
keras.Input(shape=(28, 28)): Defines the expected input shape (a 28x28 grayscale image).
layers.Flatten(): Converts the 2D image (28x28) into a 1D vector (784 elements). This is necessary for the Dense layer.
layers.Dense(10, activation="softmax"): The core of softmax regression. It's a single fully connected layer with 10 output units (one for each digit). The softmax activation function ensures the outputs are probabilities that sum to 1, suitable for multi-class classification.
model.summary(): Prints a summary of the model's layers and parameters.
model.compile(): Configures the model for training.
loss: Specifies the loss function (sparse_categorical_crossentropy for integer labels).
optimizer: Sets the optimization algorithm (Adam is a common and effective choice).
metrics: Defines metrics to evaluate during training and testing (accuracy).
- : Trains the model on the training data (, ).
This code provides a clear implementation of both requested models, trains them on MNIST, evaluates their performance, and optionally visualizes the training process.