MLP Classifier Lab with scikit-learn
MLP Classifier Lab with scikit-learn
Now, we'll proceed to use scikit-learn's MLPClassifier to build the MLP model.
# Define the MLP model with two hidden layers (128, 64 neurons)
mlp = MLPClassifier(hidden_layer_sizes=(128, 64), activation='relu', solver='adam',
max_iter=200, random_state=42)
3. Train the MLP Model: Fit the model on the training dataset. Since MLPClassifier
doesn’t require one-hot encoding for the target labels, you can use the original
integer-encoded labels.
# Make predictions
y_pred_mlp = [Link](X_test)
# Evaluate the model
from [Link] import classification_report, confusion_matrix
# Print classification report
print('Classification Report (MLP Classifier):\n',
classification_report(y_test.argmax(axis=1), y_pred_mlp))
# Confusion matrix
cm_mlp = confusion_matrix(y_test.argmax(axis=1), y_pred_mlp)
print('Confusion Matrix (MLP Classifier):\n', cm_mlp)
5. Visualize the Confusion Matrix: Visualize the confusion matrix as a heatmap to
better understand where the model performed well and where it struggled.
o Adjust the number of hidden layers, learning rate, and regularization to see
how they impact the model’s performance.
o You can also experiment with different solvers such as sgd for gradient
descent.
3. Training Time:
o Note that MLPClassifier can take more time to train compared to other
models like Logistic Regression or k-NN. Discuss trade-offs between
accuracy and computation time.
Bonus Challenges
• Early Stopping: Enable early stopping to prevent overfitting by adding
early_stopping=True to the MLPClassifier.
• Learning Curves: Plot the loss curve to understand how well the model converged.
Objective
The objective of this lab is to study a fundamental property of static neural networks (non-
recurrent): sparse approximation. We will do this by training a Multi-Layer Perceptron
(MLP) with one hidden layer on a piecewise-defined function and analyze how the network
approximates the function.
𝑠𝑖𝑛(𝜋 𝑥) 𝑖𝑓 𝑥 ∈ ] − 1, 1 [
𝑓(𝑥) = {
0 𝑖𝑓 𝑥 ∈ [−2, −1] ∪ [1, 2]
You can use the following Python code to generate the data:
import numpy as np
# Function definition
def f(x):
if -1 < x < 1:
return [Link]([Link] * x)
else:
return 0
# Generate data
[Link](42)
x_train = [Link](-2, 2, 1000)
y_train = [Link]([f(x) + [Link](0, 0.2) for x in x_train])
You can use the following Python code with TensorFlow to implement the MLP:
import tensorflow as tf
from [Link] import layers, models
# Model definition
model = [Link]()
[Link]([Link](10, activation='tanh', input_shape=(1,))) # Hidden layer with
tanh
[Link]([Link](1)) # Output layer with no activation function
Recommendations
1. Start with a small number of neurons (e.g., 1, 3, 5, 7 neurons in the hidden layer) and
observe the results.
2. Explore variations in the number of neurons in the hidden layer to see how sparse
approximation changes with model capacity.
3. Test the generalization of the model by evaluating its performance on the test set.