avatarNaina Chaturvedi

Summary

The web content provides a comprehensive guide on implementing a Multilayer Perceptron (MLP) with Keras for topic classification, alongside showcasing a variety of data science and machine learning projects and resources available for learning and implementation.

Abstract

The article delves into the concept of Multilayer Perceptron (MLP), explaining it as a fundamental deep learning model that maps inputs to outputs through a series of layers. It offers a step-by-step tutorial on building an MLP model using the Keras library within the TensorFlow ecosystem, including data preprocessing, model creation, training, and evaluation on the Reuters dataset. The author emphasizes practical learning by providing code snippets and visualizations of training and validation metrics. Additionally, the article promotes a curated list of other educational series and projects in data science, machine learning, and related fields, available through various mediums such as Medium posts, YouTube videos, and newsletters. The content aims to cater to both beginners and experienced practitioners by covering a wide range of topics, including natural language processing, data engineering, system design, and more. The author encourages continuous learning and engagement with the community through subscriptions to newsletters and YouTube channels.

Opinions

  • The author values hands-on experience, as evidenced by the inclusion of a practical MLP implementation project.
  • There is an emphasis on the importance of a comprehensive education in data science and machine learning, as shown by the extensive list of related projects and series.
  • The author believes in the power of community and shared knowledge, suggesting readers to follow their YouTube channel and newsletter for more insights and project implementations.
  • The use of Keras and TensorFlow for the MLP project indicates a preference or recommendation for these libraries for neural network implementation.
  • The article conveys enthusiasm and encouragement for readers to pursue their interests in tech, data science, and machine learning, as seen in the motivational quote by Steve Jobs at the end.

Day 48: 60 days of Data Science and Machine Learning Series

Multilayer Perceptron with project…

Pic credits : ResearchGate

Multilayer Perceptron is basically ( or a class of ) a feedforward artificial neural network which is composed of an input layer to receive the signal, an output layer that makes a decision or prediction about the input, and an arbitrary number of hidden layers for the computation. They provide a nonlinear mapping between the input layer and a corresponding output layer. They are like “hello world” of deep learning.

Some of the other best Series —

30 Days of Natural Language Processing ( NLP) Series

30 days of Data Engineering with projects Series

60 days of Data Science and ML Series with projects

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

30 days of Machine Learning Ops

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

A good introduction about MLP can be found ( at link below) —

In this project we are going to implement a multilayer Perceptron model with Keras.

Let’s dive in!

Import Necessary Libraries

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
import tensorflow as tf
from tensorflow.keras.datasets import reuters
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation
from tensorflow.keras.preprocessing.text import Tokenizer

Load Dataset

( x_train, y_train), (x_test,y_test) = reuters.load_data(num_words=10000,test_split=0.2)
print(len(x_train))
print(len(x_test))
num_classes = np.max(y_train) +1
print(num_classes)

Output —

8982
2246
46

Vectorize and One-hot Encoding

tokenizer = Tokenizer(num_words=10000)
x_train = tokenizer.sequences_to_matrix(x_train,mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test,mode='binary')
y_train = tf.keras.utils.to_categorical(y_train,num_classes)
y_test = tf.keras.utils.to_categorical(y_test,num_classes)
x_train.shape,x_test.shape
y_train.shape, y_test.shape

Output —

((8982, 10000), (2246, 10000))
((8982, 46), (2246, 46))

Build Multilayer Perceptron Model

model = Sequential([
    Dense(512,input_shape = (10000,)),
    Activation('relu'),
    Dropout(0.5),
    Dense(num_classes),
    Activation('softmax')
    
    
])
model.summary()

Output —

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 512)               5120512   
_________________________________________________________________
activation (Activation)      (None, 512)               0         
_________________________________________________________________
dropout (Dropout)            (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 46)                23598     
_________________________________________________________________
activation_1 (Activation)    (None, 46)                0         
=================================================================
Total params: 5,144,110
Trainable params: 5,144,110
Non-trainable params: 0
_________________________________________________________________

Train Model

from tensorflow.keras.callbacks import EarlyStopping
es = EarlyStopping(monitor = 'val_loss',patience=3,verbose=1,mode='min')
model.compile(optimizer ='adam',
             loss= 'categorical_crossentropy',
             metrics = ['accuracy'])
h = model.fit(x_train, y_train,
             epochs=100,
             batch_size=32,
             validation_split=0.1,
             callbacks=[es])

Output —

Train on 8083 samples, validate on 899 samples
Epoch 1/100
8083/8083 [==============================] - 9s 1ms/sample - loss: 1.3059 - accuracy: 0.7185 - val_loss: 0.9727 - val_accuracy: 0.7931
Epoch 2/100
8083/8083 [==============================] - 8s 1ms/sample - loss: 0.5040 - accuracy: 0.8898 - val_loss: 0.8712 - val_accuracy: 0.8098
Epoch 3/100
8083/8083 [==============================] - 9s 1ms/sample - loss: 0.2806 - accuracy: 0.9352 - val_loss: 0.9423 - val_accuracy: 0.7976
Epoch 4/100
8083/8083 [==============================] - 9s 1ms/sample - loss: 0.2328 - accuracy: 0.9478 - val_loss: 0.9777 - val_accuracy: 0.8053
Epoch 5/100
8083/8083 [==============================] - 10s 1ms/sample - loss: 0.1925 - accuracy: 0.9522 - val_loss: 1.0022 - val_accuracy: 0.8076
Epoch 00005: early stopping

Evaluate Model

model.evaluate(x_test,y_test,batch_size=32,verbose=1)

Output —

2246/2246 [==============================] - 1s 516us/sample - loss: 0.9245 - accuracy: 0.8077
[0.9245196666870389, 0.8076581]

Training and Validation Accuracy

plt.plot(h.history['accuracy'],label='Training Accuracy')
plt.plot(h.history['val_accuracy'],label = 'Validation Accuracy')
plt.title('Taining and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

Output —

Training and Validation Loss

plt.plot(h.history['loss'],label='Training Loss')
plt.plot(h.history['val_loss'],label = 'Validation loss')
plt.title('Taining and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

Output —

Learnings —

How to build and train a multilayer perceptron and perform topic classification with Keras

Day 49: Coming soon!

Follow and Stay tuned. Keep coding :)

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

That’s it fellas. Peace out and keep coding :)

Stay Tuned and of-course let me end this post with a quote by Steve Jobs ;)

“Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it.”

Machine Learning
Artificial Intelligence
Programming
Tech
Data Science
Recommended from ReadMedium