Using the Enron email data set, we will create a Naive Bayesian network in this simple exercise to classify whether a given email is a spam or ham by looking at its word frequency as feature set.
Mathematics
Definitions
Let's define N to be the number of total emails we have in the dataset and Ns to be the number of spam emails in the email set.
Nso is the number of spam emails that contain the word "offer"
No is the number of emails that contain the word "offer"
Then the probability of having a spam email in the set is said to be:
P(SPAM=1)=NNs
And the probability of having an email that contains the word offer is:
P(OFFER=1)=NNo
Finally, the conditional probability of an email being a spam email given that it contains the word offer:
Postulate
If the probability of finding the word offer given that it's a spam email is higher than that of finding the word offer in a non-spam email:
then we can infer that:
Proof
For abbreviation, let's define that:
Begin with
Rewrite them using Bayes' rule:
The $P(O)$ terms cancel out each other:
By definition, we can rewrite the right hand side as the following:
Re-organize the terms:
Then we can easily see that:
Q.E.D.
Feature Probability
First of all, we load the data into a class object called EmailSet and compute the feature probability for each word that has appeared in the email using FeatureProbability.from_email_set.
from naive_bayes.email_set import EmailSetfrom naive_bayes.email_set import build_and_save_email_setfrom naive_bayes.feature_prob_set import FeatureProbabilitySet# If you haven't pickled it, then runbuild_and_save_email_set()es = EmailSet.get()fps = FeatureProbabilitySet.from_email_set(es)print"Feature probability set has %s ham emails."% fps.class_count.ham_countprint"Feature probability set has %s spam emails."% fps.class_count.spam_count
Dataset already processed!
Feature probability set has 3672 ham emails.
Feature probability set has 1500 spam emails.
Code:20347 with count: {'spam_count': 1, 'ham_count': 0}
Prob ratio: inf
Notice that the word bacterial and compensating have rare occurence in the data set. The probability we compute has a very noisy estimate for their true value. In other words, they are statistically insignificant for us to draw any reliable conclusion. It is not safe to make the assumption that every email with teh word bacterial is a spam email.
Filter Low-reach Features
Let's apply a limit to filter the words that have very low occurence in our data set.
from naive_bayes.feature_prob_selector import FeatureProbabilitySelectorfps = FeatureProbabilitySet.from_email_set(es).filter_low_reach(limit=100)best_spam_features = FeatureProbabilitySelector.best_spam_features(fps)best_ham_features = FeatureProbabilitySelector.best_ham_features(fps)print"Best Spam Features"FeatureProbabilitySelector.print_feature_list(best_spam_features, es.word_encoding_dictionary)print"\n"print"Best Ham Features"FeatureProbabilitySelector.print_feature_list(best_ham_features, es.word_encoding_dictionary)
Two variables are unconditionally independent, if knowing the result of one tells nothing of the other under any circumstance.
For example, let H to be the event of flipping a head, and S to be the event of rolling a 6.
Conditional Independence
The following case is NOT unconditionally independent because it is conditional
Even though the two events are not unconditionally independent, under some cases, aka conditions, they can be independent of each other.
Examples When Unconditional Independence is Violated
Let's go back to the email examples. This is an example of conditional independence.
The two random variables are not independent of each other in this particular condition because:
The presence of the word offer suggests that the email is spam.
If the email is spam, then it is more likely to contain the word limited.
Therefore, the presence of the word offer makes the presence of the word limited more likely.
In conclusion, the words limited and offer are NOT unconditionally independent. They are conditional independent in the sense that in some conditions they are dependent of each other and some conditions they are truly independent.
However if we already knew the email is a spam email, then learning that we have the word offer doesn't add any new knowledge to our estimate of probability of seeing the word limited.
Examples When Conditional Independence is Violated
The words limited and offer often appear together in spam email because they frequently appear as part of the compound phrase a limited time offer. In this sense, the probability of finding one word while other one is present is definitely not independent.
However, if we naively assume independence
It enables us to separate terms for ease of calculation.
Applying The Naive Assumption
We are trying to calculate the probability ratio of the following.
Using Bayes' rule, we can rewrite them as:
Using the naive assumption, we can break the terms apart and simplify the expression
In conclusion,
More Generally Speaking
If we wish to improve the performance of the classifier, we should also include that probability ratio of words that do not appear in the email. For example, in this Enron dataset, the word enron NOT appearing in the email could be a good indicator that the email is spam.
If a word doesn't appear in the text/email, we just need to calculate
the probability of not having the word given an email is spam
the probability of not having the word given an email is ham.
from naive_bayes.naive_bayes_model import NaiveBayesModelfrom naive_bayes.naive_bayes_model import classification_accuracymodel =NaiveBayesModel(fps)ham_scores = model.email_scores(es.ham_emails)spam_scores = model.email_scores(es.spam_emails)cutoff_prob_ratios = [0.01,0.1,1,10,100,1000,10000,100000]for cutoff in cutoff_prob_ratios: result =classification_accuracy(cutoff, ham_scores, spam_scores)print result
Let's split the data and see how well the model performs on unseen data!
training_set, test_set = es.split(0.80)print"Training set has %s ham emails and %s spam emails"% (len(training.ham_emails),len(training.spam_emails))print"Test set has %s ham emails and %s spam emails"% (len(test.ham_emails),len(test.spam_emails))fps = FeatureProbabilitySet.from_email_set(training_set).filter_low_reach(limit=100)model =NaiveBayesModel(fps)ham_scores = model.email_scores(test_set.ham_emails)spam_scores = model.email_scores(test_set.spam_emails)cutoff_prob_ratios = [0.01,0.1,1,10,100,1000,10000,100000]for cutoff in cutoff_prob_ratios: result =classification_accuracy(cutoff, ham_scores, spam_scores)print result
Training set has 3328 ham emails and 1344 spam emails
Test set has 344 ham emails and 156 spam emails
{'true_positive_rate': 0.9901639344262295, 'false_positive_rate': 0.08803301237964237}
{'true_positive_rate': 0.9868852459016394, 'false_positive_rate': 0.08390646492434663}
{'true_positive_rate': 0.9868852459016394, 'false_positive_rate': 0.07702888583218707}
{'true_positive_rate': 0.9836065573770492, 'false_positive_rate': 0.06740027510316368}
{'true_positive_rate': 0.9770491803278688, 'false_positive_rate': 0.0577716643741403}
{'true_positive_rate': 0.9672131147540983, 'false_positive_rate': 0.048143053645116916}
{'true_positive_rate': 0.9377049180327869, 'false_positive_rate': 0.037138927097661624}
{'true_positive_rate': 0.898360655737705, 'false_positive_rate': 0.017881705639614855}
Let's denote the event of having a particular disease to be D, event for showing positive on test 1 for detecting the disease to be T1, and event for showing positive on test 2 for detecting the same disease to be T2.
P(T1∣T2)=P(T1)
Given that we know test 2 is showing a positive result, it does influence the probability of having a positive on test 1, even though test 2 could have been a false positive. It is because a positive result from either tests can influence the probability of having the disease. The tworesults we have from T1 and T2 are connected by the variable D.
P(T1∣D)=P(T1)P(T2∣D)=P(T2)
P(T1∣T2∧D)=P(T1∣D)
This is saying that if the condition of having the disease is satisfied, then the probabilities of T1 and T2 are independent from each other. And equivalently speaking,