\documentclass[11pt]{article}
\usepackage{fullpage}
\usepackage{graphicx}
\usepackage{float}
\usepackage{amssymb,amsmath}
\usepackage[colorlinks,linkcolor=blue,urlcolor=blue,citecolor=black]{hyperref} % Create hyperlinks within the document
\usepackage{url}

\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\usepackage{caption}
\DeclareCaptionType{code}[Code Listing][List of Code Listings] 

\lstset{frame=tb,
  language=python,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true
  tabsize=3
}



%homework
%\long\def\comment#1{}
%solution
\long\def\comment{}

\newcommand{\lit}[1]{\fbox{\texttt{#1}}}

\begin{document}

\title{{\bf CSXXX: NLP/Text Mining for Security}\\
       Homework Assignment \#5:\\
      Spam email classification  }

\author{}

\date{Out: Month date, Year\\
      Due: Month date, Year\\
      (xxxxx needs to be turned-in)}
\maketitle
In this assignment, you will create a Naive Bayes classifier for detecting
e-mail spam, and you will test your classifier on a publicly available spam dataset. You will experiment with three methods for modeling the distribution of features, and you will test your classifier using 10-fold cross-validation.

\textbf{Step 1}: Download the Spambase dataset available from the UCI Machine
Learning Repository.
\url{http://archive.ics.uci.edu/ml/datasets/Spambase}

The Spambase data set consists of 4,601 e-mails, of which 1,813 are spam
(39.4\%). The data set archive contains a processed version of the e-mails wherein 57 real-valued features have been extracted and the spam/non-spam label has been assigned. You should work with this processed version of the data. The data set archive contains a description of the features extracted as well as some simple statistics over those features.

\textbf{Step 2}: Partition the data into 10 folds.

To estimate the generalization (testing) error of your classifier, you will perform cross-validation. In k-fold cross-validation, one would ordinarily partition the data set randomly into k groups of roughly equal size and perform k experiments (the "folds") wherein a model is trained on k-1 of the groups and tested on the remaining group, where each group is used for testing exactly once. (A common value of k is 10.) The generalization error of the classifier is estimated by the average of the performance across all k folds.

While one should perform cross-validation with random partitions, for consistency and comparability of your results, you should partition the data into 10 groups as follows: Consider the 4,601 data points in the order they appear in the processed data file. Each group will consist of every 10th data point in file order, i.e., Group 1 will consist of points {1,11,21,...}, Group 2 will consist of points {2,12,22,...}, ..., and Group 10 will consist of ponts {10,20,30,...}. Finally, Fold k will consist of testing on Group k a model obtained by training on the remaining k-1 groups.

\textbf{Step 3}: Create three Naive Bayes classifiers by modeling the features
in three different ways.
The 57 features are real-valued, and one can model the feature distributions in
simple and complex ways. You will explore the effect of this modeling on overall performance.
\begin{enumerate}
\item Model the features as simple Bernoulli (Boolean) random variables.\\
Consider a threshold such as the overall mean value of the feature (available in
the Spambase documentation), and simply compute the fraction of the time that
the feature value is above or below the overall mean value for each class. In
other words, for feature fi with overall mean value mui, estimate       
\begin{enumerate}
  \item 
$Pr[f_i \leq
mu_i \;|\; \text{spam}]$
  \item  
$Pr[f_i > mu_i\;|\; \text{spam}] $
  \item $Pr[f_i \leq mu_i  \;|\;  \text{non-spam}]$
    \item $Pr[f_i > mu_i \;|\;  \text{non-spam}]$
\end{enumerate}
    and use these estimated
values in your Naive Bayes predictor, as appropriate. (I would suggest using Laplace or Laplace-like smoothing to avoid any issues with zero probabilities, and feel free to experiment with various theshold values, if you like.)

\item 
Model the features as Gaussian random variables, estimating the class conditional mean and variance as appropriate. (Again, I would suggest smoothing your estimate of the variance, to avoid any zero variance issues.)

\item 
Model the feature distribution via a histogram. Bucket the data into a number of
bins and estimate the class conditional probabilities of each bin. For example,
for any feature, consider the following values: min-value, mean-value,
max-value, and the class conditional (spam/non-spam) mean values, one of which
will presumably be lower than the overall mean, and one of which will be higher
than the overall mean. Order these values numerically, and create four feature
value bins as follows    
\begin{enumerate}
  \item  $[$min-value, low-mean-value$]$ 
  \item 
(low-mean-value,
overall-mean-value] 
  \item 
(overall-mean-value, high-mean-value] 
  \item (high-mean-value, max-value] 
  \end{enumerate}
 and estimate the class conditional
probabilities for each of these bins, in a manner similar to that used in the Bernoulli model above. (Again, use Laplace smoothing to avoid any issues with zero probabilities, and feel free to experiment with the number of bins and various theshold values, if you like.)

\end{enumerate}
\textbf{Step 4}: Evaluate your results.
\begin{enumerate}
  \item 
Error tables: For each of your three classifiers, create a table with one
row per fold showing your false positive, false negative, and overall error rates, and add one final row per table corresponding to the average error rates across all folds. For this problem, the false positive rate is the fraction of non-spam testing examples that are misclassified as spam, the false negative rate is the fraction of spam testing examples that are misclassified as non-spam, and the overall error rate is the fraction of overall examples that are misclassified.

 \item 
ROC Curves: In many situations, there is a different cost associated with false positive (Type I) and false negative (Type II) errors. In spam filtering, for example, a false positive error is a legitimate e-mail that is misclassified as spam (and perhaps automatically redirected to a "spam folder" or, worse, auto-deleted) while a false negative is a spam message that is misclassified as legitimate (and sent to one's inbox). Most users are willing to accept some false negative examples so long as very few legitimate e-mails are misclassified.

When using Naive Bayes, one can easily make such trade-offs. For example, in the usual Bayes formulation, one would predict "spam" if

Pr[spam $|$ data] $>$ Pr[non-spam  $|$ data]

or equivalently, in a log-odds formulation,

ln (Pr[spam $|$ data] / Pr[non-spam $|$ data]) $>$ 0.

Note that one could choose to classify an e-mail as spam for any threshold tau

ln (Pr[spam $|$ data] / Pr[non-spam $|$ data]) $>$ $\tau$


where positive values of tau effectively reduce the number of spam classifications, thus decreasing false positives at the expense of increasing false negatives, while negative values of tau have the opposite effect.

One mechanism for visualizing this trade-off is through an ROC curve. (See, for example, the Wikipedia page on ROC curves.) An ROC curve effectively visualizes the true positive (detection) rate vs. the false positive (false alarm) rate for all possible thresholds. (The true positive rate is the fraction of spam messages above threshold; the false positive rate is the fraction of non-spam messages above threshold. Note that the true positive rate is 1 minus the false negative rate.)

One simple way to generate an ROC curve is to sort all m testing points by their log-odds, and for the top k testing points, for all k between 1 and m, calculate the true positive and false positive rates associated with the top k items; plot these points.

Create an ROC curve for each of your classifiers for Fold 1. Preferable draw all three curves on the same plot so that you can compare them.
\item
AUC: An ROC curve visualizes the tradeoff between false positive rate and true positive rate (which is 1 minus the false negative rate) at various operating points. One measure for summarizing this data is to compute the area under the ROC curve or AUC. The AUC, as its name suggests, is simply the area under the ROC curve, which for a perfect curve is 1 and for a random predictor is 1/2. This area has an interesting probabilistic interpretation: it is the chance that the predictor will rank a randomly chosen positive example above a randomly chosen negative example.

The AUC can be calculated fairly simply using the trapezoidal rule for
estimating the area under a curve: If our $m$ ROC data points are

$(x_1, y_1), (x_2, y_2), ..., (x_m, y_m)$

in order, where

$(x_1, y_1) = (0,0)$

and

$(x_m, y_m) = (1,1)$

then the AUC is calculated as follows:

$(1/2) \sum_{k=2}^{m} (x_k - x_{k-1}) (y_k + y_{k-1}).$

Calculate the AUC of your three classifiers.
\end{enumerate}
\textbf{Step 5}: Prepare a report.
   
\end{document}
