Blog

Bayesian Spam Filter

Thomas Bayes

And God said let their be spam. And ever since, there was spam. It seems like spam these days never ends. It is a constant battle with no winners or losers. Sort of like the war on terrorism. But that’s a topic for another day. However, we are not all doomed. At least for now, thanks to Thomas Bayes and his bayesian spam filtering. So how does this bayes theorem work anyways? Let’s say a given spam has the word ‘free’ in it. We all know nothing is free these days. Bayes theorem states the following:

P(A|B) = [ P(B|A) * P(A)  ] /  P(B)
Read as: The probability of A given B is equal to the probability of B given A times the probability of A divided by the probability of B.

In our case lets specialize this formula to spam:
P(S|W) = [ P(W|S) * P(S) ] / [P(W|S) * P(S)] + [P(W|H) * P(H)]

Looks complicated I know. But it really isn’t.

  • P(S|W)  is the probability that a message is a spam, knowing that the word “free” is in it.
  • P(S) is the overall probability that any given message is spam.
  • P(W|S) is the probability that the word “free” appears in spam messages.
  • P(H) is the overall probability that any given message is not spam (aka ham).
  • P(W|H) is the probability that the word “free” appears in ham messages.

Thomas Bayes

But it does get complicated because we are dealing with multiple words. For multiple words the formula gets a little complicated.

P(S) = p(w1) * p(w2) * … / (p(w1) * p(w2)* … ) + (q(w1) * q(w2) * …)

Now that we have the details taken care of lets look at the code to a simple bayesian spam filter written in c++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/***************************************************************************
* Program:
*    Bayesian Spam Filter
*
* Author:
*    Don Page
*
* Summary:
*    This program reads in a hypothetical list of words and frequencies
*    in both spam and ham e-mail messages and then uses Bayesian
*    inference to determine whether hypothetical e-mail messages are spam
*    or not.  The program's judgment may be wrong in some cases, but such
*    is the case with industrial-strength spam filters as well.
******************************************************************************/


#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <ctype.h>

using namespace std;
class Words
{
private:
int numWords;
string words[200];
float spam[200];
float ham[200];
public:
Words();
int getIndex(string pWord);
float getSpam(string pWord);
float getHam(string pWord);
void insertWord(string pWord, float pSpam, float pHam);

};

/******************************************************************************
* Default Constructor
******************************************************************************/

Words::Words()
{
numWords = 0;
}

/******************************************************************************
* INPUT: pWord - Word to insert
*        pSpam - Probability of spam
*        pHam  - Probability of ham
******************************************************************************/

void Words::insertWord(string pWord, float pSpam, float pHam)
{
words[numWords] = pWord;
spam[numWords]  = pSpam;
ham[numWords]   = pHam;
numWords++;
}

/******************************************************************************
* Read words and their probabilities of being ham and spam from file
******************************************************************************/

Words* readWords(ifstream& words)
{
string word;
float spam;
float ham;
Words* myWords = new Words();

while(!words.eof())
{
words >> word;
words >> spam;
words >> ham;
myWords->insertWord(word, spam, ham);
}

return myWords;
}

/******************************************************************************
* Checks if word is inside spam list. Returns prob of spam or -1 if !found
******************************************************************************/

float Words::getSpam(string pWord)
{

int index = getIndex(pWord);
if (index != -1) // found
return spam[index];
else
return -1.0; // not found
}

/******************************************************************************
* Checks if word is inside ham list. Returns prob of ham or -1 if !found
******************************************************************************/

float Words::getHam(string pWord)
{

int index = getIndex(pWord);
if (index != -1) // found
return ham[index];
else
return -1.0; // not found
}

/******************************************************************************
* Finds a given word inside list of words. Returns -1 if not found
******************************************************************************/

int Words::getIndex(string pWord)
{
//Convert string to lowercase
for (int i = 0; i < pWord.length(); i++)
pWord[i] = tolower(pWord[i]);

int i = 0;
for (; words[i] != pWord && i < numWords; i++);

// Check to see if word was found
if (words[i] == pWord)
return i;
else
return -1;
}

/******************************************************************************
* Process each message using Bayes theorem to calculate if message is Spam
* or Ham. See below for Bayes thereom on multiple words.
* P(S) = p(w1) * p(w2) * ... / (p(w1) * p(w2)* ... ) + (q(w1) * q(w2) * ...)
******************************************************************************/

