The Wayback Machine - https://web.archive.org/web/20240908110802/https://www.geeksforgeeks.org/sms-spam-detection-using-tensorflow-in-python/
Open In App

SMS Spam Detection using TensorFlow in Python

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In today’s society, practically everyone has a mobile phone, and they all get communications (SMS/ email) on their phone regularly. But the essential point is that majority of the messages received will be spam, with only a few being ham or necessary communications. Scammers create fraudulent text messages to deceive you into giving them your personal information, such as your password, account number, or Social Security number. If they have such information, they may be able to gain access to your email, bank, or other accounts.

In this article, we are going to develop various deep learning models using Tensorflow for SMS spam detection and also analyze the performance metrics of different models.

We will be using  SMS Spam Detection Dataset, which contains SMS text and corresponding label (Ham or spam)

Implementation

We will import all the required libraries

Python3




import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers


Load the Dataset using pandas function .read_csv()

Python3




# Reading the data
df = pd.read_csv("/content/spam.csv",encoding='latin-1')
df.head()


Lets, Understand the data

 

As we can see that the dataset contains three unnamed columns with null values. So we drop those columns and rename the columns v1 and v2 to label and Text, respectively. Since the target variable is in string form, we will encode it numerically using pandas function .map().

Python3




df = df.drop(['Unnamed: 2','Unnamed: 3','Unnamed: 4'],axis=1)
df = df.rename(columns={'v1':'label','v2':'Text'})
df['label_enc'] = df['label'].map({'ham':0,'spam':1})
df.head()


Output after the above data preprocessing.

 

Let’s visualize the distribution of Ham and Spam data.

Python3




sns.countplot(x=df['label'])
plt.show()


 

The ham data is comparatively higher than spam data, it’s natural. Since we are going to use embeddings in our deep learning model, we need not balance the data. Now, let’s find the average number of words in all the sentences in SMS data.

Python3




# Find average number of tokens in all sentences
avg_words_len=round(sum([len(i.split()) for i in df['Text']])/len(df['Text']))
print(avg_words_len)


Output

Average number of words in each sentence in SMS data

Now, let’s find the total number of unique words in the corpus

Python3




# Finding Total no of unique words in corpus
s = set()
for sent in df['Text']:
  for word in sent.split():
    s.add(word)
total_words_length=len(s)
print(total_words_length)


 

Now,  splitting the data into training and testing parts using train_test_split() function.

Python3




# Splitting data for Training and testing
from sklearn.model_selection import train_test_split
  
X, y = np.asanyarray(df['Text']), np.asanyarray(df['label_enc'])
new_df = pd.DataFrame({'Text': X, 'label': y})
X_train, X_test, y_train, y_test = train_test_split(
    new_df['Text'], new_df['label'], test_size=0.2, random_state=42)
X_train.shape, y_train.shape, X_test.shape, y_test.shape


Shape of train and test data

 

Building the models

First, we will build a baseline model and then we’ll try to beat the performance of the baseline model using deep learning models (embeddings, LSTM, etc)

Here, we will choose MultinomialNB(), which performs well for text classification when the features are discrete like word counts of the words or tf-idf vectors. The tf-idf is a measure that tells how important or relevant a word is the document.

Python3




from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report,accuracy_score
  
tfidf_vec = TfidfVectorizer().fit(X_train)
X_train_vec,X_test_vec = tfidf_vec.transform(X_train),tfidf_vec.transform(X_test)
  
baseline_model = MultinomialNB()
baseline_model.fit(X_train_vec,y_train)


Performance of baseline model

 

Confusion matrix for the baseline model

 

Model 1: Creating custom Text vectorization and embedding layers:

Text vectorization is the process of converting text into a numerical representation. Example: Bag of words frequency, Binary Term frequency, etc.;

A word embedding is a learned representation of text in which words with related meanings have similar representations. Each word is assigned to a single vector, and the vector values are learned like that of a neural network.

Now, we’ll create a custom text vectorization layer using TensorFlow.

Python3




from tensorflow.keras.layers import TextVectorization
  
MAXTOKENS=total_words_length
OUTPUTLEN=avg_words_len
  
text_vec = TextVectorization(
    max_tokens=MAXTOKENS,
    standardize='lower_and_strip_punctuation',
    output_mode='int',
    output_sequence_length=OUTPUTLEN
)
text_vec.adapt(X_train)


  • MAXTOKENS is the maximum size of the vocabulary which was found earlier
  • OUTPUTLEN is the length to which the sentences should be padded irrespective of the sentence length.

Output of a sample sentence using text vectorization is shown below:

 

Now let’s create an embedding layer

Python3




embedding_layer = layers.Embedding(
    input_dim=MAXTOKENS,
    output_dim=128,
    embeddings_initializer='uniform',
    input_length=OUTPUTLEN
)


  • input_dim is the size of vocabulary
  • output_dim is the dimension of the embedding layer i.e, the size of the vector in which the words will be embedded
  • input_length is the length of input sequences

