Nowadays, many e-mail are being sent and many of them are spam e-mails. In this tutorial, I will guide you through the steps of building a small spam detection application (written in Python).
Many data scientist prefer to use this Python library: Scikit-learn. This library is capable of doing all kinds of Machine Learning magic. So, make sure that you install this library first.
Introduction
The spam detection problem is in fact a text classification problem. An e-mail (a text document) is either “spam” or “no spam”. In text mining, this is called single-label text classification, since there is only one label: “spam”. A classifier is an algorithm that is capable of telling whether a text document is either “spam” or “no spam”. In this article, we first setup a small dataset on which we will train a classifier. Then, we will create a test dataset and view the results. Before we can do all of this, we need to extract features from the texts.
Feature extraction
Take a look at the following e-mails:
$1,000 ALARMING!An appointment on July 2ndNew course content for Text ClassificationBUY VIAGRA!!
1 |
|
So, the burning question is which features should we use? It seems that e-mails with many “!”, “$” or capitals are probably spam e-mails. So, lets create 3 features and lets create our training and test set. The feature vector consists of three entries where the first entry is 1 if there is a “!” in the text (a 0 otherwise). The second entry is 1 if there is a “$” in the text (0 otherwise) and the last entry is the ratio of uppercase characters with respect to the sum of the number of uppercase characters and the number of lowercase characters.
1 |
|
For the feature extraction, we can write the following method:
1 |
|
1 |
|
You might also be interested in text classification using Neural Networks. This article explains what neural networks are and this article shows an advanced implementation of a neural network in Python.
Results
After executing the code, we get the following results:
As you can see, the classifier does the right thing! Now we can classify little spammy e-mail messages.
Exercise
Try to implement more features, like the words used in text messages. For example, the word “VIAGRA” is often used in spam e-mails. Try to classify some more text messages. If you need any help, you can send me a (not so spammy) e-mail message.