About
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt
Step 2: Load and Preprocess Data
mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images, test_images = train_images / 255.0, test_images / 255.0
Step 3: Single-Layer Perceptron
model_single_layer = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(10, activation='softmax') ])
model_single_layer.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model_single_layer.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
test_loss, test_accuracy = model_single_layer.evaluate(test_images, test_labels) print(f"Single-Layer Perceptron - Test Accuracy: {test_accuracy}")
Step 4: Multi-Layer Perceptron (MLP)
model_mlp = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ])
model_mlp.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model_mlp.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
test_loss, test_accuracy = model_mlp.evaluate(test_images, test_labels) print(f"Multi-Layer Perceptron (MLP) - Test Accuracy: {test_accuracy}")
Step 7: Visualize Results
num_samples = 5 random_indices = np.random.randint(0, len(test_images), num_samples) random_images = test_images[random_indices] random_labels = test_labels[random_indices]
Single-Layer Perceptron predictions
single_layer_predictions = model_single_layer.predict(random_images) single_layer_predicted_labels = np.argmax(single_layer_predictions, axis=1)
Multi-Layer Perceptron predictions
mlp_predictions = model_mlp.predict(random_images) mlp_predicted_labels = np.argmax(mlp_predictions, axis=1)
Display the images and predictions
plt.figure(figsize=(12, 6)) for i in range(num_samples): plt.subplot(2, num_samples, i + 1) plt.imshow(random_images[i], cmap='gray') plt.title(f'True: {random_labels[i]}') plt.axis('off')
plt.subplot(2, num_samples, i + 1 + num_samples)
plt.bar(range(10), single_layer_predictions[i])
plt.title(f'Pred (Single): {single_layer_predicted_labels[i]}')
plt.xticks(range(10))
plt.tight_layout() plt.show()