Now, let’s build and compile model 1 using the Tensorflow Functional API

Python3




input_layer = layers.Input(shape=(1,), dtype=tf.string)
vec_layer = text_vec(input_layer)
embedding_layer_model = embedding_layer(vec_layer)
x = layers.GlobalAveragePooling1D()(embedding_layer_model)
x = layers.Flatten()(x)
x = layers.Dense(32, activation='relu')(x)
output_layer = layers.Dense(1, activation='sigmoid')(x)
model_1 = keras.Model(input_layer, output_layer)
  
model_1.compile(optimizer='adam', loss=keras.losses.BinaryCrossentropy(
    label_smoothing=0.5), metrics=['accuracy'])


Summary of the model 1

 

Training the model-1

 

Plotting the history of model-1

 

Let’s create helper functions for compiling, fitting, and evaluating the model performance.

Python3




from sklearn.metrics import precision_score, recall_score, f1_score
  
def compile_model(model):
    '''
    simply compile the model with adam optimzer
    '''
    model.compile(optimizer=keras.optimizers.Adam(),
                  loss=keras.losses.BinaryCrossentropy(),
                  metrics=['accuracy'])
  
def fit_model(model, epochs, X_train=X_train, y_train=y_train,
              X_test=X_test, y_test=y_test):
    '''
    fit the model with given epochs, train 
    and test data
    '''
    history = model.fit(X_train,
                        y_train,
                        epochs=epochs,
                        validation_data=(X_test, y_test),
                        validation_steps=int(0.2*len(X_test)))
    return history
  
def evaluate_model(model, X, y):
    '''
    evaluate the model and returns accuracy, 
    precision, recall and f1-score 
    '''
    y_preds = np.round(model.predict(X))
    accuracy = accuracy_score(y, y_preds)
    precision = precision_score(y, y_preds)
    recall = recall_score(y, y_preds)
    f1 = f1_score(y, y_preds)
  
    model_results_dict = {'accuracy': accuracy,
                          'precision': precision,
                          'recall': recall,
                          'f1-score': f1}
  
    return model_results_dict


Model -2 Bidirectional LSTM

A bidirectional LSTM (Long short-term memory) is made up of two LSTMs, one accepting input in one direction and the other in the other. BiLSTMs effectively improve the network’s accessible information, boosting the context for the algorithm (e.g. knowing what words immediately follow and precede a word in a sentence).

Building and compiling the model-2

Python3




input_layer = layers.Input(shape=(1,), dtype=tf.string)
vec_layer = text_vec(input_layer)
embedding_layer_model = embedding_layer(vec_layer)
bi_lstm = layers.Bidirectional(layers.LSTM(
    64, activation='tanh', return_sequences=True))(embedding_layer_model)
lstm = layers.Bidirectional(layers.LSTM(64))(bi_lstm)
flatten = layers.Flatten()(lstm)
dropout = layers.Dropout(.1)(flatten)
x = layers.Dense(32, activation='relu')(dropout)
output_layer = layers.Dense(1, activation='sigmoid')(x)
model_2 = keras.Model(input_layer, output_layer)
  
compile_model(model_2)  # compile the model
history_2 = fit_model(model_2, epochs=5)  # fit the model


Training the model

 

Model -3 Transfer Learning with USE Encoder

Transfer Learning

Transfer learning is a machine learning approach in which a model generated for one job is utilized as the foundation for a model on a different task.

USE Layer (Universal Sentence Encoder)

The Universal Sentence Encoder converts text into high-dimensional vectors that may be used for text categorization, semantic similarity, and other natural language applications.

The USE can be downloaded from tensorflow_hub and can be used as a layer using .kerasLayer() function.

Python3




import tensorflow_hub as hub
  
# model with Sequential api
model_3 = keras.Sequential()
  
# universal-sentence-encoder layer 
# directly from tfhub
                           trainable=False,
                           input_shape=[],
                           dtype=tf.string,
                           name='USE')
model_3.add(use_layer)
model_3.add(layers.Dropout(0.2))
model_3.add(layers.Dense(64, activation=keras.activations.relu))
model_3.add(layers.Dense(1, activation=keras.activations.sigmoid))
  
compile_model(model_3)
  
history_3 = fit_model(model_3, epochs=5)


Compiling and training the model

Training model with USE

Analyzing our Model Performance

We will use the helper function which we created earlier to evaluate model performance.

Python3




baseline_model_results = evaluate_model(baseline_model, X_test_vec, y_test)
model_1_results = evaluate_model(model_1, X_test, y_test)
model_2_results = evaluate_model(model_2, X_test, y_test)
model_3_results = evaluate_model(model_3, X_test, y_test)
  
