Here's Python code using TensorFlow to implement both:
- A softmax regression model (logistic regression using softmax) using tf.keras.Sequential.
- A multilayer perceptron (MLP) with one hidden layer.
We'll use the MNIST dataset, which is available directly via TensorFlow.
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# Load and preprocess the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize the input images to [0, 1] range
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# Flatten the 28x28 images into vectors of size 784
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)
# Convert labels to one-hot encoding
y_train_cat = to_categorical(y_train, 10)
y_test_cat = to_categorical(y_test, 10)
# 1. Softmax Regression Model
softmax_model = models.Sequential([
layers.Input(shape=(784,)),
layers.Dense(10, activation='softmax')
])
softmax_model.compile(optimizer='sgd',
loss='categorical_crossentropy',
metrics=['accuracy'])
print("Training Softmax Regression Model...")
softmax_model.fit(x_train, y_train_cat, epochs=10, batch_size=32, validation_split=0.1)
# Evaluate on test data
test_loss, test_acc = softmax_model.evaluate(x_test, y_test_cat)
print(f"Softmax Regression Test Accuracy: {test_acc:.4f}")
# 2. Multilayer Perceptron (MLP) with One Hidden Layer
mlp_model = models.Sequential([
layers.Input(shape=(784,)),
layers.Dense(128, activation='relu'),
layers.Dense(10, activation='softmax')
])
mlp_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
print("\nTraining MLP Model...")
mlp_model.fit(x_train, y_train_cat, epochs=10, batch_size=32, validation_split=0.1)
# Evaluate on test data
test_loss, test_acc = mlp_model.evaluate(x_test, y_test_cat)
print(f"MLP Test Accuracy: {test_acc:.4f}")
📝 Notes:
- The softmax regression model is a single Dense layer with softmax activation.
- The MLP model adds a hidden Dense layer with ReLU activation before the output layer.
- We use categorical crossentropy loss and one-hot encoded labels.
- You can adjust the number of epochs, batch size, and hidden layer size as needed.
Let me know if you want to visualize training curves or confusion matrices!