<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/naive-bayes-classification-in-r-part-2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://sw23993.wordpress.com/2017/02/17/naive-bayes-classification-in-r-part-2/"> Environmental Science and Data Analytics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Following on from <a target="_blank" rel="nofollow" href="https://wordpress.com/post/sw23993.wordpress.com/693">Part 1</a> of this two-part post, I would now like to explain how the Naive Bayes classifier works before applying it to a classification problem involving breast cancer data. The dataset is sourced from Matjaz Zwitter and Milan Soklic from the Institute of Oncology, University Medical Center in Ljubljana, Slovenia (formerly Yugoslavia) and the attributes are as follows:</p>
<p><strong>age:</strong> a series of ranges from 20-29 to 70-79</p>
<p><strong>menopause:</strong> whether a patient was pre- or post-menopausal upon diagnosis</p>
<p><strong>tumor.size:</strong> the largest diameter (mm) of excised tumor</p>
<p><strong>inv.nodes:</strong> the number of axillary lymph nodes which contained metastatic breast cancer</p>
<p><strong>node.caps:</strong> whether metastatic cancer was contained by the lymph node capsule</p>
<p><strong>deg.malign:</strong> the histological grade of the tumor (1-3 with 3 = highly abnormal cells)</p>
<p><strong>breast:</strong> which breast the cancer occurred in</p>
<p><strong>breast.quad:</strong> region of the breast cancer occurred in (four quadrants with nipple = central)</p>
<p><strong>irradiat:</strong> whether the patient underwent radiation therapy</p>
<p>Some preprocessing of these data was required as there were some NAs (9 in total). I imputed predicted values using separate Naive Bayes classifiers. The objective here is to attempt to predict, using these attributes, with relatively high accuracy whether a recurrence of breast cancer is likely to occur in patients who were previously diagnosed and treated for the disease. We can pursue this objective by using the Naive Bayes classification method.</p>
<h2>Naive Bayes’ Classification</h2>
<p>Below is the Naive Bayes’ Theorem:</p>
<p>P(A | B) = P(A) * P(B | A) / P(B)</p>
<p>Which can be derived from the general multiplication formula for AND events:</p>
<p>P(A and B) = P(A) * P(B | A)</p>
<p>P(B | A) = P(A and B) / P(A)</p>
<p>P(B | A) = P(B) * P(A | B) / P(A)</p>
<p>If I replace the letters with meaningful words as I have been adopting throughout, the Naive Bayes formula becomes:</p>
<p>P(outcome | evidence) = P(outcome) * P(evidence | outcome) / P(evidence)</p>
<p>It is with this formula that the Naive Bayes classifier calculates conditional probabilities for a class outcome given prior information or evidence (our attributes in this case). The reason it is termed “naive” is because we assume independence between attributes when in reality they may be dependent in some way. For the breast cancer dataset we will be working with, some attributes are clearly dependent such as age and menopause status while some may or may not be dependent such as histological grade and tumor size.</p>
<p>This assumption allows us to calculate the probability of the evidence by multiplying the individual probabilities of each piece of evidence occurring together using the simple multiplication rule for independent AND events. Another point to note is that this naivety results in probabilities that are not entirely mathematically correct but they are a good approximation and adequate for the purposes of classification. Indeed, the Naive Bayes classifier has proven to be highly effective and is commonly deployed in email spam filters.</p>
<h2>Calculating Conditional Probabilities</h2>
<p>Conditional probabilities are fundamental to the working of the Naive Bayes formula. Tables of conditional probabilities must be created in order to obtain values to use in the Naive Bayes algorithm. The R package e1071 contains a very nice function for creating a Naive Bayes model:</p>
<pre>library(e1071)
model &lt;- naiveBayes(class ~ ., data = breast_cancer)
class(model)
summary(model)
print(model)</pre>
<p>The model has class “naiveBayes” and the summary tells us that the model provides a-priori probabilities of no-recurrence and recurrence events as well as conditional probability tables across all attributes. To examine the conditional probability tables just print the model.</p>
<p>One of our tasks for this assignment was to create code which would give us the same conditional probabilities as those output by the naiveBayes() function. I went about this in the following way:</p>
<pre>tbl_list &lt;- sapply(breast_cancer[-10], table, breast_cancer[ , 10])
tbl_list &lt;- lapply(tbl_list, t)

cond_probs &lt;- sapply(tbl_list, function(x) { 
  apply(x, 1, function(x) { 
    x / sum(x) }) })

cond_probs &lt;- lapply(cond_probs, t)

print(cond_probs)</pre>
<p>The first line of code uses the sapply function to loop over all attribute variables in the dataset and create tables against the class attribute. I then used the lapply function to transpose all tables in the list so the rows represented the class attribute.</p>
<p>To calculate conditional probabilities for each element in the tables, I used sapply, lapply and anonymous functions. I had to transpose the output in order to get the same structure as the naiveBayes model output. Finally, I printed out my calculated conditional probabilities and compared them with the naiveBayes output to validate the calculations.</p>
<h2>Applying the Naive Bayes’ Classifier</h2>
<p>So I’ve explained (hopefully reasonably well) how the Naive Bayes classifier works based on the fundamental rules of probability. Now it’s time to apply the model to the data. This is easily done in R by using the predict() function.</p>
<pre>preds &lt;- predict(model, newdata = breast_cancer)</pre>
<p>You will see that I have trained the model using the entire dataset and then made predictions on the same dataset. In our assignment we were asked to train the model and test it on the dataset, treating the dataset as an unlabeled test set. This is unconventional as the training set and test set are then identical but I believe the assignment was intended to just test our understanding of how the method works. In practice, one would use a training set for the model to learn from and a test set to assess model accuracy.</p>
<p>If one outcome class is more abundant in the dataset, as is the case with the breast cancer data (no-recurrence: 201, recurrence: 85), the data is unbalanced. This is okay for a generative Naive Bayes model as you want your model to learn from real-world events and to capture the truth. Manipulating the data to achieve less skew would be dangerous.</p>
<p>Applying the model to the data gives the following confusion matrix from which a model accuracy of 75% can be calculated:</p>
<pre>  conf_matrix &lt;- table(preds, breast_cancer$class)</pre>
<p>This post has only scraped the surface of classification methods in machine learning but has been a useful revision for myself and perhaps it may help others new to the Naive Bayes classifier. Please feel free to comment and correct any errors that may be present.</p>
<p> </p>
<p><em>Featured image By Dennis Hill from The OC, So. Cal. – misc 24, CC BY 2.0, <a target="_blank" rel="nofollow" href="https://commons.wikimedia.org/w/index.php?curid=54704175">https://commons.wikimedia.org/w/index.php?curid=54704175</a></em></p>
<p> </p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sw23993.wordpress.com/1197/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/sw23993.wordpress.com/1197/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://sw23993.wordpress.com/2017/02/17/naive-bayes-classification-in-r-part-2/"> Environmental Science and Data Analytics</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/2LeXmyqGikA"></a></div>