Build a Multilayer Perceptron (MLP) to classify handwritten digits in python
Download the MNIST dataset. You can use libraries like TensorFlow or PyTorch to easily access the dataset.
Normalize pixel values to the range [0, 1]. Flatten the 28x28 images into 1D arrays (784 elements).
Split the dataset into training, validation, and test sets. Model Architecture:
You can start with a simple architecture with one input layer, one or more hidden layers, and an output layer. Experiment with different activation functions, such as ReLU for hidden layers and softmax for the output layer.
Choose an appropriate loss function (e.g., categorical crossentropy for multiclass classification).Select an optimizer (e.g., Adam). Choose evaluation metrics (e.g., accuracy).
Train the MLP using the training set.Use the validation set to monitor the model's performance and prevent overfitting.Experiment with different hyperparameters, such as the number of hidden layers, the number of neurons in each layer, learning rate, and batch size.
Evaluate the model on the test set to get a final measure of its performance.Analyze metrics like accuracy, precision, recall, and confusion matrix.
If the model is not performing well, experiment with different architectures, regularization techniques, or optimization algorithms to improve performance.
Visualize the training/validation loss and accuracy over epochs to understand the training process. Visualize some misclassified examples to gain insights into potential improvements.
DEVELOPED BY: JANARTHANAN V K
REG NO: 212222230051
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_accuracy}')
import matplotlib.pyplot as plt
predictions = model.predict(x_test)
plt.figure(figsize=(10, 5))
for i in range(5):
plt.subplot(1, 5, i + 1)
plt.imshow(x_test[i], cmap='gray')
plt.axis('off')
plt.title(f"Predicted: {tf.argmax(predictions[i]).numpy()}\nActual: {y_test[i]}")
plt.show()
Thus, a Multilayer Perceptron (MLP) to classify handwritten digits in python is successfully executed