total_results = pd.DataFrame({'MultinomialNB Model':baseline_model_results,
                             'Custom-Vec-Embedding Model':model_1_results,
                             'Bidirectional-LSTM Model':model_2_results,
                             'USE-Transfer learning Model':model_3_results}).transpose()
  
total_results


Output

 

Plotting the results

 

Metrics

All four models deliver excellent results. (All of them have greater than 96 percent accuracy), thus comparing them might be difficult.

Problem

We have an unbalanced dataset; most of our data points contain the label “ham,” which is natural because most SMS are ham. Accuracy cannot be an appropriate metric in certain situations. Other measurements are required.

Which metric is better?

  • False negative and false positive are significant in this problem. Precision and recall are the metrics that allow us the ability to calculate them, but there is one more, ‘f1-score.’
  • The f1-score is the harmonic mean of accuracy and recall. Thus, we can get both with a single shot.
  • USE-Transfer learning model gives the best accuracy and f1-score.


Previous Article
Next Article

Similar Reads

Email Spam Detection using Catboost
In today's digital age, email remains one of the most widely used communication mediums. However, the prevalence of spam emails poses significant challenges for both individuals and organizations. Spam emails not only clutter inboxes but can also contain malicious links or attachments that pose security risks. To combat this, machine learning techn
9 min read
Top 10 AI Tools for Text Spam Detection
Artificial Intelligence (AI) has changed many aspects of our digital lives, including how we handle and filter spam. Spam has always been a big problem for many. It can take different forms, but a common type of spam is the message that we get in our email SPAM section. To detect these messages, it is necessary to have a Spam detector. It is a cruc
8 min read
Detecting Spam Emails Using Tensorflow in Python
Spam messages refer to unsolicited or unwanted messages/emails that are sent in bulk to users. In most messaging/emailing services, messages are detected as spam automatically so that these messages do not unnecessarily flood the users' inboxes. These messages are usually promotional and peculiar in nature. Thus, it is possible for us to build ML/D
8 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Spam Classification using OpenAI
The majority of people in today's society own a mobile phone, and they all frequently get communications (SMS/email) on their phones. But the key point is that some of the messages you get may be spam, with very few being genuine or important interactions. You may be tricked into providing your personal information, such as your password, account n
6 min read
Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read
Sobel Edge Detection vs. Canny Edge Detection in Computer Vision
Both Sobel and Canny algorithms are popular methods for edge detection in images, but they are suited for different purposes based on their characteristics and the nature of the application. Understanding when to use each can help you achieve better results for specific tasks in image processing. In this article, we are going to explore the differe
9 min read
FaceMask Detection using TensorFlow in Python
In this article, we’ll discuss our two-phase COVID-19 face mask detector, detailing how our computer vision/deep learning pipeline will be implemented. We’ll use this Python script to train a face mask detector and review the results. Given the trained COVID-19 face mask detector, we’ll proceed to implement two more additional Python scripts used t
9 min read
Fake News Detection Model using TensorFlow in Python
Fake News means incorporating information that leads people to the wrong paths. It can have real-world adverse effects that aim to intentionally deceive, gain attention, manipulate public opinion, or damage reputation. It is necessary to detect fake news mainly for media outlets to have the ability to attract viewers to their website to generate on
4 min read
Object Detection using TensorFlow
Identifying and detecting objects within images or videos is a key task in computer vision. It is critical in a variety of applications, ranging from autonomous vehicles and surveillance systems to augmented reality and medical imaging. TensorFlow, a Google open-source machine learning framework, provides a robust collection of tools for developing
7 min read
Object Detection by YOLO using Tensorflow
You Only Look Once (YOLO) is an extremely fast and accurate, real-time, state-of-the-art object-detecting technology. In this article, using Tensorflow 2.0, we will implement YOLO from scratch. A key component of computer vision is object detection, and our implementation uses TensorFlow to create the cutting-edge object detection model YOLOv3. Obj
15+ min read
Real-Time Object Detection Using TensorFlow
In November 2015, Google's deep artificial intelligence research division introduced TensorFlow, a cutting-edge machine learning library initially designed for internal purposes. This open-source library revolutionized the field, which helped researchers and developers in building, training, and deploying machine learning models. With TensorFlow, t
11 min read
ML | Training Image Classifier using Tensorflow Object Detection API
This article aims to learn how to build an object detector using Tensorflow's object detection API. Requirement :  Python ProgrammingBasics of Machine LearningBasics of neural networks (Not Mandatory)An enthusiasm to build a Cool project(Mandatory) :pEven though if you don't have the first three essentials, you're welcome to the adventure. Don't wo
11 min read
Skin Cancer Detection using TensorFlow
In this article, we will learn how to implement a Skin Cancer Detection model using Tensorflow. We will use a dataset that contains images for the two categories that are malignant or benign. We will use the transfer learning technique to achieve better results in less amount of training. We will use EfficientNet architecture as the backbone of our
5 min read
Region Proposal Object Detection with OpenCV, Keras, and TensorFlow
In this article, we'll learn how to implement Region proposal object detection with OpenCV, Keras and TensorFlow. Install all the dependencies Use the pip command for installing all the dependencies pip install tensorflow keras imutils pip install opencv-contrib-python Note: Make sure about installing the above OpenCV package otherwise you might fa
9 min read
Anomaly detection with TensorFlow
With the advancement of technology there is also a signification increment of frauds. In modern days, frauds are very common in monetary departments. Let's assume we have an efficient algorithm which observes data flow actions, learns the patterns and can even predict which are the anomalies or frauds. This efficient algorithm can be the autoencode
7 min read
Main Loopholes in TensorFlow - Tensorflow Security
TensorFlow is an open-source machine-learning framework widely used for building, training, and deploying machine-learning models. Despite its popularity and versatility, TensorFlow is not immune to security vulnerabilities and loopholes. Some of the common security loopholes in TensorFlow are related to data privacy, session hijacking, and lack of
6 min read
Why TensorFlow is So Popular - Tensorflow Features
In this article, we will see Why TensorFlow Is So Popular, and then explore Tensorflow Features. TensorFlow is an open-source software library. It was originally developed by researchers and engineers working on the Google Brain Team within Google’s Machine Intelligence research organization for the purposes of conducting machine learning and deep
3 min read
Tensorflow 1.xvs. Tensorflow 2.x: What's the Difference?
TensorFlow is an end-to-end open-source machine learning platform that contains comprehensive tools, libraries and community resources. It is meant for developers, data scientists and researchers to build and deploy applications powered by machine learning. TensorFlow was essentially built to scale, developed by Google Brain team, TensorFlow accele
6 min read
How to migrate from TensorFlow 1.x to TensorFlow 2.x
The introduction of TensorFlow 2. x marks a significant advance in the strong open-source machine learning toolkit TensorFlow. TensorFlow 2.0 introduces significant API changes, making manual code upgrades tedious and error prone. TensorFlow 2. x places an emphasis on user-friendliness and optimizes the development process, whereas TensorFlow 1. x
7 min read
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
Online Payment Fraud Detection using Machine Learning in Python
As we are approaching modernity, the trend of paying online is increasing tremendously. It is very beneficial for the buyer to pay online as it saves time, and solves the problem of free money. Also, we do not need to carry cash with us. But we all know that Good thing are accompanied by bad things. The online payment method leads to fraud that can
5 min read
Pneumonia Detection Using CNN in Python
In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify the images of patient's xray to detect whether the patient is Normal or affected by Pneumonia. To get more understanding, follow the steps accordingly. Importing Libraries The libraries we will using are : Pandas- The pandas library
10 min read
Plagiarism Detection using Python
In this article, we are going to learn how to check plagiarism using Python. Plagiarism: Plagiarism basically refers to cheating. It means stealing someone's else work, ideas, or information from the resources without providing the necessary credits to the author. For example, copying text from different resources from word to word without mentioni
10 min read
Age and Gender Detection Using OpenCV in Python
In this article, we will discuss the process of creating an Age and Gender Predictor using OpenCV.  Let's divide the task into 2 parts:  Age prediction - The prediction will be in the form of categories where categories are a few age intervals like  0-6,18-25, etc.Gender prediction - The prediction is a classifier based where categories are Male an
3 min read
Emotion Detection using Bidirectional LSTM
Emotion Detection is one of the hottest topics in research nowadays. Emotion-sensing technology can facilitate communication between machines and humans. It will also help to improve the decision-making process. Many Machine Learning Models have been proposed to recognize emotions from the text. But, in this article, our focus is on the Bidirection
10 min read
Yawn Detection using OpenCV and Dlib
In this article, we'll cover all the steps required to build a Yawn detection program using OpenCV and dlib packages. But before doing this project should be familiar with the basics of OpenCV and you should also know how to use face detection and landmark detection using dlib module. Requirements: Dlib library installed Dlib face landmark '.dat' f
2 min read
Age Detection using Deep Learning in OpenCV
In this tutorial, we are going to see the entire process of creating an Age predictor and Gender classifier project using OpenCV. Age Detection Our goal here is to create a program that will predict the gender and age of the person using an image. But predicting age might not be as simple as you think, why? You might be thinking that age prediction
5 min read
Face Detection in Flutter using Firebase ML Kit
Face detection is a technique by which we can locate the human faces in the image given. Face detection is used in many places nowadays, especially websites hosting images like Picasa, Photobucket, and Facebook. The automatic tagging feature adds a new dimension to sharing pictures among the people who are in the picture and also gives the idea to
5 min read