void processMessages(Words* words, ifstream& messages)
{
int message = 1;
string word;

float probSpam;
float probHam;
string cleanWord = "";
messages >> word;
while(!messages.eof())
{

messages >> word; // First word is message
probSpam = 0.0;
probHam = 0.0;
while (word != "MESSAGE" && !messages.eof()) // New message
{

//Parse word
for (int i = 0; i < word.length(); i++)
{
if (isalpha(word[i]))
{
cleanWord += word[i];
}
if (!isalpha(word[i]) || i == word.length() - 1) // Check cleanWord if it's spam
{
if (cleanWord.length() > 0)
{

float temp = words->getSpam(cleanWord);
if (temp > -1.0) // If Spam Calculate new probSpam
probSpam != 0.0 ? probSpam *= temp : probSpam = temp;

temp = words->getHam(cleanWord);
if (temp > -1.0) // If Ham Calculate new probHam
probHam != 0.0 ? probHam *= temp : probHam = temp;
cleanWord = "";

}
}

}// for
messages >> word;
}// while
// Should we reject message?
float threshold = probSpam / (probSpam + probHam);
cout << "Message " << message << " has a " << threshold << " probability of being spam, ";
if (threshold < .9) // Accept
cout << "so let it through.\n\n";
else // Reject
cout << "so reject it.\n\n";
message++;
}
return;
}

/******************************************************************************
* Opens two input files, words.txt and messages.txt, reads in the words and
* their spam/ham frequencies, and with that data processes the messages
* to determine if they (the messages) are spam or not.
*
* DO NOT MODIFY ANYTHING BELOW THIS LINE!
******************************************************************************/

int main(int argc, const char* argv[])
{
// Set decimal precision for output.
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

if (argc < 3)
{
cerr << "Usage: " << argv[0] << " [words file] [messages file]\n";
exit(1);
}

ifstream words(argv[1]);

ifstream messages(argv[2]);

if (words.fail() || messages.fail())
{
cerr << "File opening failed.\n";
exit(1);
}

processMessages(readWords(words), messages);

return 0;
}

 

PC inside Xbox360 Case

Do you have an Xbox360 that is just collecting dust? I decided for my next project to build a PC inside a Xbox 360 case. I knew if I was to take on this project, I would have problems with space. I did not want to buy any extra pc components but rather use what I already had lying around. Mounting the motherboard was probably the hardest part.

RSA Encryption Explained Simply

How RSA Encryption Works

RSA encryption is an Algorithm understood by so few people and used by many. In hopes to help that large percentage understand RSA Encryption better I wrote this explanation. If you ever visit a https site chances are you are using RSA encryption to encrypt or scramble the data sent over the internet. Since you could be sending important information like a credit card number it is imperative that you encrypt the data. The important thing is that we want to do this encryption process without requiring secret keys that both the sender and the recipient must posses. That’s where a system that uses a “Public Key” comes in handy.

Extended Euclidean Algorithm in C++

Writing an Extended Euclidean Calculator that calculates the inverse of a modulus can get pretty difficult. However writing a good algorithm and going through step by step can make the process so much easier.  So we want to find a’ or inverse of a so that a * a’ [=] 1 (mod b). In other words we are trying to find an integer (a’) when multiplied by     a    and then divided by   b   gives you a remainder of   1. In order to find this number(a’), we have to work the Euclidean Algorithm backwards which is referred to as the Extended Euclidean Algorithm.

Modular Exponentiation in C++

Modular Exponentiation is way of calculating the remainder when dividing an integer b (Base) by another integer m (Modulus) raised to the power e(Exponent). Fast modular exponentiation of large numbers is used all the time in RSA to encrypt/decrypt private information over the internet. Whenever you go to a secure site you are using RSA which deals with modular exponentiation.So lets understand modular exponentiation with c++!

Fibonacci Calculator C++

Fibonacci sequence using Linked Lists

The fibonacci sequence is as follows :

0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\;  \ldots.

Each successive number is equal to the sum of the two preceding numbers. If you wanted to find the 5th number of the sequence it would be 5.

F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12
0 1 1 2 3 5 8 13 21 34 55 89 144

This program is implemented with a double linked list. Each Fibonacci number stored as a sequence of integers inside of a list. For example to calculate the 6th number of the Fibonacci sequence it would start out with f1 and f2 lists that have a single node with 1 inside.

Monopoly City Streets Hack

Monopoly City Streets Vulnerability

The first thing I noticed with this online game is how easy it is to hack other accounts. Normally when you forget your password it is a matter of answering a secret question and the password is emailed to the email on the account. However since monopoly city streets does not require an email address to sign up, it is just a matter of guessing the answer to your secret question. What makes it even easier is there is only one secret question! What is your pet’s name? With just a few common pet names, it doesn’t take long for one to answer that question and be able to change the person’s password.

Sudoku Program in C++

Sudoku is one of my favorite games and I really enjoyed writing a sudoku solver. This sudoku procedural program was written in the language c++. The sudoku program allows you to input a board via a text file and allows you to save your progress. If you  get stuck, the program can finish the board. I also spent the time to implement a colored board into the  program. If you don’t understand the rules of sudoku or how to play sudoku then you can go here.

Sudoku Program Output